feat(Phase1/B): user_visible Flag — Auto-Route User-Zugriff-Schutz

Schema-Erweiterung: Jeder Raum in room-map.json bekommt ein user_visible Flag
(Default: true, abwärtskompatibel).

- RoomEntry.user_visible: bool = True (neues Feld)
- room_map.py find_room_by_keywords(): filtert user_visible=false Räume aus
  allen drei Stufen (100%-Keywords, Origin-Priorität, Kontext-Keywords)
- room_map.py is_user_visible(): neue Helper-Methode
- room_map.py _from_dict()/save(): Serialisierung/Deserialisierung des Flags
- onboarding.py check_room_map_completeness(): user_visible=false Räume
  werden NICHT als missing_rooms gemeldet (kein Onboarding-Trigger)

Tests: test_user_visible.py (9 Tests) — Routing-Filter, Default-true,
Onboarding-Ignore, Persistenz.
This commit is contained in:
Bernd (Hermes)
2026-08-20 15:58:10 +02:00
parent 6f430dc4dc
commit a51a9bb4c3
3 changed files with 259 additions and 6 deletions
+13
View File
@@ -475,8 +475,21 @@ def check_room_map_completeness(
return [] return []
# Normale Prüfung: Welche relevanten Räume fehlen in der Map? # Normale Prüfung: Welche relevanten Räume fehlen in der Map?
# Auto-Route User-Zugriff-Schutz (Phase 1/B): Räume mit user_visible=false
# werden NICHT als missing gemeldet (kein Onboarding-Trigger). Testräume
# und Räume ohne User-Zugriff lösen kein Auto-Onboarding aus.
invisible_room_ids = {
rid for rid, entry in room_map.rooms.items() if not entry.user_visible
}
missing = [] missing = []
for room_id, room_info in relevant_rooms.items(): for room_id, room_info in relevant_rooms.items():
if room_id in invisible_room_ids:
logger.info(
"check_room_map_completeness: Raum '%s' ist user_visible=false "
"— kein Onboarding-Trigger",
room_info.get("name", room_id),
)
continue
if room_id not in room_map.rooms: if room_id not in room_map.rooms:
missing.append({"room_id": room_id, "name": room_info["name"]}) missing.append({"room_id": room_id, "name": room_info["name"]})
+35
View File
@@ -77,6 +77,16 @@ class RoomEntry:
active_status_indikator: bool = True active_status_indikator: bool = True
"""V8.6: Aktivitäts-Indikator — Bot-Status automatisch anzeigen (PresenceEngine).""" """V8.6: Aktivitäts-Indikator — Bot-Status automatisch anzeigen (PresenceEngine)."""
user_visible: bool = True
"""Auto-Route User-Zugriff-Schutz (Phase 1/B): Sichtbarkeits-Flag.
- ``True`` (Default): Raum ist Routing-Ziel und Onboarding-relevant.
- ``False``: Raum wird NICHT als Routing-Ziel verwendet und triggert
KEIN Onboarding (kein ``missing_rooms``-Eintrag).
Abwärtskompatibel: Räume ohne Flag (alte room-map.json) sind sichtbar.
"""
# V8.2: Keyword-Tracking für Lern-Persistenz und Demotion # V8.2: Keyword-Tracking für Lern-Persistenz und Demotion
_keyword_last_matched: Dict[str, str] = field(default_factory=dict) _keyword_last_matched: Dict[str, str] = field(default_factory=dict)
"""Mapping keyword → ISO timestamp des letzten Matches (für Demotion).""" """Mapping keyword → ISO timestamp des letzten Matches (für Demotion)."""
@@ -397,6 +407,10 @@ class RoomMap:
for room in self._rooms.values(): for room in self._rooms.values():
if room.catch_all: if room.catch_all:
continue continue
# Auto-Route User-Zugriff-Schutz (Phase 1/B): user_visible=false
# Räume sind keine Routing-Kandidaten.
if not room.user_visible:
continue
matched = self._get_matched_keywords(room, text, "100") matched = self._get_matched_keywords(room, text, "100")
score_100 = len(matched) score_100 = len(matched)
@@ -420,6 +434,9 @@ class RoomMap:
# V8.4.6: Catch-All-Räume sind in Stufe 2 als Butler-Ziele erlaubt # V8.4.6: Catch-All-Räume sind in Stufe 2 als Butler-Ziele erlaubt
if origin_room_id is not None and origin_room_id in self._rooms: if origin_room_id is not None and origin_room_id in self._rooms:
origin_room = self._rooms[origin_room_id] origin_room = self._rooms[origin_room_id]
# Auto-Route User-Zugriff-Schutz (Phase 1/B): user_visible=false
# Räume sind keine Routing-Kandidaten (auch nicht als Origin-Ziel).
if origin_room.user_visible:
# Prüfe kontextabhängige Keywords im Ursprungsraum # Prüfe kontextabhängige Keywords im Ursprungsraum
# (auch Catch-All-Räume — sie können Kontext-Keywords haben) # (auch Catch-All-Räume — sie können Kontext-Keywords haben)
# Context-Keywords: exaktes Matching (kein Stemming/Fuzzy) # Context-Keywords: exaktes Matching (kein Stemming/Fuzzy)
@@ -437,6 +454,10 @@ class RoomMap:
best_matched: list[str] = [] best_matched: list[str] = []
for room in self._rooms.values(): for room in self._rooms.values():
# Auto-Route User-Zugriff-Schutz (Phase 1/B): user_visible=false
# Räume sind keine Routing-Kandidaten.
if not room.user_visible:
continue
matched = self._get_matched_keywords(room, text, "context") matched = self._get_matched_keywords(room, text, "context")
context_score = len(matched) context_score = len(matched)
@@ -493,6 +514,18 @@ class RoomMap:
"""True if *room_id* is in the excluded list (e.g. Multi-Agent-Raum).""" """True if *room_id* is in the excluded list (e.g. Multi-Agent-Raum)."""
return room_id in self._excluded_room_ids return room_id in self._excluded_room_ids
def is_user_visible(self, room_id: str) -> bool:
"""True if *room_id* is user-visible (routing + onboarding relevant).
Auto-Route User-Zugriff-Schutz (Phase 1/B): Räume mit
``user_visible=False`` sind weder Routing-Ziel noch Onboarding-relevant.
Unbekannte room_id → False (konservativ: nicht sichtbar).
"""
entry = self._rooms.get(room_id)
if entry is None:
return False
return entry.user_visible
def get_room_by_id(self, room_id: str) -> Optional[RoomEntry]: def get_room_by_id(self, room_id: str) -> Optional[RoomEntry]:
"""Hole einen Raum anhand seiner ID. """Hole einen Raum anhand seiner ID.
@@ -717,6 +750,7 @@ class RoomMap:
"keywords_context": room_entry.keywords_context, "keywords_context": room_entry.keywords_context,
"catch_all": room_entry.catch_all, "catch_all": room_entry.catch_all,
"active_status_indikator": room_entry.active_status_indikator, "active_status_indikator": room_entry.active_status_indikator,
"user_visible": room_entry.user_visible,
# V8.2.1 A3: Persistiere Tracking-Felder # V8.2.1 A3: Persistiere Tracking-Felder
"_stay_counts": room_entry._stay_counts, "_stay_counts": room_entry._stay_counts,
"_keyword_last_matched": room_entry._keyword_last_matched, "_keyword_last_matched": room_entry._keyword_last_matched,
@@ -1135,6 +1169,7 @@ class RoomMap:
keywords_context=keywords_context, keywords_context=keywords_context,
catch_all=room_data.get("catch_all", False), catch_all=room_data.get("catch_all", False),
active_status_indikator=room_data.get("active_status_indikator", True), active_status_indikator=room_data.get("active_status_indikator", True),
user_visible=room_data.get("user_visible", True),
) )
# V8.2.1 A3: Tracking-Felder aus JSON deserialisieren # V8.2.1 A3: Tracking-Felder aus JSON deserialisieren
if "_stay_counts" in room_data: if "_stay_counts" in room_data:
+205
View File
@@ -0,0 +1,205 @@
"""Tests für Auto-Route User-Zugriff-Schutz — Phase 1 (B): user_visible Flag.
Prüft:
- test_user_visible_false_not_routed: Raum mit user_visible=false wird
nicht als Routing-Ziel verwendet.
- test_user_visible_default_true: Raum ohne Flag ist Routing-Ziel (Default true).
- test_onboarding_ignores_user_visible_false: Onboarding ignoriert
user_visible=false Räume (kein missing_rooms-Eintrag).
"""
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
from plugin.archivar.onboarding import check_room_map_completeness
# ── Helpers ────────────────────────────────────────────────────────────────
def _make_map(rooms: list[dict]) -> RoomMap:
"""Baut eine RoomMap aus einer Liste von Raum-Dicts (mit room_id)."""
data: dict = {
"version": 2,
"rooms": {},
"excluded_rooms": [],
"fact_store_path": "/tmp/test_docs",
}
for room in rooms:
rid = room.pop("room_id")
data["rooms"][rid] = room
return RoomMap._from_dict(data)
def _room(room_id: str, name: str, keywords_100: list[str], **kwargs) -> dict:
"""Baut ein Raum-Dict für _make_map."""
d = {
"room_id": room_id,
"name": name,
"theme": name,
"keywords_100": keywords_100,
"keywords_context": [],
"catch_all": False,
}
d.update(kwargs)
return d
# ── Phase 1 (B): user_visible Flag ─────────────────────────────────────────
class TestUserVisibleRouting:
"""find_room_by_keywords() respektiert user_visible=false."""
def test_user_visible_false_not_routed(self):
"""Raum mit user_visible=false wird nicht als Routing-Ziel verwendet."""
room_map = _make_map([
_room("r_visible", "#Sichtbar", ["plugin"]),
_room("r_hidden", "#Versteckt", ["plugin"], user_visible=False),
_room("r_catchall", "#CatchAll", [], catch_all=True),
])
# Beide Räume haben das Keyword "plugin" — aber r_hidden ist unsichtbar.
result = room_map.find_room_by_keywords("Das Plugin hat einen Bug")
assert result is not None
assert result.room_id == "r_visible"
assert result.room_id != "r_hidden"
def test_user_visible_false_only_match_returns_none(self):
"""Wenn NUR der unsichtbare Raum matcht, gibt es kein Routing-Ziel."""
room_map = _make_map([
_room("r_hidden", "#Versteckt", ["plugin"], user_visible=False),
_room("r_catchall", "#CatchAll", [], catch_all=True),
])
result = room_map.find_room_by_keywords("Das Plugin hat einen Bug")
assert result is None
def test_user_visible_default_true(self):
"""Raum ohne Flag ist Routing-Ziel (Default true)."""
room_map = _make_map([
_room("r_plain", "#OhneFlag", ["plugin"]),
_room("r_catchall", "#CatchAll", [], catch_all=True),
])
result = room_map.find_room_by_keywords("Das Plugin hat einen Bug")
assert result is not None
assert result.room_id == "r_plain"
def test_user_visible_false_context_keyword_not_routed(self):
"""user_visible=false filtert auch Kontext-Keywords (Stufe 3)."""
room_map = _make_map([
_room("r_hidden", "#Versteckt", [], keywords_context=["adapter"],
user_visible=False),
_room("r_catchall", "#CatchAll", [], catch_all=True),
])
result = room_map.find_room_by_keywords("Der Adapter ist kaputt")
assert result is None
def test_is_user_visible_helper(self):
"""is_user_visible() liefert korrekte Werte."""
room_map = _make_map([
_room("r_visible", "#Sichtbar", []),
_room("r_hidden", "#Versteckt", [], user_visible=False),
_room("r_catchall", "#CatchAll", [], catch_all=True),
])
assert room_map.is_user_visible("r_visible") is True
assert room_map.is_user_visible("r_hidden") is False
assert room_map.is_user_visible("r_catchall") is True
assert room_map.is_user_visible("unbekannt") is False
class TestUserVisibleOnboarding:
"""check_room_map_completeness() ignoriert user_visible=false Räume."""
def test_onboarding_ignores_user_visible_false(self):
"""Räume mit user_visible=false werden nicht als missing gemeldet."""
room_map = _make_map([
_room("r_hidden", "#Testraum", [], user_visible=False),
_room("r_catchall", "#CatchAll", [], catch_all=True),
])
subscribed = {
"r_hidden": {"name": "#Testraum", "type": "c"},
"r_new": {"name": "#NeuerRaum", "type": "c"},
}
missing = check_room_map_completeness(
room_map=room_map,
subscribed_rooms=subscribed,
map_path="/tmp/test_map.json",
)
# r_hidden ist user_visible=false → kein missing-Eintrag.
# r_new ist sichtbar und fehlt → missing-Eintrag.
missing_ids = [m["room_id"] for m in missing]
assert "r_hidden" not in missing_ids
assert "r_new" in missing_ids
def test_onboarding_visible_room_still_reported(self):
"""Sichtbare fehlende Räume werden weiterhin gemeldet."""
room_map = _make_map([
_room("r_catchall", "#CatchAll", [], catch_all=True),
])
subscribed = {
"r_new": {"name": "#NeuerRaum", "type": "c"},
}
missing = check_room_map_completeness(
room_map=room_map,
subscribed_rooms=subscribed,
map_path="/tmp/test_map.json",
)
assert len(missing) == 1
assert missing[0]["room_id"] == "r_new"
class TestUserVisiblePersistence:
"""user_visible wird korrekt serialisiert/deserialisiert."""
def test_save_and_reload_preserves_user_visible(self):
"""save() + load() erhält user_visible=false."""
room_map = _make_map([
_room("r_hidden", "#Versteckt", [], user_visible=False),
_room("r_catchall", "#CatchAll", [], catch_all=True),
])
tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".json",
delete=False, encoding="utf-8")
tmp.close()
path = Path(tmp.name)
try:
RoomMap.save(room_map, path)
reloaded = RoomMap.load(path)
assert reloaded.rooms["r_hidden"].user_visible is False
assert reloaded.rooms["r_catchall"].user_visible is True
finally:
path.unlink(missing_ok=True)
def test_load_defaults_user_visible_true(self):
"""Räume ohne user_visible-Feld laden mit Default true."""
data = {
"version": 2,
"rooms": {
"r_plain": {
"name": "#OhneFlag",
"theme": "x",
"keywords_100": [],
"keywords_context": [],
"catch_all": False,
},
"r_catchall": {
"name": "#CatchAll",
"theme": "x",
"keywords_100": [],
"keywords_context": [],
"catch_all": True,
},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test_docs",
}
room_map = RoomMap._from_dict(data)
assert room_map.rooms["r_plain"].user_visible is True
assert room_map.rooms["r_catchall"].user_visible is True