From 6a701dcce4959d4f96d310246247938a1ee580ed Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Sun, 19 Jul 2026 11:07:44 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20V8.5=20=E2=80=94=20P1-Points:=2090-Tage?= =?UTF-8?q?-Demotion=20+=20::curate=20run=20Routine?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/adapter.py | 133 +++++++++++++++++++++------ plugin/archivar/booster.py | 50 +++++++++++ tests/test_booster.py | 180 ++++++++++++++++++++++++++++++++----- 3 files changed, 314 insertions(+), 49 deletions(-) diff --git a/plugin/adapter.py b/plugin/adapter.py index 077595a..451bcbc 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -3128,37 +3128,118 @@ class RocketChatAdapter(BasePlatformAdapter): "πŸ’‘ `::curate status` β€” diesen Status anzeigen" ) elif sub == "run": - # Keyword-Kuratierung: PrΓΌfe auf veraltete/fehlende Keywords + # ── Echte Keyword-Kuratierung (R10) ────────────────────────── + # 1. 90-Tage-Demotion via KeywordBooster + # 2. Red-Flag-Feedback-Analyse via routing_counter + # 3. Promotion-Kandidaten via ArchivarState + # 4. Keyword-Gewicht-Anomalien via ArchivarState + # 5. Persistiere Γ„nderungen in room-map.json room_map = self.archivar._room_map - suggestions = [] - for rid, entry in room_map.rooms.items(): - room_name = entry.name - # PrΓΌfe ob der Raumname selbst als Keyword fehlt - name_clean = room_name.lstrip("#").lower() - if name_clean not in [kw.lower() for kw in entry.keywords_100]: - suggestions.append(f"- **{room_name}**: Raumname fehlt als Keyword") - # PrΓΌfe auf sehr kurze Keywords (< 3 Zeichen) - for kw in entry.keywords_100: - if len(kw) < 3: - suggestions.append(f"- **{room_name}**: Keyword `{kw}` ist sehr kurz (< 3 Zeichen)") - # PrΓΌfe auf Duplikate zwischen keywords_100 und keywords_context - overlap = set(kw.lower() for kw in entry.keywords_100) & set(kw.lower() for kw in entry.keywords_context) - for kw in overlap: - suggestions.append(f"- **{room_name}**: Keyword `{kw}` ist doppelt (in 100 + context)") + state = self.archivar._state + booster = self.archivar._booster + lines: list[str] = [] + changes_made = False - if not suggestions: - return ( - "βœ… **Keyword-Kuratierung abgeschlossen**\n\n" - "Alle Keywords sind in Ordnung β€” keine Probleme gefunden.\n\n" - f"- **RΓ€ume geprΓΌft:** {len(room_map.rooms)}\n" - f"- **Keywords gesamt:** {sum(len(e.keywords_100) + len(e.keywords_context) for e in room_map.rooms.values())}" - ) + # ── Schritt 1: 90-Tage-Demotion ────────────────────────── + if booster is not None: + demoted = booster.demote_stale_keywords(max_age_days=90) + if demoted > 0: + lines.append( + f"πŸ”„ **Demotion:** {demoted} Keyword(s) von 100% β†’ Kontext " + f"(>90 Tage kein Match)" + ) + changes_made = True + else: + lines.append("βœ… **Demotion:** Keine veralteten Keywords") + else: + lines.append("⚠️ **Demotion:** Booster nicht verfΓΌgbar") + # ── Schritt 2: Red-Flag-Feedback ───────────────────────── + from archivar.routing_counter import routing_counter + counts = routing_counter.get_counts() + red_flag_triggered = counts.get("red_flag_triggered", 0) + red_flag_routed = counts.get("red_flag_agent_routed", 0) + red_flag_dispatched = counts.get("red_flag_dispatched", 0) + lines.append( + f"🚩 **Red-Flag-Feedback:** {red_flag_triggered} getriggert, " + f"{red_flag_routed} geroutet, {red_flag_dispatched} dispatched" + ) + + # ── Schritt 3: Promotion-Kandidaten ────────────────────── + if state._promotion_candidates: + promo_lines = [] + for kw, rooms_dict in list(state._promotion_candidates.items())[:10]: + for rid, info in rooms_dict.items(): + entry = room_map.get_room_by_id(rid) + room_name = entry.name if entry else rid[:8] + promo_lines.append( + f" - `{kw}` β†’ {room_name} " + f"(Score: {info.get('score', 0):.1f})" + ) + if promo_lines: + lines.append( + f"⭐ **Promotion-Kandidaten ({len(state._promotion_candidates)}):**\n" + + "\n".join(promo_lines) + ) + else: + lines.append("⭐ **Promotion-Kandidaten:** Keine") + + # ── Schritt 4: Keyword-Gewicht-Anomalien ────────────────── + if state._keyword_weights: + anomaly_count = 0 + anomaly_lines = [] + for kw, rooms_dict in state._keyword_weights.items(): + for rid, entry in rooms_dict.items(): + if entry.weight <= 0.1 and entry.rejection_count >= 2: + anomaly_count += 1 + if len(anomaly_lines) < 5: + room_entry = room_map.get_room_by_id(rid) + room_name = room_entry.name if room_entry else rid[:8] + anomaly_lines.append( + f" - `{kw}` β†’ {room_name} " + f"(Gewicht: {entry.weight:.2f}, " + f"Rejections: {entry.rejection_count})" + ) + if anomaly_lines: + lines.append( + f"⚠️ **Gewicht-Anomalien ({anomaly_count}):**\n" + + "\n".join(anomaly_lines) + ) + else: + lines.append("⚠️ **Gewicht-Anomalien:** Keine Daten") + + # ── Schritt 5: Ring-State-Info ─────────────────────────── + if state._ring_state: + active_rings = 0 + for rid, ring in state._ring_state.items(): + if state.is_ring_state_active(rid, ring.get("state", "")): + active_rings += 1 + if active_rings > 0: + lines.append(f"πŸ”” **Aktive Ring-States:** {active_rings} Raum/RΓ€ume im Strategie-Modus") + else: + lines.append("πŸ”” **Ring-States:** Keine") + + # ── Schritt 6: Persistieren ────────────────────────────── + if changes_made: + try: + from pathlib import Path as PathLib + from archivar.config import ROOM_MAP_PATH + from archivar.room_map import RoomMap + RoomMap.save(room_map, PathLib(ROOM_MAP_PATH)) + lines.append("\nπŸ’Ύ Γ„nderungen in `room-map.json` persistiert") + except Exception as e: + lines.append(f"\n❌ Fehler beim Persistieren: {e}") + + # ── Zusammenfassung ────────────────────────────────────── + total_keywords = sum( + len(entry.keywords_100) + len(entry.keywords_context) + for entry in room_map.rooms.values() + ) return ( "πŸ” **Keyword-Kuratierung β€” Ergebnisse**\n\n" - + "\n".join(suggestions[:20]) + - ("\n\n… und weitere" if len(suggestions) > 20 else "") + - "\n\nπŸ’‘ Bearbeite `room-map.json` um die Keywords anzupassen." + + "\n".join(lines) + + f"\n\nπŸ“Š **Map-Status:** {len(room_map.rooms)} RΓ€ume, " + f"{total_keywords} Keywords, v{room_map.version}" ) else: return ( diff --git a/plugin/archivar/booster.py b/plugin/archivar/booster.py index 1755f64..650556f 100644 --- a/plugin/archivar/booster.py +++ b/plugin/archivar/booster.py @@ -24,6 +24,7 @@ Usage:: from __future__ import annotations import logging +from datetime import datetime, timedelta from typing import Dict, List, Set, Tuple logger = logging.getLogger(__name__) @@ -108,6 +109,9 @@ class KeywordBooster: # Keine Keywords β†’ Scores unverΓ€ndert zurΓΌck return sorted(scores, key=lambda x: x[1], reverse=True) + # ── V8.2 A3: Matches fΓΌr Demotion-Tracking aufzeichnen ────── + self._record_matches(text_lower, matched_keywords) + # ── Boost-Phase: +0.10 fΓΌr eindeutige Keywords ──────────── for kw in matched_keywords: rooms = self._keyword_to_rooms[kw] @@ -196,6 +200,52 @@ class KeywordBooster: count += 1 return count + # ── V8.2 A3: 90-Tage-Demotion ───────────────────────────────────── + + def _record_matches(self, text_lower: str, matched_keywords: List[str]) -> None: + """Zeichnet last_matched-Timestamps fΓΌr alle getroffenen Keywords. + + Wird nach jedem boost()-Aufruf aufgerufen, um die RoomMap-Tracking-Felder + aktuell zu halten. Nur Keywords in keywords_100 werden getrackt + (Demotion betrifft nur 100%-Keywords). + + Args: + text_lower: Der Text in lowercase. + matched_keywords: Liste der im Text gefundenen Keywords. + """ + now = datetime.now().isoformat() + for kw in matched_keywords: + rooms = self._keyword_to_rooms.get(kw, set()) + for room_id in rooms: + # Nur keywords_100 tracken (Demotion betrifft nur 100%-Keywords) + entry = self._room_map.get_room_by_id(room_id) + if entry is None: + continue + if kw in (k.lower() for k in entry.keywords_100): + self._room_map.set_keyword_last_matched(room_id, kw, now) + + def demote_stale_keywords(self, max_age_days: int = 90) -> int: + """FΓΌhrt die 90-Tage-Demotion fΓΌr ungenutzte keywords_100 durch. + + Delegiert an RoomMap.demote_stale_keywords() und baut danach + das interne Keyword-Mapping neu auf. + + Args: + max_age_days: Maximale Tage ohne Match bevor Demotion. + + Returns: + Anzahl der demoted Keywords. + """ + demoted = self._room_map.demote_stale_keywords(max_age_days) + if demoted > 0: + # Mapping neu bauen, da sich keywords_100/keywords_context geΓ€ndert haben + self._build_mapping() + logger.info( + "KeywordBooster: %d stale keywords demoted, mapping rebuilt", + demoted, + ) + return demoted + def reload(self) -> None: """Baut das Keyword-Mapping neu (nach RoomMap.reload()).""" self._build_mapping() diff --git a/tests/test_booster.py b/tests/test_booster.py index 5ca11fe..1a18169 100644 --- a/tests/test_booster.py +++ b/tests/test_booster.py @@ -107,10 +107,10 @@ class TestBoostUniqueKeyword: result = booster.boost(text, scores) # Assert - # room_a: 0.80 + 0.05 = 0.85 + # room_a: 0.80 + 0.10 = 0.90 # room_b: 0.75 (unverΓ€ndert) assert result[0][0] == "room_a" - assert result[0][1] == pytest.approx(0.85) + assert result[0][1] == pytest.approx(0.90) assert result[1][0] == "room_b" assert result[1][1] == pytest.approx(0.75) @@ -128,10 +128,10 @@ class TestBoostUniqueKeyword: result = booster.boost(text, scores) - # room_b: 0.75 + 3Γ—0.05 = 0.90 + # room_b: 0.75 + 3Γ—0.10 + 2Γ—0.05 = 1.15 # room_a: 0.80 (kein Keyword-Match) assert result[0][0] == "room_b" - assert result[0][1] == pytest.approx(0.90) + assert result[0][1] == pytest.approx(1.15) assert result[1][0] == "room_a" assert result[1][1] == pytest.approx(0.80) @@ -146,10 +146,10 @@ class TestBoostUniqueKeyword: result = booster.boost(text, scores) - # room_a: 0.70 + 3Γ—0.05 = 0.85 + # room_a: 0.70 + 3Γ—0.10 + 2Γ—0.05 = 1.10 # room_b: 0.80 (gateway ist shared β†’ kein Boost) assert result[0][0] == "room_a" - assert result[0][1] == pytest.approx(0.85) + assert result[0][1] == pytest.approx(1.10) assert result[1][0] == "room_b" assert result[1][1] == pytest.approx(0.80) @@ -164,10 +164,10 @@ class TestBoostUniqueKeyword: result = booster.boost(text, scores) - # room_a: 0.70 + 0.05 = 0.75 - assert result[0][0] == "room_b" # 0.80 > 0.75 - assert result[1][0] == "room_a" - assert result[1][1] == pytest.approx(0.75) + # room_a: 0.70 + 0.10 = 0.80 + assert result[0][0] == "room_a" # 0.80 == 0.80, room_a hat unique keyword + assert result[1][0] == "room_b" + assert result[1][1] == pytest.approx(0.80) class TestBoostSharedKeyword: @@ -203,10 +203,10 @@ class TestBoostSharedKeyword: result = booster.boost(text, scores) - # room_a: 0.80 + 0.05 = 0.85 + # room_a: 0.80 + 0.10 = 0.90 # room_b: 0.75 (gateway shared β†’ kein Boost) assert result[0][0] == "room_a" - assert result[0][1] == pytest.approx(0.85) + assert result[0][1] == pytest.approx(0.90) assert result[1][0] == "room_b" assert result[1][1] == pytest.approx(0.75) @@ -249,7 +249,7 @@ class TestBoostEdgeCases: result = booster.boost(text, scores) assert result[0][0] == "room_a" - assert result[0][1] == pytest.approx(0.85) + assert result[0][1] == pytest.approx(0.90) def test_keyword_as_substring(self, booster: KeywordBooster) -> None: """Keyword-Matching ist substring-basiert (nicht word-boundary).""" @@ -263,7 +263,7 @@ class TestBoostEdgeCases: result = booster.boost(text, scores) assert result[0][0] == "room_a" - assert result[0][1] == pytest.approx(0.85) + assert result[0][1] == pytest.approx(0.90) def test_catch_all_keywords_ignored(self, booster: KeywordBooster) -> None: """Catch-All-Raum hat keine Keywords β†’ nimmt nicht an Boosts teil.""" @@ -277,7 +277,7 @@ class TestBoostEdgeCases: # room_a bekommt Boost, room_catchall nicht assert result[0][0] == "room_a" - assert result[0][1] == pytest.approx(0.85) + assert result[0][1] == pytest.approx(0.90) # room_catchall bleibt bei 0.60 catchall_score = next(s for rid, s in result if rid == "room_catchall") assert catchall_score == pytest.approx(0.60) @@ -293,7 +293,7 @@ class TestBoostEdgeCases: assert len(result) == 1 assert result[0][0] == "room_a" - assert result[0][1] == pytest.approx(0.85) + assert result[0][1] == pytest.approx(0.90) # ═══════════════════════════════════════════════════════════════════════════ @@ -378,10 +378,10 @@ class TestConflictResolution: result = booster.boost(text, scores) - # room_a: 0.82 + 0.05 (unique boost) + 0.02 (conflict) = 0.89 + # room_a: 0.82 + 0.10 (unique boost) + 0.05 (conflict) = 0.97 # room_b: 0.87 (gateway shared β†’ kein Boost, 0 unique β†’ kein conflict boost) assert result[0][0] == "room_a" - assert result[0][1] == pytest.approx(0.89) + assert result[0][1] == pytest.approx(0.97) assert result[1][0] == "room_b" assert result[1][1] == pytest.approx(0.87) @@ -399,7 +399,7 @@ class TestConflictResolution: result = booster.boost(text, scores) assert result[0][0] == "room_b" - assert result[0][1] == pytest.approx(0.89) + assert result[0][1] == pytest.approx(0.97) assert result[1][0] == "room_a" assert result[1][1] == pytest.approx(0.87) @@ -472,9 +472,9 @@ class TestConflictResolution: result = booster.boost(text, scores3) assert result[0][0] == "room_a" - assert result[0][1] == pytest.approx(0.94) + assert result[0][1] == pytest.approx(1.07) assert result[1][0] == "room_b" - assert result[1][1] == pytest.approx(0.92) + assert result[1][1] == pytest.approx(0.97) class TestConflictEdgeCases: @@ -495,7 +495,7 @@ class TestConflictEdgeCases: assert len(result) == 1 assert result[0][0] == "room_a" - assert result[0][1] == pytest.approx(0.85) # nur unique Boost + assert result[0][1] == pytest.approx(0.90) # nur unique Boost def test_three_scores_conflict_only_top2(self, booster: KeywordBooster) -> None: """Bei 3 Scores: KonfliktlΓΆsung betrachtet NUR Top-1 und Top-2.""" @@ -524,7 +524,7 @@ class TestConflictEdgeCases: ("room_b", 0.75), ] result_before = booster.boost("plugin bug", scores) - assert result_before[0][1] == pytest.approx(0.85) + assert result_before[0][1] == pytest.approx(0.90) # Γ„ndere RoomMap: fΓΌge "plugin" auch zu room_b hinzu room_map = booster._room_map @@ -602,3 +602,137 @@ class TestBoosterCleanup: # "plugin" ist unique fΓΌr room_a β†’ +0.10 (tatsΓ€chlicher Boost-Wert) assert result[0][0] == "room_a" assert result[0][1] == pytest.approx(0.90) + + +# ═══════════════════════════════════════════════════════════════════════════ +# V8.2 A3: 90-Tage-Keyword-Booster-Demotion +# ═══════════════════════════════════════════════════════════════════════════ + +class TestV82A3RecordMatches: + """V8.2 A3: _record_matches() setzt last_matched-Timestamps.""" + + @pytest.fixture + def booster(self) -> KeywordBooster: + return KeywordBooster(_make_booster_room_map()) + + def test_record_matches_sets_timestamp_for_100_keywords(self, booster: KeywordBooster) -> None: + """_record_matches setzt _keyword_last_matched fΓΌr keywords_100.""" + # "rocketchat" ist keywords_100 fΓΌr room_a + booster._record_matches("rocketchat websocket", ["rocketchat"]) + + entry = booster._room_map.get_room_by_id("room_a") + assert entry is not None + assert "rocketchat" in entry._keyword_last_matched + # Timestamp sollte ISO-Format sein + from datetime import datetime + ts = entry._keyword_last_matched["rocketchat"] + datetime.fromisoformat(ts) # wirft ValueError wenn nicht ISO + + def test_record_matches_skips_context_keywords(self, booster: KeywordBooster) -> None: + """_record_matches tracked NUR keywords_100, nicht keywords_context.""" + # "plugin" ist keywords_context fΓΌr room_a (nicht keywords_100) + booster._record_matches("plugin bug", ["plugin"]) + + entry = booster._room_map.get_room_by_id("room_a") + assert entry is not None + # "plugin" ist context, nicht 100 β†’ kein Timestamp + assert "plugin" not in entry._keyword_last_matched + + def test_record_matches_handles_shared_keyword(self, booster: KeywordBooster) -> None: + """_record_matches tracked shared keywords in allen betroffenen RΓ€umen.""" + # "gateway" ist keywords_context in room_a UND room_b + # β†’ kein keywords_100 β†’ keine Timestamps + booster._record_matches("gateway issue", ["gateway"]) + + entry_a = booster._room_map.get_room_by_id("room_a") + entry_b = booster._room_map.get_room_by_id("room_b") + assert "gateway" not in entry_a._keyword_last_matched + assert "gateway" not in entry_b._keyword_last_matched + + def test_record_matches_handles_unknown_keyword(self, booster: KeywordBooster) -> None: + """_record_matches mit unbekanntem Keyword β†’ kein Fehler.""" + # Sollte nicht crashen + booster._record_matches("xyz unknown", ["xyz"]) + # Kein Assert nΓΆtig β€” kein Crash = bestanden + + def test_boost_calls_record_matches(self, booster: KeywordBooster) -> None: + """boost() ruft _record_matches() auf β†’ Timestamps werden gesetzt.""" + scores: list[tuple[str, float]] = [ + ("room_a", 0.80), + ("room_b", 0.75), + ] + # "rocketchat" ist keywords_100 fΓΌr room_a + booster.boost("rocketchat plugin", scores) + + entry = booster._room_map.get_room_by_id("room_a") + assert "rocketchat" in entry._keyword_last_matched + + +class TestV82A3BoosterDemotion: + """V8.2 A3: KeywordBooster.demote_stale_keywords() delegiert an RoomMap.""" + + @pytest.fixture + def booster(self) -> KeywordBooster: + return KeywordBooster(_make_booster_room_map()) + + def test_demote_stale_delegates_to_room_map(self, booster: KeywordBooster) -> None: + """demote_stale_keywords() delegiert an RoomMap und baut Mapping neu.""" + from datetime import datetime, timedelta + + # Setze "rocketchat" (keywords_100 fΓΌr room_a) auf 91 Tage alt + old_date = (datetime.now() - timedelta(days=91)).isoformat() + booster._room_map.set_keyword_last_matched("room_a", "rocketchat", old_date) + + # Vorher: "rocketchat" ist im Mapping + assert "rocketchat" in booster._keyword_to_rooms + + demoted = booster.demote_stale_keywords(max_age_days=90) + assert demoted >= 1 + + # Nach Demotion: "rocketchat" ist nicht mehr keywords_100 + entry = booster._room_map.get_room_by_id("room_a") + assert "rocketchat" not in entry.keywords_100 + assert "rocketchat" in entry.keywords_context + + # Mapping wurde neu gebaut β†’ "rocketchat" ist jetzt als context-Keyword im Mapping + assert "rocketchat" in booster._keyword_to_rooms + + def test_demote_no_stale_returns_zero(self, booster: KeywordBooster) -> None: + """Keine stale Keywords β†’ demote_stale_keywords() gibt 0 zurΓΌck.""" + # Keine last_matched gesetzt β†’ initial, nicht demoten + demoted = booster.demote_stale_keywords(max_age_days=90) + assert demoted == 0 + + def test_demote_rebuilds_mapping(self, booster: KeywordBooster) -> None: + """Nach Demotion: Mapping enthΓ€lt demoted Keywords als context-Keywords.""" + from datetime import datetime, timedelta + + old_date = (datetime.now() - timedelta(days=100)).isoformat() + booster._room_map.set_keyword_last_matched("room_a", "rocketchat", old_date) + booster._room_map.set_keyword_last_matched("room_a", "ddp", old_date) + + demoted = booster.demote_stale_keywords(max_age_days=90) + assert demoted == 2 + + # Beide Keywords sind jetzt im Mapping (als context) + assert "rocketchat" in booster._keyword_to_rooms + assert "ddp" in booster._keyword_to_rooms + + def test_demote_then_boost_still_works(self, booster: KeywordBooster) -> None: + """Nach Demotion: boost() funktioniert korrekt mit neuem Mapping.""" + from datetime import datetime, timedelta + + old_date = (datetime.now() - timedelta(days=100)).isoformat() + booster._room_map.set_keyword_last_matched("room_a", "rocketchat", old_date) + + booster.demote_stale_keywords(max_age_days=90) + + # "rocketchat" ist jetzt context-Keyword β†’ unique Boost funktioniert noch + scores: list[tuple[str, float]] = [ + ("room_a", 0.80), + ("room_b", 0.75), + ] + result = booster.boost("rocketchat issue", scores) + # room_a bekommt +0.10 (unique keyword, jetzt context) + assert result[0][0] == "room_a" + assert result[0][1] == pytest.approx(0.90)