Files
Hermes_rocket.chat_Plugin/plugin/archivar/archivar_state.py
T
Hermes Agent 6b97ccfad9 feat(archivar): Selbstlernendes Keyword-Gewicht-System (Teil 2)
- KeywordWeightEntry + ManualOverride Dataclasses in archivar_state.py
- Lernalgorithmus: confirm (+0.1), stay (-0.05), never (0.0+sticky)
- Promotion: 3 confirmations + weight ≥0.85 → keywords_100
- Degradation + zeitbasierte Abwertung (Decay: 30d -10%, 90d -30%)
- Cold-Start: Bootstrap Tag 1-7 (LR=0.2), Tag 8+ (LR=0.1)
- Gewichtetes Scoring in find_room_by_keywords()
- Feedback-Schleife in adapter_integration.py nach Move-Request-Auflösung
- 54 Tests grün (inkl. 8 neue für gewichtetes Scoring)
2026-06-12 19:57:46 +02:00

572 lines
23 KiB
Python

"""
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
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from typing import Dict, Optional, Union, List
# 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._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", {})
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
}
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[bool]:
"""Prüfe ob Nachrichten im Raum bleiben sollten.
Args:
room_id: Die ID des Raums.
Returns:
True wenn Nachrichten immer im Raum bleiben sollen,
False wenn sie nie geroutet werden sollen,
None wenn die Entscheidung nicht getroffen wurde.
"""
state = self.get_room_state(room_id)
if not state:
return None
if state.stay_decision == "always":
return True
elif state.stay_decision == "never_route":
return False
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
@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
# 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