Files
Hermes_rocket.chat_Plugin/plugin/archivar/room_map.py
T
Hermes Agent 58f00c0c23 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 ✅
2026-06-05 22:06:32 +02:00

380 lines
13 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
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"),
}