diff --git a/plugin/adapter.py b/plugin/adapter.py index 7feea2a..6c3e800 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -6699,6 +6699,10 @@ class RocketChatAdapter(BasePlatformAdapter): review alle ✅ — Bestätigt alle. review alle ❌ — Verwirft alle. status — Zeigt wieviele Stichworte pro Raum gesammelt sind. + curate — Triggert den Butler-Kurator sofort (manuell). + curate status — Zeigt last_curation_ts/mode + pending_total. + curate undo — Stellt den letzten Kurator-Lauf wieder her. + curate log [N] — Zeigt die letzten N Kurationen. """ if not _MULTIROOM() or self.archivar is None: return "❌ `::keywords` ist nur im Multiroom-Modus verfügbar." @@ -6711,6 +6715,10 @@ class RocketChatAdapter(BasePlatformAdapter): action = parts[0].lower() if parts else "review" rest = parts[1] if len(parts) > 1 else "" + # ── :: keywords curate ───────────────────────────────────────── + if action == "curate": + return await self._cmd_keywords_curate(room_id, rest) + # ── :: keywords status ──────────────────────────────────────── if action == "status": from archivar.inline_commands import build_keywords_status_text @@ -6741,7 +6749,86 @@ class RocketChatAdapter(BasePlatformAdapter): return ( f"❌ Unbekannte Option: `{sub}`\n\n" "Verfügbar: `review`, `review ✅ `, `review ❌ `, " - "`review alle ✅`, `review alle ❌`, `status`" + "`review alle ✅`, `review alle ❌`, `status`, `curate`, " + "`curate status`, `curate undo `, `curate log [N]`" + ) + + async def _cmd_keywords_curate(self, room_id: str, rest: str) -> str: + """::keywords curate — Butler-Kurator (manueller Trigger + Status/Undo/Log).""" + state = self.archivar._state + room_map = getattr(self.archivar, "_room_map", None) + + from archivar.butler_curator import ButlerCurator + + # send_fn: Rückfrage an den Operator-DM (NICHT User-Räume, §6.5). + def _send_to_operator(text: str) -> None: + op_room = self._find_operator_room() + if not op_room: + logger.warning("[rocketchat] Kurator: kein Operator-DM — Rückfrage verworfen") + return + try: + self.post_message(op_room, text) + except Exception as e: + logger.warning("[rocketchat] Kurator: Rückfrage-Send fehlgeschlagen: %s", e) + + curator = ButlerCurator(state=state, room_map=room_map, send_fn=_send_to_operator) + + sub = rest.strip() + parts = sub.split(None, 1) + sub_action = parts[0].lower() if parts else "" + sub_rest = parts[1] if len(parts) > 1 else "" + + # ── :: keywords curate (ohne Subcommand) → Lauf triggern ────── + if not sub_action: + run_id = curator.run_curation(trigger_mode="manual", trigger_reason="inline command") + if run_id is None: + return "⏸️ Kurator übersprungen (Cooldown aktiv oder keine pending Keywords)." + return f"🤖 Butler-Kurator-Lauf gestartet. `run_id`: `{run_id}`" + + # ── :: keywords curate status ───────────────────────────────── + if sub_action == "status": + s = curator.get_status() + ts = s.get("last_curation_ts") or "nie" + mode = s.get("last_curation_mode") or "—" + return ( + f"📋 **Butler-Kurator Status**\n\n" + f"- Letzter Lauf: {ts}\n" + f"- Modus: {mode}\n" + f"- Pending Keywords gesamt: {s.get('pending_total', 0)}" + ) + + # ── :: keywords curate undo ────────────────────────── + if sub_action == "undo": + if not sub_rest: + return "❌ Bitte gib die `run_id` an: `:: keywords curate undo `." + result = curator.undo_last_curation(sub_rest.strip()) + if not result.get("ok"): + return f"❌ Undo fehlgeschlagen: {result.get('error', 'unbekannt')}" + return f"✅ {result.get('restored', 0)} Keyword(s) wiederhergestellt." + + # ── :: keywords curate log [N] ──────────────────────────────── + if sub_action == "log": + try: + n = int(sub_rest) if sub_rest else 5 + except ValueError: + return f"❌ Ungültige Anzahl: `{sub_rest}`." + entries = curator.get_log(n) + if not entries: + return "📋 Keine Kurator-Läufe protokolliert." + lines = ["📋 **Butler-Kurator Log**", ""] + for e in entries: + stats = e.get("stats", {}) + lines.append( + f"- `{e.get('run_id')}` ({e.get('mode')}) — " + f"{stats.get('pending_total', 0)} pending, " + f"{len(e.get('verworfen', []))} verworfen, " + f"{len(e.get('rueckfrage', []))} Rückfrage" + ) + return "\n".join(lines) + + return ( + f"❌ Unbekannte Option: `{sub}`\n\n" + "Verfügbar: `curate`, `curate status`, `curate undo `, `curate log [N]`" ) async def _evaluate_pending_keywords(self, room_id: str, rest: str) -> str: diff --git a/plugin/archivar/archivar_state.py b/plugin/archivar/archivar_state.py index 075244a..b8bebfc 100644 --- a/plugin/archivar/archivar_state.py +++ b/plugin/archivar/archivar_state.py @@ -10,6 +10,7 @@ from __future__ import annotations import json import logging import os +import secrets import time from dataclasses import dataclass, field from datetime import datetime, timedelta @@ -96,6 +97,13 @@ class ArchivarState: # Wird vom Silent-Collector-Modus befüllt und von :: keywords review # bewertet (✅ → keywords_100, ❌ → verworfen). Persistiert über Neustarts. self._pending_keywords: Dict[str, Dict[str, Dict[str, Any]]] = {} + # Butler-Kurator: curation_log + Trigger-Telemetrie (Konzept §2.1). + # curation_log: Liste der letzten Läufe (max 20, FIFO). + # last_curation_ts: ISO8601 des letzten Laufs (für 24h-Cooldown). + # last_curation_mode: "time" | "count" | "manual" (Telemetrie). + self._curation_log: List[Dict[str, Any]] = [] + self._last_curation_ts: Optional[str] = None + self._last_curation_mode: Optional[str] = None self._loaded = False def load(self) -> bool: @@ -180,6 +188,11 @@ class ArchivarState: # V3 (Silent Collector): pending_keywords laden self._pending_keywords = data.get("pending_keywords", {}) + # Butler-Kurator: curation_log + Trigger-Telemetrie laden (Defaults). + self._curation_log = data.get("curation_log", []) + self._last_curation_ts = data.get("last_curation_ts") + self._last_curation_mode = data.get("last_curation_mode") + # ── P0-B: never_route v7 Migration ────────────────────────── # v6: never_route war ein Set von room_ids (nicht gespeichert) # v7: never_route ist Dict[room_id][topic] → {state, timestamp, ...} @@ -281,6 +294,9 @@ class ArchivarState: "routing_use_counter": self._routing_use_counter, # Stufe 5 "promoted_pairs": [list(p) for p in self._promoted_pairs], # P-112 "pending_keywords": self._pending_keywords, # V3 Silent Collector + "curation_log": self._curation_log, # Butler-Kurator + "last_curation_ts": self._last_curation_ts, # Butler-Kurator + "last_curation_mode": self._last_curation_mode, # Butler-Kurator } def get_room_state(self, room_id: str) -> Optional[RoomState]: @@ -1670,4 +1686,193 @@ class ArchivarState: if not room_pending: del self._pending_keywords[room_id] return self.save() - return True \ No newline at end of file + return True + + # ── Butler-Kurator: curation_log + Trigger-Telemetrie ──────────────── + + def get_total_pending_count(self) -> int: + """Kurator: Gesamtzahl pending Keywords über alle Räume (TTL-bereinigt).""" + if not self._loaded: + self.load() + total = 0 + for room_id in list(self._pending_keywords.keys()): + total += self.get_pending_keyword_count(room_id) + return total + + def get_all_pending_keywords(self) -> List[Dict[str, Any]]: + """Kurator: Flache Liste aller pending Keywords über alle Räume. + + Returns: + Liste von ``{keyword, room_id, counter, first_seen, last_seen, source}``. + """ + if not self._loaded: + self.load() + items: List[Dict[str, Any]] = [] + for room_id in list(self._pending_keywords.keys()): + for keyword, entry in self.get_pending_keywords(room_id).items(): + items.append({ + "keyword": keyword, + "room_id": room_id, + "counter": int(entry.get("counter", 1)), + "first_seen": entry.get("first_seen", 0), + "last_seen": entry.get("last_seen", 0), + "source": entry.get("source", ""), + }) + return items + + def can_curate_now(self, cooldown_hours: int = 24) -> bool: + """Kurator: Cooldown-Check (Konzept §3.2). + + Returns: + True wenn der letzte Lauf länger als ``cooldown_hours`` her ist + (oder noch nie gelaufen ist). + """ + if not self._loaded: + self.load() + if not self._last_curation_ts: + return True + try: + last = datetime.fromisoformat(self._last_curation_ts) + except (ValueError, TypeError): + return True + return (datetime.now() - last) > timedelta(hours=cooldown_hours) + + def record_curation_run( + self, + stats: Dict[str, Any], + verworfen: List[Dict[str, Any]], + rueckfrage: List[Dict[str, Any]], + mode: str = "manual", + trigger_reason: str = "", + ) -> str: + """Kurator: Protokolliert einen Lauf in ``curation_log`` (FIFO, max 20). + + Args: + stats: Telemetrie-Dict (pending_total, stufe1..4, llm_calls, duration_ms). + verworfen: Liste der eigenmächtig verworfenen Keywords. + rueckfrage: Liste der Top-N-Rückfrage-Items. + mode: "time" | "count" | "manual". + trigger_reason: Freitext-Grund. + + Returns: + Der generierte ``run_id``. + """ + if not self._loaded: + self.load() + now = datetime.now() + run_id = f"cur_{now.strftime('%Y%m%d_%H%M%S')}_{secrets.token_hex(2)}" + entry = { + "run_id": run_id, + "ts": now.isoformat(), + "mode": mode, + "trigger_reason": trigger_reason, + "stats": stats, + "verworfen": verworfen, + "rueckfrage": rueckfrage, + "operator_response": None, + "operator_response_ts": None, + } + self._curation_log.append(entry) + # FIFO-Prune (FM8): max 20 Einträge. + if len(self._curation_log) > 20: + self._curation_log = self._curation_log[-20:] + self._last_curation_ts = now.isoformat() + self._last_curation_mode = mode + self.save() + return run_id + + def apply_curation_response( + self, run_id: str, operator_response: Dict[str, str] + ) -> bool: + """Kurator: Wendet die Operator-Entscheidung auf einen Lauf an. + + ``operator_response``: ``{keyword: "✅" | "❌" | "other"}``. + + Args: + run_id: Der Lauf, auf den geantwortet wird. + operator_response: Mapping keyword → Entscheidung. + + Returns: + True wenn der Lauf gefunden und die Antwort gespeichert wurde. + """ + if not self._loaded: + self.load() + for entry in self._curation_log: + if entry.get("run_id") == run_id: + entry["operator_response"] = operator_response + entry["operator_response_ts"] = datetime.now().isoformat() + self.save() + return True + logger.warning("Kurator: apply_curation_response — run_id '%s' nicht gefunden", run_id) + return False + + def undo_last_curation(self, run_id: str) -> Dict[str, Any]: + """Kurator: Stellt den letzten Lauf wieder her (Konzept §3.3). + + Nur der LETZTE Eintrag im ``curation_log`` ist undo-fähig. Die + verworfenen Keywords werden zurück nach ``pending_keywords`` gelegt. + + Args: + run_id: Der erwartete ``run_id`` des letzten Laufs. + + Returns: + ``{"ok": bool, "restored": int, "error": str}``. + """ + if not self._loaded: + self.load() + if not self._curation_log: + return {"ok": False, "restored": 0, "error": "kein Kurator-Lauf vorhanden"} + last = self._curation_log[-1] + if last.get("run_id") != run_id: + return { + "ok": False, + "restored": 0, + "error": "nur der letzte Lauf ist undo-fähig", + } + restored = 0 + for item in last.get("verworfen", []): + keyword = item.get("keyword", "") + if not keyword: + continue + # room_id aus dem verworfen[]-Eintrag (vom Kurator gespeichert). + room_id = item.get("room_id") + if not room_id: + # Fallback: Raum über bestehende pending-Einträge suchen. + room_id = self._find_room_for_keyword(keyword) + if room_id is None: + continue + self._pending_keywords.setdefault(room_id, {})[keyword] = { + "counter": 1, + "first_seen": time.time(), + "last_seen": time.time(), + "source": "curator_undo", + } + restored += 1 + if restored > 0: + self.save() + return {"ok": True, "restored": restored, "error": ""} + + def _find_room_for_keyword(self, keyword: str) -> Optional[str]: + """Kurator: Findet den Raum, in dem ein Keyword pending war (Undo-Helfer).""" + for room_id, room_pending in self._pending_keywords.items(): + if keyword in room_pending: + return room_id + return None + + def get_curation_log(self, n: int = 5) -> List[Dict[str, Any]]: + """Kurator: Letzte N Kurationen (neueste zuerst).""" + if not self._loaded: + self.load() + return list(reversed(self._curation_log[-n:])) + + def get_last_curation_ts(self) -> Optional[str]: + """Kurator: ISO8601 des letzten Laufs (oder None).""" + if not self._loaded: + self.load() + return self._last_curation_ts + + def get_last_curation_mode(self) -> Optional[str]: + """Kurator: Modus des letzten Laufs (oder None).""" + if not self._loaded: + self.load() + return self._last_curation_mode \ No newline at end of file diff --git a/plugin/archivar/butler_curator.py b/plugin/archivar/butler_curator.py new file mode 100644 index 0000000..3be2b70 --- /dev/null +++ b/plugin/archivar/butler_curator.py @@ -0,0 +1,415 @@ +"""Butler-Kurator: 5-stufige Pipeline zur proaktiven Pflege des Silent Collectors. + +Adressiert das "Frosch-im-Wasser"-Problem (B13/B14): Der Silent Collector +sammelt still ``pending_keywords``, die ohne periodische Kuration zu Müll +verwässern (Stopwords, Modellnamen, Proton-UIDs, Duplikate). + +Die Pipeline (Konzept ``Analysen/Butler-Kurator-Architektur_Rainer.md`` §4): + +1. **Stufe 1 Blocklist** — 4-Ebenen-Kaskade aus ``blocklist.py`` + (``is_invalid_learn_keyword``). Eindeutiger Müll → verwerfen. +2. **Stufe 2 Duplikat** — ``keyword in keywords_100[room]``? → verwerfen. +3. **Stufe 3 LLM-Sicherheits-Check** — genau EIN Call pro Keyword + (P-165-konform). ``hoch`` → verwerfen, ``mittel``/``niedrig`` → Pool. +4. **Stufe 4 Score-Aggregation** — Unsicherheits-Score, Top-N (max 5). +5. **Stufe 5 Rückfrage** — gebündelte Batch-Nachricht an Operator-DM. + +**WICHTIG (Konzept-Widerspruch aufgelöst):** Das Konzept §4.4 benennt den +Score ``unsicherheit`` und definiert ``mittel → 1.0`` (unsicher) bzw. +``niedrig → 0.0`` (passt). Der Satz "Niedrigste Scores (= unsicherste) +zuerst" ist damit ein Widerspruch — ein HÖHERER ``unsicherheit``-Score +bedeutet UNSICHERER. Diese Implementierung sortiert deshalb **absteigend** +(unsicherste zuerst) und nimmt die Top-N. Siehe Pitfall P-188. + +**Fallback (FM7):** Bei LLM-Timeout/429/Parse-Fehler → ``confidence="mittel"`` +(konservativ) → Rückfrage. Stufe 3 wird NIE übersprungen. + +**Testbarkeit:** ``llm_check_fn``, ``send_fn`` und ``now_fn`` sind injizierbar, +damit Unit-Tests ohne echtes Ollama und ohne echten RC-Send laufen. +""" + +from __future__ import annotations + +import json +import logging +import os +import time +from typing import Any, Callable, Dict, List, Optional + +logger = logging.getLogger(__name__) + +# ── Konfiguration (analog room-map.json:blocked_keywords, Env-überschreibbar) ── +# Defaults aus Konzept §6.2 / §11.2 (Andreas-Empfehlung: so lassen, 4 Wochen +# auswerten). Alle Werte via Env-Var überschreibbar für Instanz-Tuning. + +CURATOR_TRIGGER_COUNT_THRESHOLD: int = int( + os.getenv("ARCHIVAR_CURATOR_COUNT_THRESHOLD", "25") +) +"""Mengen-Schwelle: >= N pending Keywords triggern den Kurator (count-Modus).""" + +CURATOR_COOLDOWN_HOURS: int = int( + os.getenv("ARCHIVAR_CURATOR_COOLDOWN_HOURS", "24") +) +"""Cooldown zwischen zwei Kurator-Läufen (Anti-Dauerfeuer, §3.2).""" + +CURATOR_TOP_N: int = int(os.getenv("ARCHIVAR_CURATOR_TOP_N", "5")) +"""Max. Anzahl Rückfragen pro Lauf (Anti-Flut-Constraint, §4.4).""" + +CURATOR_MAX_LOG_ENTRIES: int = int( + os.getenv("ARCHIVAR_CURATOR_MAX_LOG_ENTRIES", "20") +) +"""Max. Einträge im curation_log (FIFO-Prune, FM8).""" + +CURATOR_LLM_TIMEOUT_S: float = float( + os.getenv("ARCHIVAR_CURATOR_LLM_TIMEOUT_S", "30.0") +) +"""Timeout für den Stufe-3-LLM-Call (Fallback → mittel).""" + +# ── Score-Gewichtung (Konzept §4.4 / §11.2) ──────────────────────────────── +W_CONF: float = 0.5 +W_FREQ: float = 0.3 +W_RECENCY: float = 0.2 + +# ── Stufe-3-LLM-Prompt (Konzept §4.3, verbal → konkret) ──────────────────── +# ~50 Tokens Input, ~30 Tokens Output. Antwort NUR als JSON. +CURATOR_LLM_PROMPT: str = ( + "Rolle: Butler-Kurator.\n" + 'Kontext: Raum "{room_name}" hat das Thema "{room_theme}".\n' + 'Kandidat-Keyword: "{keyword}".\n' + "Aufgabe: Bewerte ob das Keyword thematisch zum Raum passt.\n" + "\n" + "Antworte NUR mit JSON:\n" + '{{"confidence": "hoch" | "mittel" | "niedrig", "reason": "<1-Satz>"}}\n' + "\n" + "Definition:\n" + '- "hoch": Keyword ist klar NICHT thematisch (alltaegliches Wort, ' + "Technik-Begriff, ID). Verwerfen.\n" + '- "mittel": Keyword koennte thematisch sein, aber Kontext fehlt. ' + "Rueckfrage.\n" + '- "niedrig": Keyword passt eindeutig zum Thema. Akzeptieren.' +) + + +class ButlerCurator: + """5-stufige Kuratierungs-Pipeline für den Silent Collector. + + Args: + state: ``ArchivarState``-Instanz (Single-Source-of-Truth). + room_map: ``RoomMap``-Instanz (für Blocklist E2/E3 + Duplikat-Check). + llm_check_fn: Optional injizierbarer Stufe-3-Check + ``(keyword, room_name, room_theme) -> {"confidence", "reason"}``. + Default: echter Ollama-Call via ``OllamaLLMClient``. + send_fn: Optional injizierbare Rückfrage-Funktion ``(text) -> None``. + Default: nur Logging (kein echter RC-Send). + now_fn: Optional injizierbare Zeitquelle ``() -> float`` (Unix-Sekunden). + Default: ``time.time``. + """ + + def __init__( + self, + state: Any, + room_map: Any = None, + llm_check_fn: Optional[Callable[[str, str, str], Dict[str, str]]] = None, + send_fn: Optional[Callable[[str], None]] = None, + now_fn: Optional[Callable[[], float]] = None, + ) -> None: + self._state = state + self._room_map = room_map + self._llm_check_fn = llm_check_fn + self._send_fn = send_fn + self._now_fn = now_fn or time.time + + # ── Trigger-Logik (Hybrid, §3) ────────────────────────────────────── + + def should_trigger( + self, + trigger_mode: str = "time", + pending_total: Optional[int] = None, + ) -> bool: + """Hybrid-Trigger: zeitbasiert ODER mengenbasiert, mit Cooldown. + + Args: + trigger_mode: ``"time"`` (Sonntag 22:00 — feuert immer, Cooldown + reicht) oder ``"count"`` (>= Schwelle + Cooldown). + pending_total: Optional vorberechnete Gesamtzahl pending Keywords. + Bei ``None`` wird sie aus dem State gelesen. + + Returns: + True wenn der Kurator feuern soll. + """ + if not self._state.can_curate_now(CURATOR_COOLDOWN_HOURS): + return False + if trigger_mode == "time": + return True + if trigger_mode == "count": + if pending_total is None: + pending_total = self._state.get_total_pending_count() + return (pending_total or 0) >= CURATOR_TRIGGER_COUNT_THRESHOLD + logger.warning("Kurator: unbekannter trigger_mode '%s'", trigger_mode) + return False + + # ── Haupt-Pipeline ────────────────────────────────────────────────── + + def run_curation( + self, + trigger_mode: str = "manual", + trigger_reason: str = "", + ) -> Optional[str]: + """Führt einen vollständigen Kurator-Lauf aus (Stufe 1-5). + + Pre-Flight: Cooldown-Check + pending nicht leer. Bei Skip → ``None``. + + Args: + trigger_mode: ``"time"`` | ``"count"`` | ``"manual"`` (Telemetrie). + trigger_reason: Freitext-Grund (z.B. "weekly cron"). + + Returns: + ``run_id`` des protokollierten Laufs, oder ``None`` bei Skip. + """ + if not self._state.can_curate_now(CURATOR_COOLDOWN_HOURS): + logger.info("Kurator: Cooldown aktiv — Lauf übersprungen") + return None + + pending = self._state.get_all_pending_keywords() + if not pending: + logger.info("Kurator: keine pending Keywords — Lauf übersprungen") + return None + + stats: Dict[str, Any] = { + "pending_total": len(pending), + "stufe1_blocklist_verworfen": 0, + "stufe2_duplikat_verworfen": 0, + "stufe3_llm_verworfen": 0, + "stufe4_rueckfrage_pool": 0, + "llm_calls": 0, + "duration_ms": 0, + } + verworfen: List[Dict[str, Any]] = [] + rueckfrage_pool: List[Dict[str, Any]] = [] + + t0 = time.monotonic() + + for item in pending: + keyword = item["keyword"] + room_id = item["room_id"] + + # ── Stufe 1: Blocklist ────────────────────────────────────── + grund = self._stufe1_blocklist(keyword, self._room_map) + if grund: + verworfen.append({ + "keyword": keyword, "room_id": room_id, "grund": grund, "stufe": 1, + }) + stats["stufe1_blocklist_verworfen"] += 1 + self._state.remove_pending_keyword(room_id, keyword) + continue + + # ── Stufe 2: Duplikat ─────────────────────────────────────── + if self._stufe2_duplikat(keyword, room_id): + verworfen.append({ + "keyword": keyword, + "room_id": room_id, + "grund": "duplikat_in_keywords_100", + "stufe": 2, + }) + stats["stufe2_duplikat_verworfen"] += 1 + self._state.remove_pending_keyword(room_id, keyword) + continue + + # ── Stufe 3: LLM-Sicherheits-Check ────────────────────────── + room = self._room_map.get_room_by_id(room_id) if self._room_map else None + room_name = room.name if room else room_id + room_theme = room.theme if room else "" + result = self._stufe3_llm_check(keyword, room_name, room_theme) + stats["llm_calls"] += 1 + confidence = result.get("confidence", "mittel") + reason = result.get("reason", "") + + if confidence == "hoch": + verworfen.append({ + "keyword": keyword, + "room_id": room_id, + "grund": "llm_hoch", + "stufe": 3, + "llm_reason": reason, + }) + stats["stufe3_llm_verworfen"] += 1 + self._state.remove_pending_keyword(room_id, keyword) + continue + + # mittel/niedrig → Rückfrage-Pool (konservativ, §10) + rueckfrage_pool.append({ + "keyword": keyword, + "room_id": room_id, + "confidence": confidence, + "reason": reason, + "frequency": int(item.get("counter", 1)), + "last_seen": float(item.get("last_seen", self._now_fn())), + }) + + # ── Stufe 4: Score-Aggregation ────────────────────────────────── + top_n = self._stufe4_aggregate(rueckfrage_pool) + stats["stufe4_rueckfrage_pool"] = len(top_n) + + # ── Stufe 5: Rückfrage ────────────────────────────────────────── + if top_n: + self._stufe5_ask_operator(top_n) + + stats["duration_ms"] = int((time.monotonic() - t0) * 1000) + + run_id = self._state.record_curation_run( + stats=stats, + verworfen=verworfen, + rueckfrage=top_n, + mode=trigger_mode, + trigger_reason=trigger_reason, + ) + logger.info( + "Kurator-Lauf %s: %d pending, %d verworfen (S1=%d S2=%d S3=%d), " + "%d Rückfrage, %d LLM-Calls", + run_id, stats["pending_total"], len(verworfen), + stats["stufe1_blocklist_verworfen"], + stats["stufe2_duplikat_verworfen"], + stats["stufe3_llm_verworfen"], + stats["stufe4_rueckfrage_pool"], stats["llm_calls"], + ) + return run_id + + # ── Stufe 1: Blocklist ────────────────────────────────────────────── + + def _stufe1_blocklist(self, keyword: str, room_map: Any) -> Optional[str]: + """Stufe 1: 4-Ebenen-Blocklist (single source of truth, A1).""" + from archivar.blocklist import is_invalid_learn_keyword + return is_invalid_learn_keyword(keyword, room_map) + + # ── Stufe 2: Duplikat ─────────────────────────────────────────────── + + def _stufe2_duplikat(self, keyword: str, room_id: str) -> bool: + """Stufe 2: exakter, case-insensitiver Match in keywords_100 (P-028).""" + if self._room_map is None: + return False + room = self._room_map.get_room_by_id(room_id) + if room is None: + return False + kw = keyword.strip().lower() + return kw in (k.lower() for k in room.keywords_100) + + # ── Stufe 3: LLM-Sicherheits-Check ────────────────────────────────── + + def _stufe3_llm_check( + self, keyword: str, room_name: str, room_theme: str + ) -> Dict[str, str]: + """Stufe 3: genau EIN LLM-Call pro Keyword (P-165-konform). + + Fallback bei Timeout/429/Parse-Fehler → ``confidence="mittel"``. + """ + if self._llm_check_fn is not None: + try: + result = self._llm_check_fn(keyword, room_name, room_theme) + if not isinstance(result, dict): + return {"confidence": "mittel", "reason": "LLM keine gültige Antwort"} + return result + except Exception as e: + logger.warning("Kurator: injizierter LLM-Check fehlgeschlagen: %s", e) + return {"confidence": "mittel", "reason": f"LLM-Fehler: {e}"} + return self._default_llm_check(keyword, room_name, room_theme) + + def _default_llm_check( + self, keyword: str, room_name: str, room_theme: str + ) -> Dict[str, str]: + """Echter Ollama-Call für Stufe 3 (Default, wenn kein Mock injiziert).""" + try: + from archivar.classifier import OllamaLLMClient + client = OllamaLLMClient() + prompt = CURATOR_LLM_PROMPT.format( + keyword=keyword, room_name=room_name, room_theme=room_theme + ) + response = client.generate(prompt) + if not response: + return {"confidence": "mittel", "reason": "LLM keine Antwort"} + data = json.loads(response) + confidence = data.get("confidence", "mittel") + if confidence not in ("hoch", "mittel", "niedrig"): + confidence = "mittel" + return {"confidence": confidence, "reason": data.get("reason", "")} + except Exception as e: + logger.warning("Kurator: LLM-Check fehlgeschlagen (Fallback mittel): %s", e) + return {"confidence": "mittel", "reason": f"LLM-Fehler: {e}"} + + # ── Stufe 4: Score-Aggregation ────────────────────────────────────── + + def _stufe4_aggregate(self, items: List[Dict[str, Any]]) -> List[Dict[str, Any]]: + """Stufe 4: Unsicherheits-Score + Top-N (max ``CURATOR_TOP_N``). + + Score-Formel (Konzept §4.4): + unsicherheit = W_CONF*conf + W_FREQ*freq_norm + W_RECENCY*recency_norm + ``conf``: mittel=1.0, niedrig=0.0. Sortierung **absteigend** + (unsicherste zuerst) — siehe Modul-Docstring (P-188). + """ + if not items: + return [] + + now = self._now_fn() + max_freq = max((int(it.get("frequency", 1)) for it in items), default=1) + ages = [now - float(it.get("last_seen", now)) for it in items] + max_age = max(ages, default=1.0) + + scored: List[Dict[str, Any]] = [] + for it in items: + conf_score = 1.0 if it.get("confidence") == "mittel" else 0.0 + freq_norm = int(it.get("frequency", 1)) / max_freq if max_freq > 0 else 0.0 + recency_norm = (now - float(it.get("last_seen", now))) / max_age if max_age > 0 else 0.0 + score = W_CONF * conf_score + W_FREQ * freq_norm + W_RECENCY * recency_norm + scored.append({**it, "score": round(score, 4)}) + + # Unsicherste (höchster Score) zuerst, dann Top-N. + scored.sort(key=lambda x: -x["score"]) + return scored[:CURATOR_TOP_N] + + # ── Stufe 5: Rückfrage ────────────────────────────────────────────── + + def _stufe5_ask_operator(self, top_n_items: List[Dict[str, Any]]) -> None: + """Stufe 5: gebündelte Batch-Nachricht an Operator-DM (eine Nachricht).""" + text = self._build_rueckfrage_text(top_n_items) + if self._send_fn is not None: + try: + self._send_fn(text) + except Exception as e: + logger.warning("Kurator: Rückfrage-Send fehlgeschlagen: %s", e) + else: + logger.info( + "Kurator Rückfrage (kein send_fn verdrahtet): %d Keywords", + len(top_n_items), + ) + + def _build_rueckfrage_text(self, top_n_items: List[Dict[str, Any]]) -> str: + """Baut die Batch-Rückfrage-Nachricht (Konzept §4.5).""" + lines = [ + f"🤖 Butler-Kurator — {len(top_n_items)} unsichere Keywords gefunden:", + "", + ] + for i, it in enumerate(top_n_items, start=1): + lines.append(f"{i}. {it['keyword']}") + lines.append(f" Grund: {it.get('reason') or 'neues_wort_ohne_kontext'}") + if it.get("llm_reason"): + lines.append(f" LLM: \"{it['llm_reason']}\"") + lines.append(" [✅ Lernen] [❌ Verwerfen] [✏️ Andere]") + lines.append("") + return "\n".join(lines).rstrip() + + # ── Inline-Command-Helfer ─────────────────────────────────────────── + + def get_status(self) -> Dict[str, Any]: + """Status für ``::keywords curate status``.""" + return { + "last_curation_ts": self._state.get_last_curation_ts(), + "last_curation_mode": self._state.get_last_curation_mode(), + "pending_total": self._state.get_total_pending_count(), + } + + def get_log(self, n: int = 5) -> List[Dict[str, Any]]: + """Letzte N Kurationen für ``::keywords curate log [N]``.""" + return self._state.get_curation_log(n) + + def undo_last_curation(self, run_id: str) -> Dict[str, Any]: + """Undo für ``::keywords curate undo `` (delegiert an State).""" + return self._state.undo_last_curation(run_id) diff --git a/plugin/archivar/tests/test_butler_curator.py b/plugin/archivar/tests/test_butler_curator.py new file mode 100644 index 0000000..ebe58e5 --- /dev/null +++ b/plugin/archivar/tests/test_butler_curator.py @@ -0,0 +1,332 @@ +"""Butler-Kurator: Unit-Tests für die 5-stufige Pipeline. + +Testet ``plugin/archivar/butler_curator.py`` (Stufe 1-5, Trigger, Undo) +und die ``archivar_state.py``-Erweiterung (curation_log, Cooldown, Undo). + +Konzept: ``Analysen/Butler-Kurator-Architektur_Rainer.md`` §7.1. +""" + +from __future__ import annotations + +import json +import os +import sys +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from archivar.archivar_state import ArchivarState +from archivar.room_map import RoomMap, RoomEntry +from archivar.butler_curator import ButlerCurator + + +def _make_room_map(blocked_keywords=None) -> RoomMap: + """RoomMap mit LAN-Doku + BAT-Team (analog test_blocklist.py).""" + rooms = { + "room_lan": RoomEntry( + room_id="room_lan", + name="#LAN-Dokumentation", + theme="LAN-Dokumentation und Netzwerk", + keywords_100=["isp", "telekom", "vodafone"], + keywords_context=[], + ), + "room_bat": RoomEntry( + room_id="room_bat", + name="#BAT-Team", + theme="BAT-Team interne Abstimmung", + keywords_100=["trading", "krypto"], + keywords_context=[], + ), + } + return RoomMap( + rooms=rooms, + excluded_room_ids=set(), + fact_store_path=Path("/tmp/test_docs"), + blocked_keywords=blocked_keywords, + ) + + +def _make_state(tmp_path: str) -> ArchivarState: + """ArchivarState mit isoliertem State-File (kein echter Pfad).""" + # Alte State-Datei entfernen, damit Cooldown aus früheren Läufen nicht greift. + try: + os.remove(tmp_path) + except OSError: + pass + return ArchivarState(state_file_path=tmp_path) + + +class TestStufe1Blocklist(unittest.TestCase): + """Stufe 1: 4-Ebenen-Blocklist verwirft eindeutigen Müll.""" + + def setUp(self): + self.room_map = _make_room_map(blocked_keywords=["deepseek-v4-flash"]) + self.state = _make_state("/tmp/test_curator_s1.json") + self.curator = ButlerCurator( + state=self.state, room_map=self.room_map, + llm_check_fn=lambda k, r, t: {"confidence": "niedrig", "reason": ""}, + ) + + def test_stopword_verworfen(self): + self.state.collect_keyword("room_lan", "und") + run_id = self.curator.run_curation(trigger_mode="manual") + self.assertIsNotNone(run_id) + log = self.state.get_curation_log(1)[0] + self.assertEqual(log["stats"]["stufe1_blocklist_verworfen"], 1) + self.assertEqual(log["verworfen"][0]["grund"], "STOPWORD") + + def test_domain_verworfen(self): + self.state.collect_keyword("room_lan", "deepseek-v4-flash") + self.curator.run_curation(trigger_mode="manual") + log = self.state.get_curation_log(1)[0] + self.assertEqual(log["verworfen"][0]["grund"], "DOMAIN_KEYWORD") + + def test_roomname_verworfen(self): + self.state.collect_keyword("room_lan", "lan-dokumentation") + self.curator.run_curation(trigger_mode="manual") + log = self.state.get_curation_log(1)[0] + self.assertIn("Raumname", log["verworfen"][0]["grund"]) + + +class TestStufe2Duplikat(unittest.TestCase): + """Stufe 2: Duplikat in keywords_100 wird verworfen.""" + + def setUp(self): + self.room_map = _make_room_map() + self.state = _make_state("/tmp/test_curator_s2.json") + self.curator = ButlerCurator( + state=self.state, room_map=self.room_map, + llm_check_fn=lambda k, r, t: {"confidence": "niedrig", "reason": ""}, + ) + + def test_duplikat_verworfen(self): + # 'isp' ist bereits in keywords_100 von room_lan. + self.state.collect_keyword("room_lan", "isp") + self.curator.run_curation(trigger_mode="manual") + log = self.state.get_curation_log(1)[0] + self.assertEqual(log["stats"]["stufe2_duplikat_verworfen"], 1) + self.assertEqual(log["verworfen"][0]["grund"], "duplikat_in_keywords_100") + + def test_neues_keyword_passt(self): + self.state.collect_keyword("room_lan", "neues-thema") + self.curator.run_curation(trigger_mode="manual") + log = self.state.get_curation_log(1)[0] + self.assertEqual(log["stats"]["stufe2_duplikat_verworfen"], 0) + + +class TestStufe3LlmCheck(unittest.TestCase): + """Stufe 3: LLM-Sicherheits-Check (hoch → verwerfen, mittel/niedrig → Pool).""" + + def setUp(self): + self.room_map = _make_room_map() + self.state = _make_state("/tmp/test_curator_s3.json") + + def test_llm_hoch_verworfen(self): + curator = ButlerCurator( + state=self.state, room_map=self.room_map, + llm_check_fn=lambda k, r, t: {"confidence": "hoch", "reason": "Technik-Begriff"}, + ) + self.state.collect_keyword("room_lan", "firewall-konfig") + curator.run_curation(trigger_mode="manual") + log = self.state.get_curation_log(1)[0] + self.assertEqual(log["stats"]["stufe3_llm_verworfen"], 1) + + def test_llm_mittel_weiter(self): + curator = ButlerCurator( + state=self.state, room_map=self.room_map, + llm_check_fn=lambda k, r, t: {"confidence": "mittel", "reason": "unklar"}, + ) + self.state.collect_keyword("room_lan", "honcho-kontamination") + curator.run_curation(trigger_mode="manual") + log = self.state.get_curation_log(1)[0] + self.assertEqual(log["stats"]["stufe3_llm_verworfen"], 0) + self.assertEqual(log["stats"]["stufe4_rueckfrage_pool"], 1) + + def test_llm_timeout_konservativ(self): + def _timeout(k, r, t): + raise TimeoutError("LLM timeout") + curator = ButlerCurator( + state=self.state, room_map=self.room_map, llm_check_fn=_timeout, + ) + self.state.collect_keyword("room_lan", "irgendein-wort") + curator.run_curation(trigger_mode="manual") + log = self.state.get_curation_log(1)[0] + # Timeout → mittel → Rückfrage (nicht verworfen, nicht übersprungen). + self.assertEqual(log["stats"]["stufe3_llm_verworfen"], 0) + self.assertEqual(log["stats"]["stufe4_rueckfrage_pool"], 1) + self.assertEqual(log["rueckfrage"][0]["confidence"], "mittel") + + def test_llm_none_konservativ(self): + # LLM liefert None (keine Antwort) → mittel. + curator = ButlerCurator( + state=self.state, room_map=self.room_map, + llm_check_fn=lambda k, r, t: None, + ) + self.state.collect_keyword("room_lan", "irgendein-wort") + curator.run_curation(trigger_mode="manual") + log = self.state.get_curation_log(1)[0] + self.assertEqual(log["rueckfrage"][0]["confidence"], "mittel") + + +class TestStufe4Aggregation(unittest.TestCase): + """Stufe 4: Score-Aggregation + Top-N (max 5).""" + + def setUp(self): + self.room_map = _make_room_map() + self.state = _make_state("/tmp/test_curator_s4.json") + + def _curator_with_mittel(self): + return ButlerCurator( + state=self.state, room_map=self.room_map, + llm_check_fn=lambda k, r, t: {"confidence": "mittel", "reason": "unklar"}, + ) + + def test_top_n_limit(self): + curator = self._curator_with_mittel() + for i in range(30): + self.state.collect_keyword("room_lan", f"kw-{i}") + curator.run_curation(trigger_mode="manual") + log = self.state.get_curation_log(1)[0] + self.assertEqual(log["stats"]["stufe4_rueckfrage_pool"], 5) + + def test_leerer_pool(self): + # Alles "hoch" → verworfen, Pool leer (kein mittel/niedrig). + curator = ButlerCurator( + state=self.state, room_map=self.room_map, + llm_check_fn=lambda k, r, t: {"confidence": "hoch", "reason": "Müll"}, + ) + self.state.collect_keyword("room_lan", "kw-a") + curator.run_curation(trigger_mode="manual") + log = self.state.get_curation_log(1)[0] + self.assertEqual(log["stats"]["stufe4_rueckfrage_pool"], 0) + + def test_score_sortierung_mittel_vor_niedrig(self): + # mittel (unsicher, Score 1.0) muss vor niedrig (Score 0.0) sortiert + # werden. Beide gehen in den Pool (konservativ, §10), aber mittel zuerst. + curator = ButlerCurator( + state=self.state, room_map=self.room_map, + llm_check_fn=lambda k, r, t: ( + {"confidence": "mittel", "reason": ""} if k == "unsicher" + else {"confidence": "niedrig", "reason": ""} + ), + ) + self.state.collect_keyword("room_lan", "sicher") + self.state.collect_keyword("room_lan", "unsicher") + curator.run_curation(trigger_mode="manual") + log = self.state.get_curation_log(1)[0] + pool_keywords = [it["keyword"] for it in log["rueckfrage"]] + # Beide im Pool, aber 'unsicher' (mittel) zuerst. + self.assertEqual(pool_keywords[0], "unsicher") + self.assertIn("sicher", pool_keywords) + + +class TestStufe5Rueckfrage(unittest.TestCase): + """Stufe 5: gebündelte Batch-Nachricht (eine Nachricht, nicht N).""" + + def setUp(self): + self.room_map = _make_room_map() + self.state = _make_state("/tmp/test_curator_s5.json") + + def test_batch_nachricht_einmal(self): + sent = [] + curator = ButlerCurator( + state=self.state, room_map=self.room_map, + llm_check_fn=lambda k, r, t: {"confidence": "mittel", "reason": "unklar"}, + send_fn=lambda text: sent.append(text), + ) + for i in range(5): + self.state.collect_keyword("room_lan", f"kw-{i}") + curator.run_curation(trigger_mode="manual") + # Genau EINE Nachricht, die alle 5 enthält. + self.assertEqual(len(sent), 1) + for i in range(5): + self.assertIn(f"kw-{i}", sent[0]) + + +class TestTrigger(unittest.TestCase): + """Hybrid-Trigger: Cooldown + Mengen-Schwelle.""" + + def setUp(self): + self.room_map = _make_room_map() + self.state = _make_state("/tmp/test_curator_trigger.json") + + def test_cooldown_skip(self): + # Letzter Lauf vor 1h → skip. + self.state.record_curation_run( + stats={"pending_total": 0}, verworfen=[], rueckfrage=[], mode="manual" + ) + curator = ButlerCurator(state=self.state, room_map=self.room_map) + self.assertFalse(curator.should_trigger(trigger_mode="time")) + + def test_cooldown_pass(self): + # Kein letzter Lauf → run. + curator = ButlerCurator(state=self.state, room_map=self.room_map) + self.assertTrue(curator.should_trigger(trigger_mode="time")) + + def test_mengen_trigger(self): + curator = ButlerCurator(state=self.state, room_map=self.room_map) + self.assertTrue(curator.should_trigger(trigger_mode="count", pending_total=25)) + + def test_mengen_trigger_unter_schwelle(self): + curator = ButlerCurator(state=self.state, room_map=self.room_map) + self.assertFalse(curator.should_trigger(trigger_mode="count", pending_total=24)) + + +class TestUndo(unittest.TestCase): + """Undo: letzten Lauf wiederherstellen.""" + + def setUp(self): + self.room_map = _make_room_map() + self.state = _make_state("/tmp/test_curator_undo.json") + + def test_undo_stellt_her(self): + curator = ButlerCurator( + state=self.state, room_map=self.room_map, + llm_check_fn=lambda k, r, t: {"confidence": "niedrig", "reason": ""}, + ) + # 7 Stopwords sammeln → alle in Stufe 1 verworfen. + for w in ("und", "oder", "aber", "the", "a", "an", "of"): + self.state.collect_keyword("room_lan", w) + run_id = curator.run_curation(trigger_mode="manual") + log = self.state.get_curation_log(1)[0] + self.assertEqual(len(log["verworfen"]), 7) + # Undo → alle 7 zurück nach pending. + result = self.state.undo_last_curation(run_id) + self.assertTrue(result["ok"]) + self.assertEqual(result["restored"], 7) + + def test_undo_nur_letzter(self): + # Zwei Läufe; Undo des ERSTEN run_id → Fehler. + curator = ButlerCurator( + state=self.state, room_map=self.room_map, + llm_check_fn=lambda k, r, t: {"confidence": "niedrig", "reason": ""}, + ) + self.state.collect_keyword("room_lan", "und") + run_id_1 = curator.run_curation(trigger_mode="manual") + # Cooldown umgehen: direkt zweiten Lauf erzwingen. + self.state._last_curation_ts = None + self.state.collect_keyword("room_lan", "oder") + run_id_2 = curator.run_curation(trigger_mode="manual") + self.assertNotEqual(run_id_1, run_id_2) + result = self.state.undo_last_curation(run_id_1) + self.assertFalse(result["ok"]) + self.assertIn("letzte Lauf", result["error"]) + + +class TestStateMigration(unittest.TestCase): + """Regression: alte archivar_state.json (ohne Kurator-Keys) lädt mit Defaults.""" + + def test_load_legacy_state(self): + path = "/tmp/test_curator_legacy.json" + with open(path, "w", encoding="utf-8") as f: + json.dump({"rooms": {}, "pending_keywords": {}}, f) + state = ArchivarState(state_file_path=path) + self.assertTrue(state.load()) + self.assertEqual(state.get_curation_log(), []) + self.assertIsNone(state.get_last_curation_ts()) + self.assertTrue(state.can_curate_now()) + + +if __name__ == "__main__": + unittest.main()