# @implements: [F-542] — Helper-Modul (Konversationshistorie für Router V7-4), kein eigenes Feature # TODO: @implements: [F-???] — kein passendes Feature in PMDB gefunden, Funktion: Ring-Buffer-Konversationshistorie pro Raum """ ConversationHistory — Ring-Buffer für Konversationshistorie pro Raum. Sub-Feature B5v6.5: Blocker für V7-3 (Verfall) und V7-4 (rekursive Einleitungen). Speichert die letzten N=10 Nachrichten pro Raum als In-Memory Ring-Buffer. Thread-safe via asyncio.Lock. Nicht persistent — nach Neustart beginnt die Historie neu (akzeptiert von Andreas: 'jetzt' verblasst ohnehin). Usage:: history = ConversationHistory(max_size=10) history.add("room-123", "user", "Was ist der Status?") history.add("room-123", "agent", "Alles grün.") recent = history.get("room-123") # → letzte 10 Nachrichten history.set_topic_hint("room-123", "Deployment-Status") hint = history.get_topic_hint("room-123") # → "Deployment-Status" """ from __future__ import annotations import asyncio import logging from collections import deque from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Any, Dict, List, Optional logger = logging.getLogger(__name__) @dataclass class MessageEntry: """Ein einzelner Eintrag im Ring-Buffer.""" role: str """'user' oder 'agent'.""" text: str """Nachrichtentext.""" timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc)) """Zeitstempel der Nachricht (UTC).""" def to_dict(self) -> Dict[str, Any]: """Serialisiere für externe Nutzung (z.B. Prompt-Bau).""" return { "role": self.role, "text": self.text, "timestamp": self.timestamp.isoformat(), } class ConversationHistory: """Ring-Buffer für Konversationshistorie pro Raum. Thread-safe via asyncio.Lock. In-Memory, nicht persistent. """ def __init__(self, max_size: int = 10) -> None: """Initialisiere den Ring-Buffer. Args: max_size: Maximale Anzahl Nachrichten pro Raum (default: 10). """ if max_size < 1: raise ValueError(f"max_size must be >= 1, got {max_size}") self._max_size = max_size self._lock = asyncio.Lock() # room_id → deque[MessageEntry] (maxlen=self._max_size) self._buffers: Dict[str, deque[MessageEntry]] = {} # room_id → topic string self._topic_hints: Dict[str, str] = {} # ── Public API ────────────────────────────────────────────────────── async def add( self, room_id: str, role: str, text: str, timestamp: Optional[datetime] = None, ) -> None: """Füge eine Nachricht zum Ring-Buffer hinzu. Wenn der Buffer voll ist (max_size erreicht), fällt die älteste Nachricht automatisch heraus (deque mit maxlen). Args: room_id: Rocket.Chat Raum-ID. role: 'user' oder 'agent'. text: Nachrichtentext. timestamp: Optionaler Zeitstempel (default: jetzt UTC). """ if not room_id: return if not text or not text.strip(): return entry = MessageEntry( role=role, text=text.strip(), timestamp=timestamp or datetime.now(timezone.utc), ) async with self._lock: if room_id not in self._buffers: self._buffers[room_id] = deque(maxlen=self._max_size) self._buffers[room_id].append(entry) async def get( self, room_id: str, limit: Optional[int] = None, ) -> List[Dict[str, Any]]: """Liefere die letzten N Nachrichten für einen Raum. Args: room_id: Rocket.Chat Raum-ID. limit: Maximale Anzahl zurückzugebender Nachrichten. None oder > max_size → alle im Buffer (max max_size). Returns: Liste von dicts mit 'role', 'text', 'timestamp' (ISO-Format), neueste zuletzt. Leere Liste wenn Raum nicht existiert. """ async with self._lock: buf = self._buffers.get(room_id) if buf is None: return [] entries = list(buf) if limit is not None and limit < len(entries): entries = entries[-limit:] return [e.to_dict() for e in entries] async def get_topic_hint(self, room_id: str) -> Optional[str]: """Liefere das letzte bekannte Thema für einen Raum. Args: room_id: Rocket.Chat Raum-ID. Returns: Thema-String oder None wenn kein Thema gesetzt. """ async with self._lock: return self._topic_hints.get(room_id) async def set_topic_hint(self, room_id: str, topic: str) -> None: """Setze das Thema für einen Raum. Wird vom Router gesetzt, wenn das LLM ein Thema erkennt. Überschreibt ein vorheriges Thema. Args: room_id: Rocket.Chat Raum-ID. topic: Thema-String (z.B. 'Deployment-Status'). """ if not room_id or not topic: return async with self._lock: self._topic_hints[room_id] = topic.strip() logger.debug( "Topic hint set for room %s: %s", room_id[:8], topic[:60], ) async def clear(self, room_id: str) -> None: """Lösche die Historie für einen Raum (M13 GC). Args: room_id: Rocket.Chat Raum-ID. """ async with self._lock: self._buffers.pop(room_id, None) self._topic_hints.pop(room_id, None) logger.debug("Conversation history cleared for room %s", room_id[:8]) async def cleanup_orphaned_rooms(self, active_room_ids: set) -> int: """Entferne Räume, die nicht mehr aktiv sind (M13 GC). Thread-safe via asyncio.Lock. Args: active_room_ids: Set von Raum-IDs, die noch aktiv sind (aus room-map.json nach M13-Bereinigung). Returns: Anzahl der entfernten Räume. """ async with self._lock: return self.cleanup_orphaned_rooms_sync(active_room_ids) def cleanup_orphaned_rooms_sync(self, active_room_ids: set) -> int: """Sync-Variante für M13 GC (Startup, kein Concurrent-Access). Args: active_room_ids: Set von Raum-IDs, die noch aktiv sind. Returns: Anzahl der entfernten Räume. """ orphaned = [ rid for rid in self._buffers if rid not in active_room_ids ] for rid in orphaned: del self._buffers[rid] self._topic_hints.pop(rid, None) if orphaned: logger.info( "ConversationHistory GC: %d orphaned rooms removed (%d remaining)", len(orphaned), len(self._buffers), ) return len(orphaned) # ── Utility ───────────────────────────────────────────────────────── @property def max_size(self) -> int: """Maximale Anzahl Nachrichten pro Raum.""" return self._max_size @property def room_count(self) -> int: """Anzahl der Räume mit Historie (nicht thread-safe, für Debug).""" return len(self._buffers) async def get_room_count(self) -> int: """Thread-safe: Anzahl der Räume mit Historie.""" async with self._lock: return len(self._buffers)