""" Persistenz-Layer für Archivar v3. Speichert und lädt Raum-Zustände für das Routing-Verhalten. Die Zustände werden in einer JSON-Datei gespeichert und über Neustarts hinweg persistiert. """ from __future__ import annotations import json import logging import os import time from dataclasses import dataclass, field from datetime import datetime, timedelta from typing import Dict, Optional, Union, List, Any # Use absolute import instead of relative import try: from config import ARCHIVAR_STATE_PATH except ImportError: # Fallback for testing ARCHIVAR_STATE_PATH = "~/.hermes/hermes-agent/data/archivar-state.json" logger = logging.getLogger(__name__) @dataclass class RoomState: """Zustand eines Raums für das Archivar-Routing.""" stay_decision: str # "always"|"ask"|"never_route" decided_at: str # ISO-Zeitstempel decided_by: str # Benutzername @dataclass class KeywordWeightEntry: """Eintrag für ein Keyword-Gewicht in einem Raum.""" weight: float last_updated: str # ISO-Zeitstempel confirmation_count: int rejection_count: int last_confirmation: Optional[str] # ISO-Zeitstempel oder None @dataclass class ManualOverride: """Manueller Override für ein Keyword-Gewicht.""" override_weight: float override_reason: str override_date: str # ISO-Zeitstempel override_by: str class ArchivarState: """Persistenz-Layer für Archivar v3 Raum-Zustände.""" def __init__(self, state_file_path: Optional[str] = None) -> None: """ Args: state_file_path: Pfad zur JSON-Datei für den Zustand. Wenn None, wird der Standardpfad aus der Konfiguration verwendet. """ self._state_file_path = state_file_path or ARCHIVAR_STATE_PATH self._rooms: Dict[str, RoomState] = {} self._keyword_weights: Dict[str, Dict[str, KeywordWeightEntry]] = {} self._sticky_keywords: Dict[str, List[str]] = {} # keyword -> list of room_ids self._manual_overrides: Dict[str, Dict[str, ManualOverride]] = {} self._promotion_candidates: Dict[str, Dict[str, Dict[str, Union[float, str]]]] = {} self._stay_tracker: Dict[str, Dict[str, Union[int, float]]] = {} self._onboarding_state: Dict[str, Any] = {} self._loaded = False def load(self) -> bool: """Lade den Zustand aus der Datei. Returns: True wenn erfolgreich geladen, False bei Fehler. """ try: # Stelle sicher, dass das Verzeichnis existiert os.makedirs(os.path.dirname(self._state_file_path), exist_ok=True) if not os.path.exists(self._state_file_path): # Erstelle eine leere Datei wenn sie nicht existiert self._save_to_file({}) logger.info("Created new archivar state file: %s", self._state_file_path) return True with open(self._state_file_path, 'r', encoding='utf-8') as f: data = json.load(f) rooms_data = data.get("rooms", {}) self._rooms = {} for room_id, state_data in rooms_data.items(): self._rooms[room_id] = RoomState( stay_decision=state_data["stay_decision"], decided_at=state_data["decided_at"], decided_by=state_data["decided_by"] ) # Lade Keyword-Gewichte keyword_weights_data = data.get("keyword_weights", {}) self._keyword_weights = {} for keyword, rooms_data in keyword_weights_data.items(): self._keyword_weights[keyword] = {} for room_id, weight_data in rooms_data.items(): self._keyword_weights[keyword][room_id] = KeywordWeightEntry( weight=weight_data["weight"], last_updated=weight_data["last_updated"], confirmation_count=weight_data["confirmation_count"], rejection_count=weight_data["rejection_count"], last_confirmation=weight_data["last_confirmation"] ) # Lade Sticky-Keywords self._sticky_keywords = data.get("sticky_keywords", {}) # Lade manuelle Overrides manual_overrides_data = data.get("manual_overrides", {}) self._manual_overrides = {} for keyword, rooms_data in manual_overrides_data.items(): self._manual_overrides[keyword] = {} for room_id, override_data in rooms_data.items(): self._manual_overrides[keyword][room_id] = ManualOverride( override_weight=override_data["override_weight"], override_reason=override_data["override_reason"], override_date=override_data["override_date"], override_by=override_data["override_by"] ) # Lade Promotion-Kandidaten self._promotion_candidates = data.get("promotion_candidates", {}) # Lade stay_tracker (P1-3: persistent über Neustarts) self._stay_tracker = data.get("stay_tracker", {}) # Lade onboarding_state (P1-4: persistent über Neustarts) self._onboarding_state = data.get("onboarding_state", {}) self._loaded = True logger.info("Loaded archivar state for %d rooms", len(self._rooms)) return True except Exception as e: logger.error("Failed to load archivar state: %s", e) return False def save(self) -> bool: """Speichere den aktuellen Zustand in die Datei. Returns: True wenn erfolgreich gespeichert, False bei Fehler. """ try: return self._save_to_file(self._to_dict()) except Exception as e: logger.error("Failed to save archivar state: %s", e) return False def _save_to_file(self, data: dict) -> bool: """Speichere Daten in die Zustandsdatei.""" try: # Stelle sicher, dass das Verzeichnis existiert os.makedirs(os.path.dirname(self._state_file_path), exist_ok=True) with open(self._state_file_path, 'w', encoding='utf-8') as f: json.dump(data, f, indent=2, ensure_ascii=False) logger.debug("Saved archivar state to %s", self._state_file_path) return True except Exception as e: logger.error("Failed to write archivar state file: %s", e) return False def _to_dict(self) -> dict: """Konvertiere den Zustand in ein serialisierbares Dictionary.""" rooms_dict = {} for room_id, state in self._rooms.items(): rooms_dict[room_id] = { "stay_decision": state.stay_decision, "decided_at": state.decided_at, "decided_by": state.decided_by } # Konvertiere Keyword-Gewichte keyword_weights_dict = {} for keyword, rooms_data in self._keyword_weights.items(): keyword_weights_dict[keyword] = {} for room_id, weight_entry in rooms_data.items(): keyword_weights_dict[keyword][room_id] = { "weight": weight_entry.weight, "last_updated": weight_entry.last_updated, "confirmation_count": weight_entry.confirmation_count, "rejection_count": weight_entry.rejection_count, "last_confirmation": weight_entry.last_confirmation } # Konvertiere manuelle Overrides manual_overrides_dict = {} for keyword, rooms_data in self._manual_overrides.items(): manual_overrides_dict[keyword] = {} for room_id, override_entry in rooms_data.items(): manual_overrides_dict[keyword][room_id] = { "override_weight": override_entry.override_weight, "override_reason": override_entry.override_reason, "override_date": override_entry.override_date, "override_by": override_entry.override_by } return { "rooms": rooms_dict, "keyword_weights": keyword_weights_dict, "sticky_keywords": self._sticky_keywords, "manual_overrides": manual_overrides_dict, "promotion_candidates": self._promotion_candidates, "stay_tracker": self._stay_tracker, "onboarding_state": self._onboarding_state, } def get_room_state(self, room_id: str) -> Optional[RoomState]: """Hole den Zustand für einen Raum. Args: room_id: Die ID des Raums. Returns: RoomState wenn vorhanden, sonst None. """ if not self._loaded: self.load() return self._rooms.get(room_id) def set_room_state(self, room_id: str, decision: str, decided_by: str) -> bool: """Setze den Zustand für einen Raum. Args: room_id: Die ID des Raums. decision: Die Entscheidung ("always"|"ask"|"never_route"). decided_by: Der Benutzer, der die Entscheidung getroffen hat. Returns: True wenn erfolgreich gespeichert, False bei Fehler. """ if decision not in ("always", "ask", "never_route"): logger.error("Invalid stay decision: %s", decision) return False state = RoomState( stay_decision=decision, decided_at=datetime.now().isoformat(), decided_by=decided_by ) self._rooms[room_id] = state # Speichere sofort return self.save() def should_stay_in_room(self, room_id: str) -> Optional[str]: """Prüfe ob Nachrichten im Raum bleiben sollten. Args: room_id: Die ID des Raums. Returns: 'origin_first' wenn Nachrichten immer im Raum bleiben sollen (Origin-First Guard — same room, kein Move-Request nötig), 'sticky' wenn sie nie geroutet werden sollen (Sticky — Move-Request bereits beantwortet, kein neuer Move-Request), None wenn die Entscheidung nicht getroffen wurde (Move-Request möglich). """ state = self.get_room_state(room_id) if not state: return None if state.stay_decision == "always": return "origin_first" elif state.stay_decision == "never_route": return "sticky" else: return None # "ask" - Entscheidung pro Nachricht def remove_room_state(self, room_id: str) -> bool: """Entferne den Zustand für einen Raum. Args: room_id: Die ID des Raums. Returns: True wenn erfolgreich entfernt, False bei Fehler. """ if room_id in self._rooms: del self._rooms[room_id] return self.save() return True def cleanup_orphaned_rooms(self, valid_room_ids: set) -> int: """M13: Entferne alle Zustandsdaten für Räume, die nicht mehr in room-map.json sind. Bereinigt: - ``_rooms`` (stay_decision: always/ask/never_route) - ``_keyword_weights`` (gelernte Keyword-Gewichte pro Raum) - ``_sticky_keywords`` (sticky-Raum-Referenzen) - ``_manual_overrides`` (manuelle Override-Referenzen) - ``_promotion_candidates`` (Promotion-Kandidaten-Referenzen) Args: valid_room_ids: Set von Raum-IDs, die BEHALTEN werden sollen (aus der bereinigten room-map.json). Returns: Anzahl der entfernten Einträge (Summe über alle Kategorien). """ removed = 0 # 1. Room states (stay_decision) orphaned_rooms = [rid for rid in self._rooms if rid not in valid_room_ids] for rid in orphaned_rooms: del self._rooms[rid] removed += 1 if orphaned_rooms: logger.info( "ArchivarState GC: %d orphaned room states removed (%s)", len(orphaned_rooms), ", ".join(f"{rid[:8]}…" for rid in orphaned_rooms[:5]), ) # 2. Keyword weights: entferne Einträge für orphaned rooms for keyword, rooms_dict in list(self._keyword_weights.items()): orphaned = [rid for rid in rooms_dict if rid not in valid_room_ids] for rid in orphaned: del self._keyword_weights[keyword][rid] removed += 1 # Wenn das Keyword jetzt keine Räume mehr hat → ganz löschen if not self._keyword_weights[keyword]: del self._keyword_weights[keyword] # 3. Sticky keywords: entferne orphaned room_ids aus Listen for keyword, room_list in list(self._sticky_keywords.items()): before = len(room_list) self._sticky_keywords[keyword] = [ rid for rid in room_list if rid in valid_room_ids ] removed += before - len(self._sticky_keywords[keyword]) if not self._sticky_keywords[keyword]: del self._sticky_keywords[keyword] # 4. Manual overrides: entferne Einträge für orphaned rooms for keyword, rooms_dict in list(self._manual_overrides.items()): orphaned = [rid for rid in rooms_dict if rid not in valid_room_ids] for rid in orphaned: del self._manual_overrides[keyword][rid] removed += 1 if not self._manual_overrides[keyword]: del self._manual_overrides[keyword] # 5. Promotion candidates: entferne Einträge für orphaned rooms for keyword, rooms_dict in list(self._promotion_candidates.items()): orphaned = [rid for rid in rooms_dict if rid not in valid_room_ids] for rid in orphaned: del self._promotion_candidates[keyword][rid] removed += 1 if not self._promotion_candidates[keyword]: del self._promotion_candidates[keyword] if removed > 0: self.save() logger.info( "ArchivarState GC: %d total orphaned entries removed across all categories", removed, ) return removed @property def rooms(self) -> Dict[str, RoomState]: """Gibt eine Kopie der aktuellen Räume zurück.""" return self._rooms.copy() @property def is_loaded(self) -> bool: """True wenn der Zustand geladen wurde.""" return self._loaded # ── P1-3: stay_tracker Persistenz ────────────────────────────────── def get_stay_tracker(self) -> Dict[str, Dict[str, Union[int, float]]]: """Gibt den stay_tracker zurück (für Auto-Promotion nach 3x 'Hier bleiben').""" if not self._loaded: self.load() return self._stay_tracker def update_stay_tracker(self, room_id: str, username: str) -> int: """Inkrementiert den stay-Counter für einen Raum und speichert. Returns: Aktueller Count nach Inkrement. """ now = time.time() stay_key = f"{room_id}:{username}" stay_data = self._stay_tracker.get(stay_key, {"count": 0, "first_seen": now}) if now - stay_data["first_seen"] > 600: # 10 Minuten Fenster stay_data = {"count": 0, "first_seen": now} stay_data["count"] += 1 self._stay_tracker[stay_key] = stay_data self.save() return int(stay_data["count"]) def cleanup_stay_tracker(self, valid_room_ids: set) -> int: """Entfernt stay_tracker-Einträge für gelöschte Räume.""" removed = 0 for stay_key in list(self._stay_tracker.keys()): rid = stay_key.split(":", 1)[0] if ":" in stay_key else stay_key if rid not in valid_room_ids: del self._stay_tracker[stay_key] removed += 1 if removed > 0: self.save() return removed # ── P1-4: onboarding_state Persistenz ────────────────────────────── def get_onboarding_state(self) -> Dict[str, Any]: """Gibt den onboarding_state zurück.""" if not self._loaded: self.load() return self._onboarding_state def set_onboarding_state(self, state: Dict[str, Any]) -> bool: """Speichert den onboarding_state persistent.""" self._onboarding_state = state return self.save() def clear_onboarding_state(self) -> bool: """Löscht den onboarding_state.""" self._onboarding_state = {} return self.save() # Neue Methoden für das selbstlernende Keyword-Gewicht-System def update_keyword_weight(self, keyword: str, room_id: str, feedback_type: str) -> bool: """ Aktualisiert das Gewicht basierend auf Benutzerfeedback. Args: keyword: Das betroffene Keyword room_id: Die Zielraum-ID feedback_type: "confirm", "stay", oder "never" Returns: True wenn das Gewicht erfolgreich aktualisiert wurde """ try: # Initialisiere Einträge falls nicht vorhanden if keyword not in self._keyword_weights: self._keyword_weights[keyword] = {} # Hole oder erstelle den Gewichtseintrag if room_id not in self._keyword_weights[keyword]: # Cold-Start: Initialgewicht basierend auf Anzahl der Räume # (wir nehmen an, dass mindestens 3 Räume existieren) initial_weight = 1.0 / 3.0 self._keyword_weights[keyword][room_id] = KeywordWeightEntry( weight=initial_weight, last_updated=datetime.now().isoformat(), confirmation_count=0, rejection_count=0, last_confirmation=None ) entry = self._keyword_weights[keyword][room_id] # Bestimme die Lernrate basierend auf der Anzahl der Bestätigungen # Tag 1-7: LEARNING_RATE = 0.2, Tag 8+: LEARNING_RATE = 0.1 learning_rate = 0.2 if entry.confirmation_count < 7 else 0.1 # Hole die aktuelle Zeit now = datetime.now().isoformat() # Hole alle Räume mit Gewichten für dieses Keyword (außer dem Zielraum) other_rooms = {rid: weight_entry for rid, weight_entry in self._keyword_weights[keyword].items() if rid != room_id} if feedback_type == "confirm": # Positives Feedback (✅Ja / "confirm") # new_weight = old_weight + (1 - old_weight) * LEARNING_RATE new_weight = entry.weight + (1 - entry.weight) * learning_rate # Begrenze das Gewicht auf maximal 0.95 new_weight = min(new_weight, 0.95) # Verteile reduziertes Gewicht auf andere Räume if other_rooms: weight_reduction = (1 - entry.weight) * learning_rate reduction_per_room = weight_reduction / len(other_rooms) for other_room_id, other_entry in other_rooms.items(): # other_weight = other_weight - (other_weight * LEARNING_RATE / num_other_rooms) reduced_weight = other_entry.weight - (other_entry.weight * learning_rate / len(other_rooms)) # Begrenze das Gewicht auf minimal 0.05 reduced_weight = max(reduced_weight, 0.05) # Aktualisiere den Eintrag self._keyword_weights[keyword][other_room_id] = KeywordWeightEntry( weight=reduced_weight, last_updated=now, confirmation_count=other_entry.confirmation_count, rejection_count=other_entry.rejection_count, last_confirmation=other_entry.last_confirmation ) # Aktualisiere den Zielraum self._keyword_weights[keyword][room_id] = KeywordWeightEntry( weight=new_weight, last_updated=now, confirmation_count=entry.confirmation_count + 1, rejection_count=entry.rejection_count, last_confirmation=now ) elif feedback_type == "stay": # Schwach negatives Feedback (📍Hier / "stay") # new_weight = old_weight - old_weight * LEARNING_RATE * 0.5 new_weight = entry.weight - entry.weight * learning_rate * 0.5 # Begrenze das Gewicht auf minimal 0.05 new_weight = max(new_weight, 0.05) # Verteile Gewicht auf andere Räume if other_rooms: weight_addition = (1 - entry.weight) * learning_rate * 0.5 addition_per_room = weight_addition / len(other_rooms) for other_room_id, other_entry in other_rooms.items(): # other_weight = other_weight + ((1 - other_weight) * LEARNING_RATE * 0.5 / num_other_rooms) increased_weight = other_entry.weight + ((1 - other_entry.weight) * learning_rate * 0.5 / len(other_rooms)) # Begrenze das Gewicht auf maximal 0.95 increased_weight = min(increased_weight, 0.95) # Aktualisiere den Eintrag self._keyword_weights[keyword][other_room_id] = KeywordWeightEntry( weight=increased_weight, last_updated=now, confirmation_count=other_entry.confirmation_count, rejection_count=other_entry.rejection_count, last_confirmation=other_entry.last_confirmation ) # Aktualisiere den Zielraum self._keyword_weights[keyword][room_id] = KeywordWeightEntry( weight=new_weight, last_updated=now, confirmation_count=entry.confirmation_count, rejection_count=entry.rejection_count + 1, last_confirmation=entry.last_confirmation ) elif feedback_type == "never": # Stark negatives Feedback (📌Generell / "never") # Setze Gewicht auf 0.0 self._keyword_weights[keyword][room_id] = KeywordWeightEntry( weight=0.0, last_updated=now, confirmation_count=entry.confirmation_count, rejection_count=entry.rejection_count + 2, # Zählt als 2 negative Bestätigungen last_confirmation=entry.last_confirmation ) # Füge Keyword zu sticky_keywords für diesen Raum hinzu if keyword not in self._sticky_keywords: self._sticky_keywords[keyword] = [] if room_id not in self._sticky_keywords[keyword]: self._sticky_keywords[keyword].append(room_id) # Prüfe auf Promotion-Berechtigung self.check_promotion_eligibility(keyword, room_id) # Speichere den aktualisierten Zustand return self.save() except Exception as e: logger.error("Failed to update keyword weight: %s", e) return False def calculate_room_score(self, keyword: str, room_id: str) -> float: """ Berechnet den Score für ein Keyword in einem Raum unter Berücksichtigung von Overrides, Sticky-Rooms und gelernten Gewichten. Args: keyword: Das zu bewertende Keyword room_id: Die Raum-ID Returns: Der berechnete Score (0.0 - 1.0) """ # Prüfe manuelle Overrides (höchste Priorität) if keyword in self._manual_overrides and room_id in self._manual_overrides[keyword]: return self._manual_overrides[keyword][room_id].override_weight # Prüfe Sticky-Rooms (Gewicht 0.0) if keyword in self._sticky_keywords and room_id in self._sticky_keywords[keyword]: return 0.0 # Verwende gelerntes Gewicht if keyword in self._keyword_weights and room_id in self._keyword_weights[keyword]: return self._keyword_weights[keyword][room_id].weight # Default: Gleichverteilung basierend auf Anzahl der Räume # (angenommen mindestens 3 Räume) return 1.0 / 3.0 def check_promotion_eligibility(self, keyword: str, room_id: str) -> bool: """ Prüft ob ein Keyword für die Promotion in keywords_100 berechtigt ist. Args: keyword: Das zu prüfende Keyword room_id: Die Raum-ID Returns: True wenn das Keyword förderfähig ist, False sonst """ try: # Prüfe ob das Keyword existiert if keyword not in self._keyword_weights or room_id not in self._keyword_weights[keyword]: return False entry = self._keyword_weights[keyword][room_id] # Prüfe Kriterien für Promotion: # - Mindestens 3 confirmations # - Gewicht ≥ 0.85 # - Keine rejections im gleichen Raum if (entry.confirmation_count >= 3 and entry.weight >= 0.85 and entry.rejection_count == 0): # Trage in Promotion-Kandidaten ein if keyword not in self._promotion_candidates: self._promotion_candidates[keyword] = {} self._promotion_candidates[keyword][room_id] = { "score": entry.confirmation_count + entry.weight, # Einfache Scoring-Formel "last_updated": datetime.now().isoformat() } # Speichere den aktualisierten Zustand self.save() return True return False except Exception as e: logger.error("Failed to check promotion eligibility: %s", e) return False def apply_decay(self) -> bool: """ Wendet zeitbasierte Abwertung (Decay) an. - 30 Tage: -10% - 90 Tage: -30% Returns: True wenn Decay erfolgreich angewendet wurde, False bei Fehler """ try: now = datetime.now() updated = False # Iteriere durch alle Keywords und Räume for keyword, rooms_data in self._keyword_weights.items(): for room_id, entry in rooms_data.items(): # Parse das last_updated Datum try: last_updated = datetime.fromisoformat(entry.last_updated) except ValueError: # Falls das Datum nicht geparst werden kann, überspringen continue # Berechne die Zeitdifferenz in Tagen days_diff = (now - last_updated).days # Wende Decay an, wenn nötig new_weight = entry.weight if days_diff >= 90: # 90 Tage: -30% new_weight = entry.weight * 0.7 elif days_diff >= 30: # 30 Tage: -10% new_weight = entry.weight * 0.9 # Nur aktualisieren, wenn sich das Gewicht geändert hat if new_weight != entry.weight: self._keyword_weights[keyword][room_id] = KeywordWeightEntry( weight=new_weight, last_updated=entry.last_updated, # Datum bleibt unverändert confirmation_count=entry.confirmation_count, rejection_count=entry.rejection_count, last_confirmation=entry.last_confirmation ) updated = True # Speichere Änderungen, wenn welche vorgenommen wurden if updated: return self.save() return True except Exception as e: logger.error("Failed to apply decay: %s", e) return False