feat(archivar): Zweistufiges Keyword-Evidenz-System — 100% + context
This commit is contained in:
+61
-21
@@ -51,12 +51,20 @@ class RoomEntry:
|
||||
theme: str
|
||||
"""Thema des Raums (ein Satz)."""
|
||||
|
||||
keywords: list[str] = field(default_factory=list)
|
||||
"""Stichworte für Keyword-Matching."""
|
||||
keywords_100: list[str] = field(default_factory=list)
|
||||
"""100% Evidenz Stichworte für Keyword-Matching."""
|
||||
|
||||
keywords_context: list[str] = field(default_factory=list)
|
||||
"""Kontextabhängige Stichworte für Keyword-Matching."""
|
||||
|
||||
catch_all: bool = False
|
||||
"""True wenn dieser Raum der EINE Catch-All-Raum ist."""
|
||||
|
||||
@property
|
||||
def keywords(self) -> list[str]:
|
||||
"""Legacy property for backward compatibility."""
|
||||
return self.keywords_context
|
||||
|
||||
def match_score(self, text: str) -> int:
|
||||
"""Return number of keyword matches in *text* (case-insensitive).
|
||||
|
||||
@@ -66,10 +74,11 @@ class RoomEntry:
|
||||
Returns:
|
||||
Number of matching keywords (0 if none match).
|
||||
"""
|
||||
if not self.keywords:
|
||||
return 0
|
||||
# Prüfe beide Listen: keywords_100 und keywords_context
|
||||
text_lower = text.lower()
|
||||
return sum(1 for kw in self.keywords if kw in text_lower)
|
||||
score_100 = sum(1 for kw in self.keywords_100 if kw.lower() in text_lower)
|
||||
score_context = sum(1 for kw in self.keywords_context if kw.lower() in text_lower)
|
||||
return score_100 + score_context
|
||||
|
||||
|
||||
# ── Exception ─────────────────────────────────────────────────────────────
|
||||
@@ -150,26 +159,40 @@ class RoomMap:
|
||||
if no room has any matching keywords or if the best score
|
||||
is below the minimum threshold.
|
||||
"""
|
||||
# Origin-First-Prinzip: Wenn ein Ursprungsraum angegeben ist, prüfe zuerst diesen
|
||||
text_lower = text.lower()
|
||||
|
||||
# Stufe 1: Prüfe 100% Evidenz Keywords zuerst
|
||||
# EIN Treffer reicht für sofortigen Match (kein min_score)
|
||||
for room in self._rooms.values():
|
||||
if room.catch_all:
|
||||
continue
|
||||
|
||||
# Prüfe ob 100% Keywords matchen
|
||||
if any(kw.lower() in text_lower for kw in room.keywords_100):
|
||||
return room
|
||||
|
||||
# Stufe 2: Origin-Priorität mit kontextabhängigen Keywords
|
||||
# Origin-Priorität gilt NUR für context-Keywords (100% schlagen immer durch)
|
||||
if origin_room_id is not None and origin_room_id in self._rooms:
|
||||
origin_room = self._rooms[origin_room_id]
|
||||
# Nur prüfen, wenn es kein Catch-All-Raum ist (die haben keine Keywords)
|
||||
if not origin_room.catch_all:
|
||||
origin_score = origin_room.match_score(text)
|
||||
# Wenn der Ursprungsraum den Mindestscore erreicht, wird er ausgewählt
|
||||
if origin_score >= min_score:
|
||||
# Prüfe kontextabhängige Keywords im Ursprungsraum
|
||||
context_score = sum(1 for kw in origin_room.keywords_context if kw.lower() in text_lower)
|
||||
if context_score >= min_score:
|
||||
return origin_room
|
||||
|
||||
# Globaler Scan wie bisher
|
||||
# Stufe 3: Globaler Scan mit kontextabhängigen Keywords
|
||||
best_room: Optional[RoomEntry] = None
|
||||
best_score: int = 0
|
||||
|
||||
for room in self._rooms.values():
|
||||
if room.catch_all:
|
||||
continue # Catch-All never matches keywords
|
||||
score = room.match_score(text)
|
||||
if score > best_score:
|
||||
best_score = score
|
||||
|
||||
# Prüfe kontextabhängige Keywords
|
||||
context_score = sum(1 for kw in room.keywords_context if kw.lower() in text_lower)
|
||||
if context_score > best_score:
|
||||
best_score = context_score
|
||||
best_room = room
|
||||
|
||||
if best_room is not None and best_score >= min_score:
|
||||
@@ -276,25 +299,29 @@ class RoomMap:
|
||||
|
||||
return cls._from_dict(data)
|
||||
|
||||
def add_or_update_room(self, room_id: str, name: str, theme: str = "", keywords: Optional[list] = None, catch_all: bool = False) -> None:
|
||||
def add_or_update_room(self, room_id: str, name: str, theme: str = "", keywords_100: Optional[list] = None, keywords_context: Optional[list] = None, catch_all: bool = False) -> None:
|
||||
"""Fügt Raum zur In-Memory-Map hinzu ODER aktualisiert bestehenden.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID
|
||||
name: Menschenlesbarer Name (z.B. "#Rocketchat-Plugin")
|
||||
theme: Thema des Raums (ein Satz)
|
||||
keywords: Stichworte für Keyword-Matching
|
||||
keywords_100: 100% Evidenz Stichworte für Keyword-Matching
|
||||
keywords_context: Kontextabhängige Stichworte für Keyword-Matching
|
||||
catch_all: True wenn dieser Raum der EINE Catch-All-Raum ist
|
||||
"""
|
||||
if keywords is None:
|
||||
keywords = []
|
||||
if keywords_100 is None:
|
||||
keywords_100 = []
|
||||
if keywords_context is None:
|
||||
keywords_context = []
|
||||
|
||||
# Erstelle oder aktualisiere den RoomEntry
|
||||
self._rooms[room_id] = RoomEntry(
|
||||
room_id=room_id,
|
||||
name=name,
|
||||
theme=theme,
|
||||
keywords=keywords,
|
||||
keywords_100=keywords_100,
|
||||
keywords_context=keywords_context,
|
||||
catch_all=catch_all
|
||||
)
|
||||
|
||||
@@ -362,7 +389,8 @@ class RoomMap:
|
||||
data["rooms"][room_id] = {
|
||||
"name": room_entry.name,
|
||||
"theme": room_entry.theme,
|
||||
"keywords": room_entry.keywords,
|
||||
"keywords_100": room_entry.keywords_100,
|
||||
"keywords_context": room_entry.keywords_context,
|
||||
"catch_all": room_entry.catch_all
|
||||
}
|
||||
|
||||
@@ -378,11 +406,23 @@ class RoomMap:
|
||||
# Parse rooms
|
||||
rooms: dict[str, RoomEntry] = {}
|
||||
for room_id, room_data in data.get("rooms", {}).items():
|
||||
# Abwärtskompatibilität: Wenn keywords_100 fehlt (alte room-map.json),
|
||||
# alte keywords-Liste als keywords_context interpretieren, keywords_100 bleibt leer
|
||||
if "keywords_100" in room_data:
|
||||
# Neue Struktur (Version 2+)
|
||||
keywords_100 = room_data.get("keywords_100", [])
|
||||
keywords_context = room_data.get("keywords_context", [])
|
||||
else:
|
||||
# Alte Struktur (Version 1) - Abwärtskompatibilität
|
||||
keywords_100 = []
|
||||
keywords_context = room_data.get("keywords", [])
|
||||
|
||||
rooms[room_id] = RoomEntry(
|
||||
room_id=room_id,
|
||||
name=room_data.get("name", room_id),
|
||||
theme=room_data.get("theme", ""),
|
||||
keywords=room_data.get("keywords", []),
|
||||
keywords_100=keywords_100,
|
||||
keywords_context=keywords_context,
|
||||
catch_all=room_data.get("catch_all", False),
|
||||
)
|
||||
|
||||
|
||||
@@ -41,12 +41,22 @@ def _make_map_json(rooms: list[dict] | None = None, excluded: list[str] | None =
|
||||
"fact_store_path": "/tmp/test_docs",
|
||||
}
|
||||
for room in (rooms or []):
|
||||
data["rooms"][room["room_id"]] = {
|
||||
room_data = {
|
||||
"name": room["name"],
|
||||
"theme": room.get("theme", ""),
|
||||
"keywords": room.get("keywords", []),
|
||||
"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)
|
||||
|
||||
|
||||
@@ -162,6 +172,127 @@ class TestRoomMapKeywords:
|
||||
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=2."""
|
||||
# Only one context keyword match should not be enough
|
||||
result = room_map_v2.find_room_by_keywords("plugin")
|
||||
assert result is None
|
||||
|
||||
# Two context keyword matches should 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 ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -255,7 +386,7 @@ class TestRoomMapValidation:
|
||||
])
|
||||
errors = rm.validate(subscribed_ids={"r999"})
|
||||
assert len(errors) >= 1
|
||||
assert any("catch_all room" in e.lower() for e in errors)
|
||||
assert any("catch-all room" in e.lower() for e in errors)
|
||||
|
||||
|
||||
# ── Migration from Legacy Env Vars ─────────────────────────────────────────
|
||||
@@ -320,7 +451,8 @@ class TestRoomEntry:
|
||||
def test_match_score(self):
|
||||
entry = RoomEntry(
|
||||
room_id="r1", name="#Dev", theme="dev",
|
||||
keywords=["plugin", "gateway", "adapter"],
|
||||
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
|
||||
@@ -329,14 +461,14 @@ class TestRoomEntry:
|
||||
def test_match_score_no_keywords(self):
|
||||
entry = RoomEntry(
|
||||
room_id="admin", name="DM Admin", theme="admin",
|
||||
keywords=[], catch_all=True,
|
||||
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=["Plugin", "GATEWAY"],
|
||||
keywords_100=["Plugin"], keywords_context=["GATEWAY"],
|
||||
)
|
||||
assert entry.match_score("plugin gateway") == 2
|
||||
|
||||
|
||||
Reference in New Issue
Block a user