fix(archivar): keywords_100 match_keyword → match_keyword_exact in room_map.py (P-108b)

This commit is contained in:
Bernd (Hermes)
2026-08-26 05:00:02 +02:00
parent 275f0673e2
commit f382c8c674
7 changed files with 187 additions and 24 deletions
+5 -5
View File
@@ -31,7 +31,7 @@ from datetime import datetime, timedelta
from pathlib import Path from pathlib import Path
from typing import Optional, Dict, List from typing import Optional, Dict, List
from .keyword_matcher import match_keyword, match_keyword_exact, find_matching_keywords from .keyword_matcher import match_keyword_exact
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -111,8 +111,8 @@ class RoomEntry:
Returns: Returns:
Number of matching keywords (0 if none match). Number of matching keywords (0 if none match).
""" """
# 100%-Keywords: morphological matching (stemming, fuzzy) # 100%-Keywords: exact matching (P-108b — konsistent mit booster.py)
score_100 = sum(1 for kw in self.keywords_100 if match_keyword(kw, text)) score_100 = sum(1 for kw in self.keywords_100 if match_keyword_exact(kw, text))
# Context-Keywords: exact matching only (case-insensitive) # Context-Keywords: exact matching only (case-insensitive)
score_context = sum(1 for kw in self.keywords_context if match_keyword_exact(kw, text)) score_context = sum(1 for kw in self.keywords_context if match_keyword_exact(kw, text))
return score_100 + score_context return score_100 + score_context
@@ -303,7 +303,7 @@ class RoomMap:
List of matching keyword strings. List of matching keyword strings.
""" """
if keyword_type == "100": if keyword_type == "100":
return [kw for kw in room.keywords_100 if match_keyword(kw, text)] return [kw for kw in room.keywords_100 if match_keyword_exact(kw, text)]
else: else:
return [kw for kw in room.keywords_context if match_keyword_exact(kw, text)] return [kw for kw in room.keywords_context if match_keyword_exact(kw, text)]
@@ -485,7 +485,7 @@ class RoomMap:
Used by the router to distinguish 100% keyword matches (auto-route, no Butler) Used by the router to distinguish 100% keyword matches (auto-route, no Butler)
from context keyword matches (Butler asks, learning opportunity). from context keyword matches (Butler asks, learning opportunity).
""" """
return any(match_keyword(kw, text) for kw in room.keywords_100) return any(match_keyword_exact(kw, text) for kw in room.keywords_100)
def calculate_weighted_score(self, text: str, room: RoomEntry) -> float: def calculate_weighted_score(self, text: str, room: RoomEntry) -> float:
""" """
+19 -13
View File
@@ -389,10 +389,14 @@ class TestRoomMapMorphologicalMatching:
]) ])
def test_find_room_plural_keyword(self, room_map): def test_find_room_plural_keyword(self, room_map):
"""'Homelabs' should match #LAN-Dokumentation via 'homelab' keyword.""" """'Homelabs' (Plural) matcht 'homelab' NICHT mehr — P-108b exact matching.
Plural-Formen müssen als eigene keywords_100-Variante eingetragen werden
(P-028/P-108b bewusster Trade-off).
"""
result = room_map.find_room_by_keywords("Homelabs konfigurieren") result = room_map.find_room_by_keywords("Homelabs konfigurieren")
assert result is not None # Plural ist kein exact-Match mehr → kein 100%-Routing auf r_lan.
assert result.room_id == "r_lan" assert result is None or result.room_id != "r_lan"
def test_find_room_dativ_keyword(self, room_map): def test_find_room_dativ_keyword(self, room_map):
"""'dem Homelab' should match via 'homelab' keyword.""" """'dem Homelab' should match via 'homelab' keyword."""
@@ -401,10 +405,9 @@ class TestRoomMapMorphologicalMatching:
assert result.room_id == "r_lan" assert result.room_id == "r_lan"
def test_find_room_plural_dokumentation(self, room_map): def test_find_room_plural_dokumentation(self, room_map):
"""'Dokumentationen' should match via 'dokumentation' keyword.""" """'Dokumentationen' matcht 'dokumentation' NICHT mehr — P-108b exact matching."""
result = room_map.find_room_by_keywords("Dokumentationen aktualisieren") result = room_map.find_room_by_keywords("Dokumentationen aktualisieren")
assert result is not None assert result is None or result.room_id != "r_lan"
assert result.room_id == "r_lan"
def test_find_room_compound_ddp(self, room_map): def test_find_room_compound_ddp(self, room_map):
"""'DDP-WebSocket' should match #RC-Plugin via 'ddp' keyword.""" """'DDP-WebSocket' should match #RC-Plugin via 'ddp' keyword."""
@@ -413,12 +416,15 @@ class TestRoomMapMorphologicalMatching:
assert result.room_id == "r_rc" assert result.room_id == "r_rc"
def test_is_100_percent_match_plural(self, room_map): def test_is_100_percent_match_plural(self, room_map):
"""is_100_percent_match should use morphological matching.""" """is_100_percent_match nutzt exact matching — Plural matcht NICHT mehr (P-108b)."""
lan_room = room_map.get_room_by_id("r_lan") lan_room = room_map.get_room_by_id("r_lan")
assert lan_room is not None assert lan_room is not None
assert room_map.is_100_percent_match("Homelabs", lan_room) is True # Singular (exact) bleibt True
assert room_map.is_100_percent_match("Dokumentationen", lan_room) is True assert room_map.is_100_percent_match("Homelab", lan_room) is True
assert room_map.is_100_percent_match("Netzwerke", lan_room) is True # Plural/Stemming-Formen sind kein 100%-Match mehr (P-028/P-108b)
assert room_map.is_100_percent_match("Homelabs", lan_room) is False
assert room_map.is_100_percent_match("Dokumentationen", lan_room) is False
assert room_map.is_100_percent_match("Netzwerke", lan_room) is False
def test_is_100_percent_match_false_positive_prevention(self, room_map): def test_is_100_percent_match_false_positive_prevention(self, room_map):
"""is_100_percent_match should NOT match semantically different words.""" """is_100_percent_match should NOT match semantically different words."""
@@ -463,10 +469,10 @@ class TestRoomEntryMatchScore:
keywords_100=["homelab", "dokumentation"], keywords_100=["homelab", "dokumentation"],
keywords_context=["docker"], keywords_context=["docker"],
) )
# 'Homelabs' → match 'homelab' (1), 'Dokumentationen' → match 'dokumentation' (1) # P-108b exact matching: 'Homelabs'/'Dokumentationen' sind KEINE
# 'Docker' → match 'docker' (1) = total 3 # 100%-Matches mehr. Nur 'Docker' (context, exact) matcht → 1.
score = entry.match_score("Homelabs und Dokumentationen mit Docker") score = entry.match_score("Homelabs und Dokumentationen mit Docker")
assert score == 3 assert score == 1
def test_match_score_no_false_positive(self): def test_match_score_no_false_positive(self):
entry = RoomEntry( entry = RoomEntry(
@@ -277,7 +277,7 @@ class TestP108aTopicMismatch(unittest.TestCase):
self._mock_route_to("room_lan_doku", "#LAN-Doku") self._mock_route_to("room_lan_doku", "#LAN-Doku")
asyncio.run(self.adapter._process_incoming( asyncio.run(self.adapter._process_incoming(
self._msg("Bitte dokumentiere das neue Feature", "room_rc_plugin") self._msg("Bitte die dokumentation aktualisieren", "room_rc_plugin")
)) ))
# Archivar wurde aufgerufen (Topic-Mismatch → _should_classify bleibt True). # Archivar wurde aufgerufen (Topic-Mismatch → _should_classify bleibt True).
@@ -301,7 +301,7 @@ class TestP108aTopicMismatch(unittest.TestCase):
self._mock_route_to("room_lan_doku", "#LAN-Doku") self._mock_route_to("room_lan_doku", "#LAN-Doku")
asyncio.run(self.adapter._process_incoming( asyncio.run(self.adapter._process_incoming(
self._msg("Bitte dokumentiere das neue Feature", "room_rc_plugin") self._msg("Bitte die dokumentation aktualisieren", "room_rc_plugin")
)) ))
# Archivar wurde aufgerufen — Routing ist erlaubt (kein Bypass). # Archivar wurde aufgerufen — Routing ist erlaubt (kein Bypass).
@@ -0,0 +1,157 @@
"""
P-108b — Wahrheitsquellen-Divergenz keywords_100-Matcher.
room_map.py nutzte ``match_keyword`` (Fuzzy/Stemming) für ``keywords_100``,
während booster.py bereits ``match_keyword_exact`` nutzt (P-028-Mitigation,
Commit 374e2e7). Zwei Pfade für dieselbe Frage → einer ist per Definition
falsch.
Fix (Rainer APPROVED): keywords_100 in room_map.py auf
``match_keyword_exact`` umstellen. keywords_context bleibt unverändert
(bereits exact).
TDD-Anker:
- Szenario B (Regression-Guard): hypheniertes Keyword ``routing-target``
MUSS weiterhin als keywords_100-Match erkannt werden.
- Divergenz-Fix (RED→GREEN): Fuzzy-False-Positive wie ``homelabor``↔``homelab``
oder ``firewall``↔``firewaller`` dürfen NICHT mehr über den 100%-Pfad
matchen (konsistent mit booster.py).
"""
from __future__ import annotations
import json
import sys
import tempfile
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from plugin.archivar.room_map import RoomMap, RoomEntry
def _load_map(rooms: list[dict]) -> RoomMap:
"""Build a RoomMap from a list of room dicts (keywords_100/context)."""
data = {
"version": 2,
"rooms": {},
"excluded_rooms": [],
"fact_store_path": "/tmp/test_docs",
}
for r in rooms:
data["rooms"][r["room_id"]] = {
"name": r.get("name", r["room_id"]),
"theme": r.get("theme", ""),
"keywords_100": r.get("keywords_100", []),
"keywords_context": r.get("keywords_context", []),
"catch_all": r.get("catch_all", False),
"user_visible": r.get("user_visible", True),
}
tmp = tempfile.NamedTemporaryFile(
mode="w", suffix=".json", delete=False, encoding="utf-8"
)
tmp.write(json.dumps(data))
tmp.close()
path = Path(tmp.name)
try:
return RoomMap.load(path)
finally:
path.unlink(missing_ok=True)
@pytest.fixture
def room_map() -> RoomMap:
return _load_map(
[
{
"room_id": "r_target",
"name": "#test-rc-target",
"theme": "routing target test",
"keywords_100": ["routing-target"],
"keywords_context": [],
},
{
"room_id": "r_lan",
"name": "#LAN-Dokumentation",
"theme": "LAN docs",
"keywords_100": ["homelab", "dokumentation", "netzwerk"],
"keywords_context": ["docker"],
},
{
"room_id": "r_admin",
"name": "DM Admin",
"theme": "admin",
"keywords_100": [],
"keywords_context": [],
"catch_all": True,
},
]
)
class TestP108bRoutingTargetHyphen:
"""Szenario B — hyphenierte Keywords müssen 100%-Matches bleiben."""
def test_routing_target_hyphen_is_100_percent_match(self, room_map):
"""'routing-target Konfiguration' muss keyword_100-Match ergeben."""
target = room_map.get_room_by_id("r_target")
assert target is not None
assert room_map.is_100_percent_match("routing-target Konfiguration", target) is True
def test_routing_target_find_room(self, room_map):
"""find_room_by_keywords muss Szenario B an den Zielraum routen."""
result = room_map.find_room_by_keywords("routing-target Konfiguration")
assert result is not None
assert result.room_id == "r_target"
def test_routing_target_match_score(self, room_map):
"""match_score zählt das hyphenierte Keyword als 100%-Treffer."""
target = room_map.get_room_by_id("r_target")
assert target is not None
assert target.match_score("routing-target Konfiguration") >= 1
class TestP108bFuzzyDivergenceFix:
"""RED→GREEN: Fuzzy-False-Positives dürfen nicht mehr 100%-matchen."""
def test_homelabor_no_longer_100_matches_homelab(self, room_map):
"""'homelabor' darf NICHT mehr als 'homelab' 100%-matchen (P-028)."""
lan = room_map.get_room_by_id("r_lan")
assert lan is not None
assert room_map.is_100_percent_match("homelabor", lan) is False
def test_firewaller_no_longer_100_matches_firewall(self):
"""'firewaller' darf NICHT mehr als 'firewall' 100%-matchen."""
m = _load_map(
[
{
"room_id": "r_fw",
"name": "#Netz",
"keywords_100": ["firewall"],
"keywords_context": [],
},
{"room_id": "r_admin", "name": "DM Admin", "catch_all": True},
]
)
fw = m.get_room_by_id("r_fw")
assert fw is not None
assert m.is_100_percent_match("firewaller", fw) is False
def test_homelabor_not_routed_via_fuzzy(self, room_map):
"""'homelabor' darf find_room_by_keywords NICHT via Fuzzy routen."""
result = room_map.find_room_by_keywords("homelabor")
assert result is None or result.room_id != "r_lan"
def test_exact_match_still_works(self, room_map):
"""Exakter Treffer (Singular) bleibt ein 100%-Match."""
lan = room_map.get_room_by_id("r_lan")
assert lan is not None
assert room_map.is_100_percent_match("homelab", lan) is True
def test_case_insensitive_100_match(self, room_map):
"""Case-Insensitivity bleibt erhalten (exact ist case-insensitive)."""
lan = room_map.get_room_by_id("r_lan")
assert lan is not None
assert room_map.is_100_percent_match("HOMELAB", lan) is True
+1 -1
View File
@@ -207,7 +207,7 @@ class TestKeyword100Route:
router = _make_router(multi_room_map) router = _make_router(multi_room_map)
decision = await router.route( decision = await router.route(
"Bitte dokumentiere das neue Feature", "Bitte die dokumentation aktualisieren",
origin_room_id="room_rc_plugin", origin_room_id="room_rc_plugin",
) )
+2 -2
View File
@@ -346,11 +346,11 @@ class TestSonyContextKeyword:
router = _make_router(room_map) router = _make_router(room_map)
decision = asyncio.run(router.route( decision = asyncio.run(router.route(
"Bitte dokumentiere das neue Feature", "Bitte die dokumentation aktualisieren",
origin_room_id="room_rc_plugin", origin_room_id="room_rc_plugin",
)) ))
# 'dokumentiere' matches 'dokumentation' (100% keyword for #LAN-Doku) # 'dokumentation' matches (100% keyword for #LAN-Doku)
assert decision.target_room == "room_lan_doku", ( assert decision.target_room == "room_lan_doku", (
f"Expected target_room='room_lan_doku', got {decision.target_room}" f"Expected target_room='room_lan_doku', got {decision.target_room}"
) )
+1 -1
View File
@@ -460,7 +460,7 @@ class TestRegression:
router = _make_router(room_map) router = _make_router(room_map)
decision = asyncio.run(router.route( decision = asyncio.run(router.route(
"Bitte dokumentiere das neue Feature", "Bitte die dokumentation aktualisieren",
origin_room_id="room_rc_plugin", origin_room_id="room_rc_plugin",
)) ))