diff --git a/plugin/adapter.py b/plugin/adapter.py index f743e7c..4653f13 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -469,6 +469,9 @@ class RocketChatAdapter(BasePlatformAdapter): # Archivar initialisieren (Embedding-basierte Klassifikation) try: await self.archivar.initialize() + # Feed the actual subscribed room IDs to the router so it can + # validate targets and store unrouteable messages in doc_store. + self.archivar.set_subscribed_room_ids(list(self._subscribed_rooms)) logger.info("[rocketchat] Archivar initialisiert — Embedding-basierte Nachrichten-Klassifikation aktiv") except Exception as e: logger.warning("[rocketchat] Archivar-Initialisierung fehlgeschlagen: %s — Fallback ohne Klassifikation", e) diff --git a/plugin/archivar/__init__.py b/plugin/archivar/__init__.py index 95b6cf5..82cf0f7 100644 --- a/plugin/archivar/__init__.py +++ b/plugin/archivar/__init__.py @@ -10,6 +10,7 @@ Architektur: Siehe docs/Archivar_Architecture.md from .classifier import MessageClassifier, ClassificationResult, EmbeddingClient, OllamaEmbeddingClient from .config import ROOM_MAPPING, CATCH_ALL_ROOM, CATEGORY_TEXTS, OLLAMA_CONFIG, CONFIDENCE_THRESHOLD +from .doc_store import DocumentationStore from .router import MessageRouter, RoutingDecision from .adapter_integration import ArchivarMessageHandler @@ -18,6 +19,7 @@ __all__ = [ "ClassificationResult", "EmbeddingClient", "OllamaEmbeddingClient", + "DocumentationStore", "ROOM_MAPPING", "CATCH_ALL_ROOM", "CATEGORY_TEXTS", diff --git a/plugin/archivar/adapter_integration.py b/plugin/archivar/adapter_integration.py index 1a32a47..b0c0b59 100644 --- a/plugin/archivar/adapter_integration.py +++ b/plugin/archivar/adapter_integration.py @@ -47,6 +47,7 @@ from .classifier import ( MessageClassifier, ) from .config import CONFIDENCE_THRESHOLD, OLLAMA_CONFIG +from .doc_store import DocumentationStore from .router import MessageRouter, RoutingDecision logger = logging.getLogger(__name__) @@ -96,6 +97,7 @@ class ArchivarMessageHandler: ) self._router = MessageRouter(self._classifier) self._router.set_confidence_threshold(confidence_threshold) + self._doc_store = DocumentationStore() self._initialized = False # Statistiken (erweitert um Latenz + Fehler) @@ -184,6 +186,20 @@ class ArchivarMessageHandler: self._stats["total"] += 1 if decision.is_meta: self._stats["meta"] += 1 + elif decision.is_unrouteable: + self._stats["classified"] += 1 + # Store in documentation store — message is classified but + # the target room is not in our subscription list + stored = self._doc_store.store( + text=text, + category=decision.category, + confidence=decision.confidence, + reason=decision.unrouteable_reason, + ) + logger.info( + "Unrouteable [%s] stored in doc_store: %s", + decision.category, stored, + ) elif decision.is_fallback: self._stats["fallback"] += 1 elif decision.is_catch_all: @@ -238,6 +254,10 @@ class ArchivarMessageHandler: decision = await self.classify_and_route(text) + # If unrouteable, don't try to forward — message is already in doc_store + if decision.is_unrouteable: + return decision + # Only forward if the target differs from origin if decision.target_room and decision.target_room != origin_room_id: prefix = decision.prefix or "" @@ -339,3 +359,23 @@ class ArchivarMessageHandler: """ self._send_callback = callback logger.debug("Send callback registered") + + def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None: + """Set the bot's current subscribed room IDs for routing validation. + + When set, the router will ONLY forward messages to rooms in this list. + Messages targeting unsubscribed rooms are stored in the + DocumentationStore instead. + + Call this after adapter.connect() when the subscription list is ready. + + Args: + room_ids: List of Rocket.Chat room IDs the bot is currently + subscribed to. Pass None to disable validation. + """ + self._router.set_subscribed_room_ids(room_ids) + + @property + def doc_store(self) -> DocumentationStore: + """Documentation store for unrouteable messages.""" + return self._doc_store diff --git a/plugin/archivar/doc_store.py b/plugin/archivar/doc_store.py new file mode 100644 index 0000000..c5d0dd4 --- /dev/null +++ b/plugin/archivar/doc_store.py @@ -0,0 +1,133 @@ +""" +Documentation store for Archivar — filesystem persistence for messages +that cannot be routed because no room mapping exists or the target room +is not in the bot's subscription list. + +Writes classified-but-unrouteable messages to: + ~/.hermes/hermes-agent/data/archivar_docs/{category}/{timestamp}.md + +Each stored document is a self-contained markdown file with YAML frontmatter +containing classification metadata and a human-readable reason why routing +was blocked. +""" + +from __future__ import annotations + +import os +import time +from pathlib import Path +from typing import Optional + + +def _get_hermes_agent_dir() -> Path: + """Resolve hermes-agent directory (works regardless of HERMES_HOME).""" + hermes_home = os.environ.get("HERMES_HOME", os.path.expanduser("~/.hermes")) + return Path(hermes_home) / "hermes-agent" + + +class DocumentationStore: + """Filesystem store for unrouteable classified messages. + + When the Archivar classifies a message but no valid target room exists + (either because ROOM_MAPPING is empty for that category, or the resolved + target room is not in the bot's current subscription list), the message + is saved here instead of being silently dropped or forwarded to the + wrong room. + + Usage:: + + store = DocumentationStore() + path = store.store( + text="Server monitoring shows CPU spike", + category="FAKT", + confidence=0.92, + reason="ARCHIVAR_FAKT_ROOM not configured", + origin_room="6a19b0ff02aeecd36b1aa16c", + ) + # → ~/.hermes/hermes-agent/data/archivar_docs/fakt/2026-06-03_21-30-00.md + """ + + def __init__(self, base_dir: Optional[Path] = None) -> None: + if base_dir is None: + base_dir = _get_hermes_agent_dir() / "data" / "archivar_docs" + self._base_dir = Path(base_dir) + + def store( + self, + text: str, + category: str, + confidence: float, + reason: str = "", + origin_room: str = "", + ) -> str: + """Store an unrouteable message as a markdown document. + + Args: + text: The original message text. + category: Classification category (FAKT, FRAGE, ALARM). + confidence: Classification confidence (0.0–1.0). + reason: Human-readable reason why routing was blocked. + origin_room: Rocket.Chat room ID where the message originated. + + Returns: + Absolute path to the stored file. + """ + category_dir = self._base_dir / category.lower() + category_dir.mkdir(parents=True, exist_ok=True) + + timestamp = time.strftime("%Y-%m-%d_%H-%M-%S") + filename = f"{timestamp}.md" + filepath = category_dir / filename + + content = self._format_doc(text, category, confidence, reason, origin_room) + filepath.write_text(content, encoding="utf-8") + + return str(filepath) + + @staticmethod + def _format_doc( + text: str, + category: str, + confidence: float, + reason: str, + origin_room: str, + ) -> str: + """Format a message as a documentation entry with YAML frontmatter.""" + timestamp = time.strftime("%Y-%m-%d %H:%M:%S") + return ( + f"---\n" + f"category: {category}\n" + f"confidence: {confidence:.3f}\n" + f"timestamp: {timestamp}\n" + f"origin_room: {origin_room}\n" + f"reason: {reason}\n" + f"---\n\n" + f"# {category}: Unrouteable Message\n\n" + f"**Reason:** {reason}\n\n" + f"{text}\n" + ) + + def list_stored(self, category: str = "") -> list[Path]: + """List stored documents, optionally filtered by category. + + Args: + category: Filter by category name (e.g. 'fakt', 'frage', 'alarm'). + Empty string returns all. + + Returns: + Sorted list of Path objects, newest first. + """ + if category: + target = self._base_dir / category.lower() + else: + target = self._base_dir + + if not target.exists(): + return [] + + return sorted(target.glob("**/*.md"), reverse=True) + + @property + def base_dir(self) -> Path: + """Base directory for stored documents.""" + return self._base_dir diff --git a/plugin/archivar/router.py b/plugin/archivar/router.py index ccad078..2b08d2e 100644 --- a/plugin/archivar/router.py +++ b/plugin/archivar/router.py @@ -85,6 +85,13 @@ class RoutingDecision: is_meta: bool = False """True, wenn die Nachricht als Meta-Frage erkannt wurde.""" + is_unrouteable: bool = False + """True, wenn der Zielraum nicht in den subscribed rooms des Bots ist + und die Nachricht stattdessen im DocumentationStore abgelegt wird.""" + + unrouteable_reason: str = "" + """Grund, warum kein Routing möglich war (nur bei is_unrouteable=True).""" + prefix: str = "" """Optionaler Präfix-Text für die weitergeleitete Nachricht (z.B. [FALLBACK]).""" @@ -104,6 +111,7 @@ class MessageRouter: Usage:: router = MessageRouter(classifier) + router.set_subscribed_room_ids(["6a19...", "6a1f..."]) decision = await router.route("Wie konfiguriere ich das Plugin?") # decision.target_room → "6a19b0ff02aeecd36b1aa16c" (#Rocketchat-Plugin) # decision.category → "FRAGE" @@ -117,6 +125,7 @@ class MessageRouter: """ self._classifier = classifier self._confidence_threshold = CONFIDENCE_THRESHOLD + self._subscribed_room_ids: Optional[set] = None # ── Public API ────────────────────────────────────────────────────── @@ -198,7 +207,7 @@ class MessageRouter: result.category, text ) - return RoutingDecision( + decision = RoutingDecision( category=result.category, target_room=target_room, confidence=result.confidence, @@ -206,6 +215,25 @@ class MessageRouter: project=project, ) + # ── Subscription-Validierung ────────────────────────────────── + self._check_unrouteable(decision) + return decision + + def _check_unrouteable(self, decision: RoutingDecision) -> None: + """Validate target_room against subscribed IDs. + + If the target room is not in the bot's subscription list, mark the + decision as unrouteable so the caller can store the message in the + DocumentationStore instead of forwarding it. + """ + reason = self._validate_target_room(decision.category, decision.target_room) + if reason: + decision.is_unrouteable = True + decision.unrouteable_reason = reason + logger.warning( + "Unrouteable [%s]: %s", decision.category, reason + ) + # ── Room Resolution ──────────────────────────────────────────────── def _resolve_room(self, category: str, text: str = "") -> str: @@ -333,3 +361,43 @@ class MessageRouter: raise ValueError(f"Confidence threshold must be in [0.0, 1.0], got {value}") self._confidence_threshold = value logger.info("Confidence threshold set to %.2f", value) + + def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None: + """Set the bot's current subscribed room IDs for validation. + + When set, the router will ONLY route to rooms that are in this list. + Messages targeting unsubscribed rooms are marked as ``is_unrouteable`` + and should be stored in the DocumentationStore instead. + + Args: + room_ids: List of Rocket.Chat room IDs the bot is subscribed to. + Pass None or empty list to disable validation. + """ + if room_ids: + self._subscribed_room_ids = set(room_ids) + logger.debug( + "Router subscribed IDs set: %d rooms", len(self._subscribed_room_ids) + ) + else: + self._subscribed_room_ids = None + + def _validate_target_room(self, category: str, room_id: str) -> str: + """Validate target room against subscribed IDs. + + Returns: + Empty string if valid. Human-readable reason if blocked. + """ + if not room_id: + return f"no room configured for category '{category}'" + + if self._subscribed_room_ids is None: + return "" # validation disabled + + if room_id not in self._subscribed_room_ids: + return ( + f"target room {room_id[:8]}... for category '{category}' " + f"is not in bot's subscription list " + f"({len(self._subscribed_room_ids)} subscribed rooms)" + ) + + return ""