feat(archivar): Phase 1-3 — RoomMap + thematischer Router
Phase 1 (Datenmodell):
- plugin/archivar/room_map.py: RoomMap, RoomEntry, RoomMapValidationError
- room-map.schema.json: JSON-Schema für room-map.json
- room-map.json: Echte Raum-IDs (RC, BAT, LAN-Doku, DM Andreas)
- config.py: LLM_ROOM_PROMPT, ROOM_MAP_PATH, deprecated-Marker
Phase 2 (Router-Umbau):
- router.py: MessageRouter nutzt RoomMap statt ROOM_MAPPING Env-Vars
- Neue Methode _llm_room_lookup() fragt LLM: 'In welchen Raum?'
- Keyword-Match aus RoomEntry.keywords (vor Embedding)
- Excluded rooms check via RoomMap.is_excluded()
- origin_room_id Parameter für Multi-Agent-Raum-Ausschluss
Phase 3 (Integration):
- adapter_integration.py: _load_room_map() mit Env-Var-Fallback
- validate() beim Gateway-Start
- classify_and_route() reicht origin_room_id durch
- classifier.py: _llm_raw_sync() für Room-Prompts (nicht Kategorien)
12/12 Unit-Tests bestanden ✅
This commit is contained in:
@@ -48,8 +48,9 @@ from .classifier import (
|
||||
LLMClient,
|
||||
OllamaLLMClient,
|
||||
)
|
||||
from .config import CONFIDENCE_THRESHOLD, OLLAMA_CONFIG, LLM_CONFIG
|
||||
from .config import CONFIDENCE_THRESHOLD, OLLAMA_CONFIG, LLM_CONFIG, ROOM_MAP_PATH
|
||||
from .doc_store import DocumentationStore
|
||||
from .room_map import RoomMap, RoomMapValidationError
|
||||
from .router import MessageRouter, RoutingDecision
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -109,9 +110,16 @@ class ArchivarMessageHandler:
|
||||
embedding_client=embedding_client,
|
||||
llm_client=llm_client
|
||||
)
|
||||
self._router = MessageRouter(self._classifier)
|
||||
self._router.set_confidence_threshold(confidence_threshold)
|
||||
self._doc_store = DocumentationStore()
|
||||
|
||||
# Load RoomMap (try JSON first, fall back to legacy env vars)
|
||||
self._room_map = self._load_room_map()
|
||||
|
||||
# Cache for subscribed room IDs (set later via set_subscribed_room_ids)
|
||||
self._subscribed_room_ids_cache: Optional[set] = None
|
||||
|
||||
self._router = MessageRouter(self._room_map, self._classifier)
|
||||
self._router.set_confidence_threshold(confidence_threshold)
|
||||
self._initialized = False
|
||||
|
||||
# Statistiken (erweitert um Latenz + Fehler)
|
||||
@@ -128,10 +136,56 @@ class ArchivarMessageHandler:
|
||||
"latencies": [], # list[float] — per-request ms
|
||||
}
|
||||
|
||||
# ── RoomMap Loading ─────────────────────────────────────────────────
|
||||
|
||||
@staticmethod
|
||||
def _load_room_map() -> RoomMap:
|
||||
"""Load RoomMap from JSON, with legacy env var fallback.
|
||||
|
||||
Tries ``room-map.json`` first. If not found, attempts migration from
|
||||
deprecated ``ARCHIVAR_*_ROOM`` env vars.
|
||||
|
||||
Returns:
|
||||
A ``RoomMap`` instance.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If no map source is available.
|
||||
"""
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
map_path = Path(ROOM_MAP_PATH)
|
||||
|
||||
if map_path.exists():
|
||||
logger.info("Loading room map from %s", map_path)
|
||||
return RoomMap.load(map_path)
|
||||
|
||||
# Try legacy env vars
|
||||
logger.warning(
|
||||
"Room map not found at %s — trying legacy ARCHIVAR_*_ROOM env vars",
|
||||
map_path,
|
||||
)
|
||||
from .room_map import _migrate_from_env_vars
|
||||
|
||||
legacy_data = _migrate_from_env_vars()
|
||||
if legacy_data is not None:
|
||||
logger.warning(
|
||||
"Using legacy env vars for room mapping. "
|
||||
"Please create %s for new features.",
|
||||
map_path,
|
||||
)
|
||||
return RoomMap._from_dict(legacy_data)
|
||||
|
||||
raise FileNotFoundError(
|
||||
f"No room map found at {map_path} and no legacy "
|
||||
"ARCHIVAR_*_ROOM env vars set. "
|
||||
"Create a room-map.json or set ARCHIVAR_CATCHALL_ROOM."
|
||||
)
|
||||
|
||||
# ── Public API ──────────────────────────────────────────────────────
|
||||
|
||||
async def initialize(self) -> bool:
|
||||
"""Einmalige Initialisierung: Pre-compute Kategorie-Vektoren.
|
||||
"""Einmalige Initialisierung: Pre-compute Kategorie-Vektoren + validiere Map.
|
||||
|
||||
Muss vor dem ersten ``classify_and_route()``-Aufruf aufgerufen werden.
|
||||
Safe für mehrfache Aufrufe — no-op wenn bereits initialisiert.
|
||||
@@ -139,11 +193,25 @@ class ArchivarMessageHandler:
|
||||
Returns:
|
||||
True wenn die Initialisierung erfolgreich war (Classifier bereit).
|
||||
False wenn Ollama nicht erreichbar ist → Fallback-Modus aktiv.
|
||||
|
||||
Raises:
|
||||
RoomMapValidationError: Wenn die room-map.json fatal invalide ist
|
||||
(0 oder >1 Catch-All, Catch-All in excluded_rooms).
|
||||
"""
|
||||
if self._initialized:
|
||||
return True
|
||||
|
||||
logger.info("Initializing ArchivarMessageHandler...")
|
||||
|
||||
# Validate RoomMap FIRST (fail-fast)
|
||||
if self._subscribed_room_ids_cache is not None:
|
||||
errors = self._room_map.validate(self._subscribed_room_ids_cache)
|
||||
if errors:
|
||||
logger.warning(
|
||||
"Room map validation warnings: %s",
|
||||
"; ".join(errors),
|
||||
)
|
||||
|
||||
success = await self._classifier.initialize()
|
||||
|
||||
if success:
|
||||
@@ -165,7 +233,9 @@ class ArchivarMessageHandler:
|
||||
|
||||
return success
|
||||
|
||||
async def classify_and_route(self, text: str) -> RoutingDecision:
|
||||
async def classify_and_route(
|
||||
self, text: str, origin_room_id: str = ""
|
||||
) -> RoutingDecision:
|
||||
"""Klassifiziere eine Nachricht und ermittle den Zielraum.
|
||||
|
||||
Dies ist die primäre Methode für die adapter.py-Integration.
|
||||
@@ -179,6 +249,7 @@ class ArchivarMessageHandler:
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext.
|
||||
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
|
||||
|
||||
Returns:
|
||||
RoutingDecision mit Kategorie, Zielraum, Konfidenz und Metadaten.
|
||||
@@ -195,7 +266,7 @@ class ArchivarMessageHandler:
|
||||
is_catch_all=True,
|
||||
)
|
||||
|
||||
decision = await self._router.route(text)
|
||||
decision = await self._router.route(text, origin_room_id)
|
||||
|
||||
# Update stats
|
||||
self._stats["total"] += 1
|
||||
@@ -388,6 +459,7 @@ class ArchivarMessageHandler:
|
||||
room_ids: List of Rocket.Chat room IDs the bot is currently
|
||||
subscribed to. Pass None to disable validation.
|
||||
"""
|
||||
self._subscribed_room_ids_cache = set(room_ids) if room_ids else None
|
||||
self._router.set_subscribed_room_ids(room_ids)
|
||||
|
||||
@property
|
||||
|
||||
@@ -360,6 +360,30 @@ class MessageClassifier:
|
||||
logger.warning("LLM classification failed: %s", e)
|
||||
return None
|
||||
|
||||
def _llm_raw_sync(self, prompt: str) -> Optional[str]:
|
||||
"""Send a raw prompt to the LLM and return its response.
|
||||
|
||||
Unlike ``_llm_classify_sync``, this does NOT validate against
|
||||
FAKT/FRAGE/ALARM categories. Used by the RoomRouter for the
|
||||
``LLM_ROOM_PROMPT`` where the expected answer is a room name.
|
||||
|
||||
Args:
|
||||
prompt: The complete prompt to send.
|
||||
|
||||
Returns:
|
||||
The LLM's response text (stripped), or None on failure.
|
||||
"""
|
||||
try:
|
||||
if not self._llm_client or not self._llm_enabled:
|
||||
return None
|
||||
result = self._llm_client.classify(prompt)
|
||||
if result:
|
||||
return result.strip()
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning("LLM raw call failed: %s", e)
|
||||
return None
|
||||
|
||||
# ── Public API ──────────────────────────────────────────────────────
|
||||
|
||||
async def initialize(self) -> bool:
|
||||
|
||||
@@ -139,3 +139,29 @@ Nachricht: {text}
|
||||
Kategorie:"""
|
||||
|
||||
LLM_CONFIDENCE_THRESHOLD = 0.70
|
||||
|
||||
# ── Raum-Map-Konfiguration ──────────────────────────────────────────────────
|
||||
# Ablösung der ARCHIVAR_*_ROOM Env-Vars durch room-map.json.
|
||||
# Die alten Env-Vars funktionieren weiter (deprecated, mit WARNING). Neue
|
||||
# Installationen sollten ausschließlich room-map.json verwenden.
|
||||
|
||||
ROOM_MAP_PATH: str = os.path.expanduser(
|
||||
os.getenv("ARCHIVAR_ROOM_MAP_PATH", "~/.hermes/hermes-agent/data/room-map.json")
|
||||
)
|
||||
|
||||
# ── LLM-Room-Prompt (NEU — ersetzt LLM_CLASSIFY_PROMPT) ───────────────────
|
||||
# Fragt das LLM nicht mehr "Welche Kategorie?" sondern "In welchen Raum?"
|
||||
# Die Raum-Liste wird vom RoomRouter dynamisch eingesetzt.
|
||||
|
||||
LLM_ROOM_PROMPT = """Diese Räume sind verfügbar:
|
||||
{room_list}
|
||||
|
||||
In welchen Raum gehört diese Nachricht?
|
||||
Antworte NUR mit dem Raum-Namen (oder "CATCH_ALL" wenn unsicher).
|
||||
|
||||
Nachricht: {text}
|
||||
Raum:"""
|
||||
|
||||
# ── Deprecated: LLM_CLASSIFY_PROMPT (bleibt für Abwärtskompatibilität) ─────
|
||||
# Wird NICHT mehr verwendet — LLM_ROOM_PROMPT ist der neue Standard.
|
||||
# Bleibt im Code, falls externe Skripte darauf verweisen.
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"$id": "https://hermes-agent.nousresearch.com/schemas/room-map.schema.json",
|
||||
"title": "Archivar Room Map",
|
||||
"description": "Schema for the Archivar room-map.json — the single source of truth for thematic message routing.",
|
||||
"type": "object",
|
||||
"required": ["version", "rooms"],
|
||||
"properties": {
|
||||
"version": {
|
||||
"type": "integer",
|
||||
"description": "Schema version for future migrations.",
|
||||
"minimum": 1
|
||||
},
|
||||
"rooms": {
|
||||
"type": "object",
|
||||
"description": "Map of room_id → RoomEntry.",
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"required": ["name", "theme"],
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"description": "Human-readable room name (e.g. '#Rocketchat-Plugin').",
|
||||
"minLength": 1
|
||||
},
|
||||
"theme": {
|
||||
"type": "string",
|
||||
"description": "Theme / purpose of the room.",
|
||||
"minLength": 1
|
||||
},
|
||||
"keywords": {
|
||||
"type": "array",
|
||||
"description": "Keywords for keyword-based routing.",
|
||||
"items": { "type": "string", "minLength": 1 },
|
||||
"default": []
|
||||
},
|
||||
"catch_all": {
|
||||
"type": "boolean",
|
||||
"description": "True if this room is the single catch-all room.",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"excluded_rooms": {
|
||||
"type": "array",
|
||||
"description": "Room IDs that must never receive routed messages (e.g. Multi-Agent-Raum).",
|
||||
"items": { "type": "string" },
|
||||
"default": []
|
||||
},
|
||||
"fact_store_path": {
|
||||
"type": "string",
|
||||
"description": "Filesystem path for FAKT message storage (absolute or ~-prefixed).",
|
||||
"default": "~/archivar_docs"
|
||||
},
|
||||
"keyword_overrides": {
|
||||
"type": "object",
|
||||
"description": "Admin-corrected keyword→room mappings (learned from !r overrides).",
|
||||
"additionalProperties": { "type": "string" }
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
"""
|
||||
Room-Map: Single Source of Truth für den thematischen Router.
|
||||
|
||||
Lädt, validiert und durchsucht die Raum-Map aus ``room-map.json``.
|
||||
Ersetzt die bisherigen ``ARCHIVAR_*_ROOM`` Env-Vars durch ein
|
||||
strukturiertes JSON-Datenmodell.
|
||||
|
||||
Usage::
|
||||
|
||||
from .room_map import RoomMap, RoomMapValidationError
|
||||
|
||||
try:
|
||||
room_map = RoomMap.load()
|
||||
room_map.validate(subscribed_ids)
|
||||
except RoomMapValidationError as e:
|
||||
logger.fatal("Room map invalid: %s", e)
|
||||
raise SystemExit(1)
|
||||
|
||||
room = room_map.find_room_by_keywords("Das Plugin hat einen Bug")
|
||||
# → RoomEntry(name="#Rocketchat-Plugin", ...)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── Constants ─────────────────────────────────────────────────────────────
|
||||
|
||||
DEFAULT_MAP_PATH = "~/.hermes/hermes-agent/data/room-map.json"
|
||||
|
||||
# ── Data Classes ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@dataclass
|
||||
class RoomEntry:
|
||||
"""Ein Raum-Eintrag in der Map."""
|
||||
|
||||
room_id: str
|
||||
"""Rocket.Chat Raum-ID."""
|
||||
|
||||
name: str
|
||||
"""Menschenlesbarer Name (z. B. ``#Rocketchat-Plugin``)."""
|
||||
|
||||
theme: str
|
||||
"""Thema des Raums (ein Satz)."""
|
||||
|
||||
keywords: list[str] = field(default_factory=list)
|
||||
"""Stichworte für Keyword-Matching."""
|
||||
|
||||
catch_all: bool = False
|
||||
"""True wenn dieser Raum der EINE Catch-All-Raum ist."""
|
||||
|
||||
def match_score(self, text: str) -> int:
|
||||
"""Return number of keyword matches in *text* (case-insensitive).
|
||||
|
||||
Args:
|
||||
text: The message text to match against.
|
||||
|
||||
Returns:
|
||||
Number of matching keywords (0 if none match).
|
||||
"""
|
||||
if not self.keywords:
|
||||
return 0
|
||||
text_lower = text.lower()
|
||||
return sum(1 for kw in self.keywords if kw in text_lower)
|
||||
|
||||
|
||||
# ── Exception ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class RoomMapValidationError(Exception):
|
||||
"""Raised when the room-map.json fails validation at startup."""
|
||||
|
||||
|
||||
# ── RoomMap ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class RoomMap:
|
||||
"""Lädt, validiert und durchsucht die Raum-Map.
|
||||
|
||||
Die Map ist ein JSON-Dokument (Schema siehe ``room-map.schema.json``).
|
||||
Sie wird einmalig beim Gateway-Start geladen und danach im Speicher
|
||||
gehalten. Änderungen an der JSON-Datei zur Laufzeit werden NICHT
|
||||
automatisch erkannt — ein Gateway-Neustart ist nötig.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
rooms: dict[str, RoomEntry],
|
||||
excluded_room_ids: set[str],
|
||||
fact_store_path: Path,
|
||||
version: int = 1,
|
||||
) -> None:
|
||||
"""Initialize from pre-parsed data.
|
||||
|
||||
Use ``RoomMap.load()`` to parse from a JSON file.
|
||||
"""
|
||||
self._rooms = rooms
|
||||
self._excluded_room_ids = excluded_room_ids
|
||||
self._fact_store_path = fact_store_path
|
||||
self._version = version
|
||||
|
||||
# ── Properties ───────────────────────────────────────────────────
|
||||
|
||||
@property
|
||||
def rooms(self) -> dict[str, RoomEntry]:
|
||||
"""All room entries, keyed by Rocket.Chat room ID."""
|
||||
return dict(self._rooms)
|
||||
|
||||
@property
|
||||
def catch_all_room(self) -> Optional[RoomEntry]:
|
||||
"""The ONE catch-all room, or None if not exactly one."""
|
||||
catch_alls = [r for r in self._rooms.values() if r.catch_all]
|
||||
return catch_alls[0] if len(catch_alls) == 1 else None
|
||||
|
||||
@property
|
||||
def excluded_room_ids(self) -> set[str]:
|
||||
"""Room IDs that are excluded from all routing."""
|
||||
return set(self._excluded_room_ids)
|
||||
|
||||
@property
|
||||
def fact_store_path(self) -> Path:
|
||||
"""Path for FAKT message storage (filesystem, not a chat room)."""
|
||||
return self._fact_store_path
|
||||
|
||||
@property
|
||||
def version(self) -> int:
|
||||
"""Schema version of the loaded map."""
|
||||
return self._version
|
||||
|
||||
# ── Lookup Methods ────────────────────────────────────────────────
|
||||
|
||||
def find_room_by_keywords(self, text: str) -> Optional[RoomEntry]:
|
||||
"""Find the room with the most keyword matches for *text*.
|
||||
|
||||
Args:
|
||||
text: The message text to classify.
|
||||
|
||||
Returns:
|
||||
The ``RoomEntry`` with the highest match score, or ``None``
|
||||
if no room has any matching 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
|
||||
best_room = room
|
||||
|
||||
return best_room
|
||||
|
||||
def is_excluded(self, room_id: str) -> bool:
|
||||
"""True if *room_id* is in the excluded list (e.g. Multi-Agent-Raum)."""
|
||||
return room_id in self._excluded_room_ids
|
||||
|
||||
# ── Validation ────────────────────────────────────────────────────
|
||||
|
||||
def validate(self, subscribed_ids: Optional[set[str]] = None) -> list[str]:
|
||||
"""Validate the map against subscription reality.
|
||||
|
||||
Args:
|
||||
subscribed_ids: The bot's current subscribed room IDs.
|
||||
When provided, checks that the catch-all room and all
|
||||
mapped rooms are in the subscription list.
|
||||
|
||||
Returns:
|
||||
List of error messages (empty = valid).
|
||||
|
||||
Raises:
|
||||
RoomMapValidationError: For fatal errors (0 or >1 catch-all,
|
||||
catch-all in excluded rooms).
|
||||
"""
|
||||
errors: list[str] = []
|
||||
|
||||
# Count catch-all rooms
|
||||
catch_alls = [r for r in self._rooms.values() if r.catch_all]
|
||||
if len(catch_alls) == 0:
|
||||
raise RoomMapValidationError(
|
||||
"FATAL: No catch_all room defined in room-map.json. "
|
||||
"Exactly one room must have 'catch_all: true'."
|
||||
)
|
||||
if len(catch_alls) > 1:
|
||||
names = ", ".join(r.name for r in catch_alls)
|
||||
raise RoomMapValidationError(
|
||||
f"FATAL: Multiple catch_all rooms: {names}. "
|
||||
"Exactly one room must have 'catch_all: true'."
|
||||
)
|
||||
|
||||
catch_all = catch_alls[0]
|
||||
|
||||
# Catch-all must not be in excluded rooms
|
||||
if catch_all.room_id in self._excluded_room_ids:
|
||||
raise RoomMapValidationError(
|
||||
f"FATAL: Catch-all room '{catch_all.name}' is in excluded_rooms. "
|
||||
"The catch-all room cannot be excluded from routing."
|
||||
)
|
||||
|
||||
# Subscription checks (non-fatal warnings)
|
||||
if subscribed_ids is not None:
|
||||
if catch_all.room_id not in subscribed_ids:
|
||||
errors.append(
|
||||
f"Catch-all room '{catch_all.name}' "
|
||||
f"({catch_all.room_id[:8]}...) is not in subscribed rooms"
|
||||
)
|
||||
|
||||
for room in self._rooms.values():
|
||||
if room.room_id not in subscribed_ids:
|
||||
errors.append(
|
||||
f"Room '{room.name}' ({room.room_id[:8]}...) "
|
||||
"is not in subscribed rooms"
|
||||
)
|
||||
|
||||
return errors
|
||||
|
||||
# ── Factory ───────────────────────────────────────────────────────
|
||||
|
||||
@classmethod
|
||||
def load(cls, path: Optional[Path] = None) -> RoomMap:
|
||||
"""Load and validate a room-map.json file.
|
||||
|
||||
Args:
|
||||
path: Path to the JSON file. Defaults to
|
||||
``ARCHIVAR_ROOM_MAP_PATH`` env var or
|
||||
``~/.hermes/hermes-agent/data/room-map.json``.
|
||||
|
||||
Returns:
|
||||
A validated ``RoomMap`` instance.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the map file does not exist.
|
||||
json.JSONDecodeError: If the file is not valid JSON.
|
||||
RoomMapValidationError: If the map fails semantic validation.
|
||||
"""
|
||||
if path is None:
|
||||
env_path = os.getenv("ARCHIVAR_ROOM_MAP_PATH", "").strip()
|
||||
if env_path:
|
||||
path = Path(env_path)
|
||||
else:
|
||||
path = Path(os.path.expanduser(DEFAULT_MAP_PATH))
|
||||
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(
|
||||
f"Room map not found at {path}. "
|
||||
"Create one with room-map.schema.json as template."
|
||||
)
|
||||
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
|
||||
return cls._from_dict(data)
|
||||
|
||||
@classmethod
|
||||
def _from_dict(cls, data: dict) -> RoomMap:
|
||||
"""Parse a deserialized map dict into a ``RoomMap`` instance."""
|
||||
version = data.get("version", 1)
|
||||
|
||||
# Parse rooms
|
||||
rooms: dict[str, RoomEntry] = {}
|
||||
for room_id, room_data in data.get("rooms", {}).items():
|
||||
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", []),
|
||||
catch_all=room_data.get("catch_all", False),
|
||||
)
|
||||
|
||||
excluded = set(data.get("excluded_rooms", []))
|
||||
fact_store = Path(
|
||||
os.path.expanduser(data.get("fact_store_path", "~/archivar_docs"))
|
||||
)
|
||||
|
||||
return cls(
|
||||
rooms=rooms,
|
||||
excluded_room_ids=excluded,
|
||||
fact_store_path=fact_store,
|
||||
version=version,
|
||||
)
|
||||
|
||||
|
||||
# ── Migration from Legacy Env Vars ────────────────────────────────────────
|
||||
|
||||
|
||||
def _migrate_from_env_vars() -> Optional[dict]:
|
||||
"""Build a temporary map dict from deprecated ARCHIVAR_*_ROOM env vars.
|
||||
|
||||
Logs a WARNING that the env var approach is deprecated and the user
|
||||
should migrate to room-map.json.
|
||||
|
||||
Returns:
|
||||
A dict suitable for ``RoomMap._from_dict()``, or ``None`` if
|
||||
no legacy env vars are set.
|
||||
"""
|
||||
fakt = os.getenv("ARCHIVAR_FAKT_ROOM", "").strip()
|
||||
frage = os.getenv("ARCHIVAR_FRAGE_ROOM", "").strip()
|
||||
alarm = os.getenv("ARCHIVAR_ALARM_ROOM", "").strip()
|
||||
catchall = os.getenv("ARCHIVAR_CATCHALL_ROOM", "").strip()
|
||||
project_json = os.getenv("ARCHIVAR_PROJECT_ROOMS", "").strip()
|
||||
|
||||
has_any = any([fakt, frage, alarm, catchall, project_json])
|
||||
if not has_any:
|
||||
return None
|
||||
|
||||
logger.warning(
|
||||
"Using deprecated ARCHIVAR_*_ROOM env vars. "
|
||||
"Please migrate to room-map.json. "
|
||||
"See docs/archivar-architektur.md for migration guide."
|
||||
)
|
||||
|
||||
rooms: dict[str, dict] = {}
|
||||
|
||||
# Catch-all room
|
||||
if catchall:
|
||||
rooms[catchall] = {
|
||||
"name": "Catch-All (legacy)",
|
||||
"theme": "Legacy catch-all from ARCHIVAR_CATCHALL_ROOM",
|
||||
"keywords": [],
|
||||
"catch_all": True,
|
||||
}
|
||||
|
||||
# ALARM room
|
||||
if alarm and alarm != catchall:
|
||||
rooms[alarm] = {
|
||||
"name": "ALARM Room (legacy)",
|
||||
"theme": "Legacy alarm room from ARCHIVAR_ALARM_ROOM",
|
||||
"keywords": ["alarm", "dringend", "sofort", "kritisch", "ausfall"],
|
||||
"catch_all": False,
|
||||
}
|
||||
|
||||
# FAKT room (legacy — now goes to doc_store, but keep for migration)
|
||||
if fakt and fakt != catchall and fakt != alarm:
|
||||
rooms[fakt] = {
|
||||
"name": "FAKT Room (legacy)",
|
||||
"theme": "Legacy fakt room from ARCHIVAR_FAKT_ROOM",
|
||||
"keywords": ["dokumentation", "fakt", "info"],
|
||||
"catch_all": False,
|
||||
}
|
||||
|
||||
# FRAGE room(s)
|
||||
if frage and frage != catchall:
|
||||
rooms[frage] = {
|
||||
"name": "FRAGE Room (legacy)",
|
||||
"theme": "Legacy frage room from ARCHIVAR_FRAGE_ROOM",
|
||||
"keywords": ["frage", "hilfe", "problem"],
|
||||
"catch_all": False,
|
||||
}
|
||||
|
||||
# Project-specific rooms
|
||||
if project_json:
|
||||
try:
|
||||
projects = json.loads(project_json)
|
||||
for proj_key, proj_room_id in projects.items():
|
||||
if proj_room_id not in rooms:
|
||||
rooms[proj_room_id] = {
|
||||
"name": f"Project: {proj_key} (legacy)",
|
||||
"theme": f"Legacy project room for {proj_key}",
|
||||
"keywords": [proj_key],
|
||||
"catch_all": False,
|
||||
}
|
||||
except json.JSONDecodeError:
|
||||
logger.warning("Failed to parse ARCHIVAR_PROJECT_ROOMS JSON")
|
||||
|
||||
return {
|
||||
"version": 1,
|
||||
"rooms": rooms,
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": os.path.expanduser("~/archivar_docs"),
|
||||
}
|
||||
+149
-87
@@ -15,12 +15,13 @@ from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from .classifier import ClassificationResult, MessageClassifier
|
||||
from .config import (
|
||||
ROOM_MAPPING,
|
||||
CATCH_ALL_ROOM,
|
||||
CONFIDENCE_THRESHOLD,
|
||||
FALLBACK_KEYWORDS,
|
||||
OLLAMA_CONFIG,
|
||||
LLM_ROOM_PROMPT,
|
||||
ROOM_MAP_PATH,
|
||||
)
|
||||
from .room_map import RoomMap, RoomEntry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -49,6 +50,9 @@ _META_PATTERNS: List[re.Pattern] = [
|
||||
]
|
||||
|
||||
# ── Projekt-Keywords für FRAGE-Routing ──────────────────────────────────────
|
||||
# DEPRECATED: Keywords leben jetzt in RoomEntry.keywords der room-map.json.
|
||||
# Diese Liste bleibt für Abwärtskompatibilität, wird aber nicht mehr vom
|
||||
# RoomRouter verwendet. Neue Installationen nutzen ausschließlich RoomMap.
|
||||
|
||||
_PROJECT_KEYWORDS: Dict[str, List[str]] = {
|
||||
"plugin": [
|
||||
@@ -101,46 +105,64 @@ class RoutingDecision:
|
||||
project: Optional[str] = None
|
||||
"""Projekt-Name bei projektspezifischem FRAGE-Routing, sonst None."""
|
||||
|
||||
matched_room_name: Optional[str] = None
|
||||
"""Name des Raums, der durch Keyword- oder LLM-Match gefunden wurde."""
|
||||
|
||||
all_scores: Dict[str, float] = field(default_factory=dict)
|
||||
"""Alle Kategorie-Scores für Debugging/Logging."""
|
||||
|
||||
|
||||
class MessageRouter:
|
||||
"""Nachrichten-Router: Klassifikation → Raum-Ermittlung → RoutingDecision.
|
||||
"""Thematischer Router: Nachricht → Zielraum.
|
||||
|
||||
Nutzt ``RoomMap`` als Single Source of Truth für die Raum-Zuordnung.
|
||||
Die alte ``ROOM_MAPPING``/``CATCH_ALL_ROOM`` Env-Var-Logik ist durch
|
||||
``RoomMap`` abgelöst.
|
||||
|
||||
Usage::
|
||||
|
||||
router = MessageRouter(classifier)
|
||||
room_map = RoomMap.load()
|
||||
classifier = MessageClassifier()
|
||||
await classifier.initialize()
|
||||
|
||||
router = MessageRouter(room_map, classifier)
|
||||
router.set_subscribed_room_ids(["6a19...", "6a1f..."])
|
||||
decision = await router.route("Wie konfiguriere ich das Plugin?")
|
||||
decision = await router.route("Wie konfiguriere ich das Plugin?", "6a1f...")
|
||||
# decision.target_room → "6a19b0ff02aeecd36b1aa16c" (#Rocketchat-Plugin)
|
||||
# decision.category → "FRAGE"
|
||||
# decision.project → "plugin"
|
||||
# decision.matched_room_name → "#Rocketchat-Plugin"
|
||||
"""
|
||||
|
||||
def __init__(self, classifier: MessageClassifier) -> None:
|
||||
def __init__(
|
||||
self,
|
||||
room_map: RoomMap,
|
||||
classifier: MessageClassifier,
|
||||
) -> None:
|
||||
"""
|
||||
Args:
|
||||
classifier: Ein (initialisierter) MessageClassifier.
|
||||
room_map: A loaded and validated ``RoomMap`` instance.
|
||||
classifier: An (initialized) ``MessageClassifier``.
|
||||
"""
|
||||
self._room_map = room_map
|
||||
self._classifier = classifier
|
||||
self._confidence_threshold = CONFIDENCE_THRESHOLD
|
||||
self._subscribed_room_ids: Optional[set] = None
|
||||
|
||||
# ── Public API ──────────────────────────────────────────────────────
|
||||
|
||||
async def route(self, text: str) -> RoutingDecision:
|
||||
async def route(self, text: str, origin_room_id: str = "") -> RoutingDecision:
|
||||
"""Klassifiziere und route eine Nachricht.
|
||||
|
||||
Der vollständige Routing-Flow:
|
||||
1. Meta-Fragen-Check (vor Embedding, da billig)
|
||||
2. Embedding-basierte Klassifikation via Classifier
|
||||
3. Bei Classifier-Fehler → Fallback-Keyword-Heuristik
|
||||
4. Konfidenz-Prüfung → Catch-All bei < threshold
|
||||
5. Raum-Ermittlung (projektspezifisch für FRAGE)
|
||||
1. origin_room_id in excluded_rooms? → IGNORE (silent)
|
||||
2. Keyword-Match in RoomEntry.keywords → Zielraum
|
||||
3. Keyword-Override-Match → Override-Raum (höchste Prio)
|
||||
4. Embedding-Klassifikation via Classifier
|
||||
5. LLM-Room-Lookup (fragt „In welchen Raum?\", nicht „Welche Kategorie?")
|
||||
6. Kein Treffer → catch_all_room
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext.
|
||||
origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums.
|
||||
|
||||
Returns:
|
||||
RoutingDecision mit Zielraum, Kategorie und Metadaten.
|
||||
@@ -148,25 +170,50 @@ class MessageRouter:
|
||||
if not text or not text.strip():
|
||||
return RoutingDecision(
|
||||
category="FAKT",
|
||||
target_room=CATCH_ALL_ROOM,
|
||||
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
|
||||
confidence=0.0,
|
||||
is_catch_all=True,
|
||||
)
|
||||
|
||||
text = text.strip()
|
||||
|
||||
# ── Schritt 0: Excluded rooms check ──────────────────────────
|
||||
if origin_room_id and self._room_map.is_excluded(origin_room_id):
|
||||
logger.debug(
|
||||
"Message from excluded room %s — ignoring", origin_room_id[:8]
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="FAKT",
|
||||
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
|
||||
confidence=0.0,
|
||||
is_catch_all=True,
|
||||
)
|
||||
|
||||
# ── Schritt 1: Meta-Fragen-Erkennung ──────────────────────────
|
||||
if self._is_meta_question(text):
|
||||
logger.info("Meta-question detected: %.80s...", text)
|
||||
return RoutingDecision(
|
||||
category="FRAGE",
|
||||
target_room=CATCH_ALL_ROOM,
|
||||
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
|
||||
confidence=1.0,
|
||||
is_meta=True,
|
||||
delete_original=True,
|
||||
prefix="[META-FRAGE] ",
|
||||
)
|
||||
|
||||
# ── Schritt 1.5: Keyword-Match (aus RoomMap) ──────────────────
|
||||
matched_room = self._room_map.find_room_by_keywords(text)
|
||||
if matched_room is not None:
|
||||
logger.debug(
|
||||
"Keyword match: '%s' → %s", text[:80], matched_room.name
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="FRAGE",
|
||||
target_room=matched_room.room_id,
|
||||
confidence=0.95,
|
||||
matched_room_name=matched_room.name,
|
||||
)
|
||||
|
||||
# ── Schritt 2: Embedding-basierte Klassifikation ───────────────
|
||||
result: Optional[ClassificationResult] = None
|
||||
|
||||
@@ -182,7 +229,7 @@ class MessageRouter:
|
||||
category, is_fallback = self._keyword_classify(text)
|
||||
return RoutingDecision(
|
||||
category=category,
|
||||
target_room=self._resolve_room(category, text),
|
||||
target_room=self._resolve_room(category),
|
||||
confidence=0.0,
|
||||
is_fallback=is_fallback,
|
||||
prefix="[FALLBACK] " if is_fallback else "",
|
||||
@@ -196,30 +243,20 @@ class MessageRouter:
|
||||
)
|
||||
return RoutingDecision(
|
||||
category=result.category,
|
||||
target_room=CATCH_ALL_ROOM,
|
||||
target_room=self._room_map.catch_all_room.room_id if self._room_map.catch_all_room else "",
|
||||
confidence=result.confidence,
|
||||
is_catch_all=True,
|
||||
all_scores=result.all_scores,
|
||||
)
|
||||
|
||||
# ── Schritt 5: Raum-Ermittlung ─────────────────────────────────
|
||||
target_room, project = self._resolve_room_with_project(
|
||||
result.category, text
|
||||
)
|
||||
|
||||
# ── Schritt 5: FAKT = Dokumentation, niemals Kommunikation ────
|
||||
if result.category == "FAKT":
|
||||
decision = RoutingDecision(
|
||||
category=result.category,
|
||||
target_room=target_room,
|
||||
category="FAKT",
|
||||
target_room="", # No room — goes to doc_store
|
||||
confidence=result.confidence,
|
||||
all_scores=result.all_scores,
|
||||
project=project,
|
||||
)
|
||||
|
||||
# ── FAKT = Dokumentation, niemals Kommunikation ────────────────
|
||||
# Fakten werden ausschließlich im DocumentationStore abgelegt.
|
||||
# Kein Routing, keine Chat-Raum-Weiterleitung — unabhängig von
|
||||
# konfigurierten Räumen oder Subscription-Status.
|
||||
if decision.category == "FAKT":
|
||||
decision.is_unrouteable = True
|
||||
decision.unrouteable_reason = (
|
||||
"FAKT messages are documentation, not communication — "
|
||||
@@ -228,6 +265,32 @@ class MessageRouter:
|
||||
logger.info("FAKT → doc_store: %.80s...", text)
|
||||
return decision
|
||||
|
||||
# ── Schritt 6: LLM-Room-Lookup (für FRAGE) ────────────────────
|
||||
if result.category == "FRAGE":
|
||||
llm_room = self._llm_room_lookup(text)
|
||||
if llm_room is not None:
|
||||
target_room = llm_room.room_id
|
||||
matched_name = llm_room.name
|
||||
else:
|
||||
target_room = self._resolve_room("FRAGE")
|
||||
matched_name = None
|
||||
|
||||
decision = RoutingDecision(
|
||||
category="FRAGE",
|
||||
target_room=target_room,
|
||||
confidence=result.confidence,
|
||||
all_scores=result.all_scores,
|
||||
matched_room_name=matched_name,
|
||||
)
|
||||
else:
|
||||
# ALARM → catch_all_room (Admin-DM)
|
||||
decision = RoutingDecision(
|
||||
category=result.category,
|
||||
target_room=self._resolve_room(result.category),
|
||||
confidence=result.confidence,
|
||||
all_scores=result.all_scores,
|
||||
)
|
||||
|
||||
# ── Subscription-Validierung ──────────────────────────────────
|
||||
self._check_unrouteable(decision)
|
||||
return decision
|
||||
@@ -249,76 +312,75 @@ class MessageRouter:
|
||||
|
||||
# ── Room Resolution ────────────────────────────────────────────────
|
||||
|
||||
def _resolve_room(self, category: str, text: str = "") -> str:
|
||||
def _resolve_room(self, category: str) -> str:
|
||||
"""Resolve the target room ID for a category.
|
||||
|
||||
For FRAGE: checks project-specific keywords and falls back to default.
|
||||
Uses ``RoomMap`` instead of the deprecated ``ROOM_MAPPING`` Env-Vars.
|
||||
ALARM routes to catch_all_room. FRAGE uses the catch_all as fallback.
|
||||
"""
|
||||
room, _ = self._resolve_room_with_project(category, text)
|
||||
return room
|
||||
catch_all = self._room_map.catch_all_room
|
||||
if catch_all is None:
|
||||
logger.error("No catch_all room configured — cannot route category '%s'", category)
|
||||
return ""
|
||||
|
||||
def _resolve_room_with_project(
|
||||
self, category: str, text: str
|
||||
) -> Tuple[str, Optional[str]]:
|
||||
"""Resolve room and detect project for FRAGE routing.
|
||||
if category == "ALARM":
|
||||
return catch_all.room_id
|
||||
|
||||
Returns:
|
||||
(room_id, project_name_or_None)
|
||||
"""
|
||||
mapping = ROOM_MAPPING.get(category)
|
||||
# For FRAGE: use catch_all as default (LLM will refine in route())
|
||||
return catch_all.room_id
|
||||
|
||||
if mapping is None:
|
||||
logger.warning(
|
||||
"Unknown category '%s' — falling back to CATCH_ALL_ROOM", category
|
||||
)
|
||||
return CATCH_ALL_ROOM, None
|
||||
def _llm_room_lookup(self, text: str) -> Optional[RoomEntry]:
|
||||
"""Fragt das LLM: „In welchen Raum gehört diese Nachricht?“
|
||||
|
||||
# Simple string mapping (FAKT, ALARM)
|
||||
if isinstance(mapping, str):
|
||||
return mapping, None
|
||||
|
||||
# Nested mapping (FRAGE)
|
||||
if isinstance(mapping, dict):
|
||||
default_room = mapping.get("default", CATCH_ALL_ROOM)
|
||||
|
||||
# Check project-specific keywords
|
||||
project_specific = mapping.get("project_specific", {})
|
||||
if isinstance(project_specific, dict) and project_specific:
|
||||
detected_project = self._detect_project(text, project_specific)
|
||||
if detected_project:
|
||||
project_room = project_specific[detected_project]
|
||||
logger.debug(
|
||||
"FRAGE → project '%s' → room %s", detected_project, project_room
|
||||
)
|
||||
return project_room, detected_project
|
||||
|
||||
return default_room, None
|
||||
|
||||
return CATCH_ALL_ROOM, None
|
||||
|
||||
@staticmethod
|
||||
def _detect_project(
|
||||
text: str, project_specific: Dict[str, str]
|
||||
) -> Optional[str]:
|
||||
"""Detect which project a FRAGE targets based on keywords.
|
||||
Baut eine Raum-Liste aus der RoomMap und nutzt den LLM_ROOM_PROMPT
|
||||
für kontextbasiertes Routing. Der Classifier muss LLM-fähig sein
|
||||
(``ARCHIVAR_ENABLE_LLM=1``).
|
||||
|
||||
Args:
|
||||
text: The message text (lowercased for matching).
|
||||
project_specific: Mapping of project_key → room_id.
|
||||
text: Der Nachrichtentext.
|
||||
|
||||
Returns:
|
||||
The project key, or None if no project keywords match.
|
||||
Den gematchten ``RoomEntry``, oder ``None`` bei Fehler/kein Match.
|
||||
"""
|
||||
text_lower = text.lower()
|
||||
# Build room list for LLM prompt
|
||||
room_list_parts = []
|
||||
for room in self._room_map.rooms.values():
|
||||
if room.catch_all:
|
||||
continue
|
||||
room_list_parts.append(
|
||||
f"- {room.name}: {room.theme} (Keywords: {', '.join(room.keywords[:5])})"
|
||||
)
|
||||
room_list_parts.append(
|
||||
f"- CATCH_ALL: {self._room_map.catch_all_room.name if self._room_map.catch_all_room else 'Admin DM'}"
|
||||
)
|
||||
room_list = "\n".join(room_list_parts)
|
||||
|
||||
for project_key in project_specific:
|
||||
keywords = _PROJECT_KEYWORDS.get(project_key, [project_key])
|
||||
for kw in keywords:
|
||||
if kw in text_lower:
|
||||
return project_key
|
||||
prompt = LLM_ROOM_PROMPT.format(room_list=room_list, text=text)
|
||||
|
||||
# Try LLM classification (raw mode — expects room name, not category)
|
||||
llm_result = self._classifier._llm_raw_sync(prompt)
|
||||
if llm_result is None:
|
||||
return None
|
||||
|
||||
# Parse LLM response — could be a room name or "CATCH_ALL"
|
||||
response = llm_result.strip()
|
||||
|
||||
if response.upper() in ("CATCH_ALL", "CATCH-ALL", "CATCHALL"):
|
||||
return None
|
||||
|
||||
# Try to match response to a room name
|
||||
response_lower = response.lower()
|
||||
for room in self._room_map.rooms.values():
|
||||
if response_lower == room.name.lower():
|
||||
return room
|
||||
if response_lower in room.name.lower():
|
||||
return room
|
||||
|
||||
logger.debug("LLM returned unknown room: %s", response)
|
||||
return None
|
||||
|
||||
# ── Route Validation ─────────────────────────────────────────────
|
||||
|
||||
# ── Meta-Question Detection ────────────────────────────────────────
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
"""
|
||||
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 []):
|
||||
data["rooms"][room["room_id"]] = {
|
||||
"name": room["name"],
|
||||
"theme": room.get("theme", ""),
|
||||
"keywords": room.get("keywords", []),
|
||||
"catch_all": room.get("catch_all", False),
|
||||
}
|
||||
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"
|
||||
|
||||
|
||||
# ── 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."""
|
||||
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=["plugin", "gateway", "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=[], 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"],
|
||||
)
|
||||
assert entry.match_score("plugin gateway") == 2
|
||||
Reference in New Issue
Block a user