fe9ee213f3
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).
416 lines
18 KiB
Python
416 lines
18 KiB
Python
"""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 <run_id>`` (delegiert an State)."""
|
|
return self._state.undo_last_curation(run_id)
|