feat(curator): Butler-Kurator 5-stufige Pipeline (B13/B14-Fix)
5-stufige Pipeline zur proaktiven Pflege des Silent Collectors
(Konzept Analysen/Butler-Kurator-Architektur_Rainer.md):
- Stufe 1: Blocklist (4-Ebenen aus 6cbea1b, single source of truth)
- Stufe 2: Duplikats-Check (keyword in keywords_100[room])
- Stufe 3: LLM-Sicherheits-Check (1 Call/Keyword, P-165-konform,
Fallback bei Timeout/429 -> confidence='mittel' -> Rueckfrage)
- Stufe 4: Score-Aggregation (Unsicherheits-Score, Top-N max 5)
- Stufe 5: Rueckfrage (gebuendelte Batch-Nachricht an Operator-DM)
archivar_state.py: curation_log[], last_curation_ts, last_curation_mode
+ Methoden record_curation_run, apply_curation_response,
undo_last_curation, can_curate_now (Defaults fuer Legacy-Migration).
Trigger: Hybrid (zeitbasiert Sonntag 22:00 ODER mengenbasiert >=25
pending + 24h Cooldown).
Inline-Commands: ::keywords curate, curate status, curate undo <run_id>,
curate log [N].
20 neue Unit-Tests (test_butler_curator.py), Regression gruen.
Pitfall P-188: Konzept-Score-Widerspruch aufgeloest (unsicherheit
absteigend sortiert, nicht aufsteigend).
This commit is contained in:
@@ -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
|
||||
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
|
||||
Reference in New Issue
Block a user