Compare commits
2 Commits
536f3ecde0
...
65939b3208
| Author | SHA1 | Date | |
|---|---|---|---|
| 65939b3208 | |||
| 6a701dcce4 |
+162
-46
@@ -1283,9 +1283,29 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# P1-4: Prüfe ob ein persistierter Onboarding-State existiert
|
||||
persisted_onboarding = self.archivar._state.get_onboarding_state()
|
||||
if persisted_onboarding and persisted_onboarding.get("operator_room_id"):
|
||||
# Bug C: Zombie-State-Validierung
|
||||
# Prüfe ob der Operator-Raum noch subscribed ist und der Lock aktiv
|
||||
op_room = persisted_onboarding.get("operator_room_id", "")
|
||||
op_room_subscribed = op_room in self._room_info
|
||||
from archivar.onboarding import is_onboarding_locked
|
||||
lock_active = False
|
||||
if op_room_subscribed:
|
||||
# Prüfe ob mindestens ein missing_room-Lock aktiv ist
|
||||
for room in persisted_onboarding.get("missing_rooms", []):
|
||||
if is_onboarding_locked(room.get("room_id", "")):
|
||||
lock_active = True
|
||||
break
|
||||
if op_room_subscribed and lock_active:
|
||||
logger.info("[rocketchat] P1-4: Persistierten Onboarding-State wiederhergestellt")
|
||||
self._onboarding_state = persisted_onboarding
|
||||
self.archivar._stats["onboarding_active"] = True
|
||||
else:
|
||||
logger.warning(
|
||||
"[rocketchat] Bug C: Zombie-Onboarding-State verworfen — "
|
||||
"op_room_subscribed=%s, lock_active=%s",
|
||||
op_room_subscribed, lock_active,
|
||||
)
|
||||
self.archivar._state.clear_onboarding_state()
|
||||
# B9: Trigger-Bedingungen für Auto-Onboarding
|
||||
# 1. MULTIROOM_AGENT=true (bereits geprüft durch _MULTIROOM())
|
||||
# 2. Gateway findet Räume die nicht in room-map.json stehen
|
||||
@@ -3053,21 +3073,30 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
async def _cmd_onboarding(self, room_id: str, args: str) -> str:
|
||||
"""::onboarding — Startet das Onboarding für einen Raum neu.
|
||||
|
||||
Ohne Args: Onboarding für den aktuellen Raum.
|
||||
Ohne Args: Onboarding für ALLE fehlenden c/p-Räume (wie connect()-Auto-Trigger).
|
||||
Mit Raumname: Onboarding für den angegebenen Raum.
|
||||
"""
|
||||
if not _MULTIROOM() or self.archivar is None:
|
||||
return "❌ `::onboarding` ist nur im Multiroom-Modus verfügbar."
|
||||
|
||||
target_room_id = room_id
|
||||
target_room_name = self._room_info.get(room_id, {}).get("name", room_id)
|
||||
# Onboarding-State zurücksetzen falls aktiv
|
||||
if self._onboarding_state:
|
||||
from archivar.onboarding import release_onboarding_lock
|
||||
missing = self._onboarding_state.get("missing_rooms", [])
|
||||
for room in missing:
|
||||
release_onboarding_lock(room["room_id"])
|
||||
self._onboarding_state = {}
|
||||
if self.archivar is not None:
|
||||
self.archivar._stats["onboarding_active"] = False
|
||||
self.archivar._state.clear_onboarding_state()
|
||||
|
||||
# Wenn ein Raumname als Argument angegeben ist, suche die ID
|
||||
room_arg = args.strip()
|
||||
if room_arg:
|
||||
# Suche nach Raumname (mit oder ohne #)
|
||||
# Mit Raumname: Onboarding für den angegebenen Raum
|
||||
search_name = room_arg.lstrip("#").lower()
|
||||
found = False
|
||||
target_room_id = room_id
|
||||
target_room_name = self._room_info.get(room_id, {}).get("name", room_id)
|
||||
for rid, info in self._room_info.items():
|
||||
if info.get("name", "").lstrip("#").lower() == search_name:
|
||||
target_room_id = rid
|
||||
@@ -3081,23 +3110,22 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"\n".join(f"- {info.get('name', rid)}" for rid, info in self._room_info.items()
|
||||
if info.get("type") in ("c", "p"))
|
||||
)
|
||||
missing = [{"room_id": target_room_id, "name": target_room_name}]
|
||||
else:
|
||||
# Bug B: Ohne Args → alle fehlenden c/p-Räume finden (wie connect())
|
||||
subscribed_with_types = {
|
||||
rid: {"name": info.get("name", ""), "type": info.get("type", "d")}
|
||||
for rid, info in self._room_info.items()
|
||||
}
|
||||
missing = self.archivar.check_room_map_completeness(subscribed_with_types)
|
||||
if not missing:
|
||||
return (
|
||||
"✅ **Room-Map ist vollständig**\n\n"
|
||||
f"Alle {len([r for r in self._room_info.values() if r.get('type') in ('c','p')])} "
|
||||
"c/p-Räume sind in der Map eingetragen.\n\n"
|
||||
"💡 `::onboarding #Raumname` — Onboarding für einen bestimmten Raum starten"
|
||||
)
|
||||
|
||||
# Onboarding-State zurücksetzen falls aktiv
|
||||
if self._onboarding_state:
|
||||
from archivar.onboarding import release_onboarding_lock
|
||||
missing = self._onboarding_state.get("missing_rooms", [])
|
||||
for room in missing:
|
||||
release_onboarding_lock(room["room_id"])
|
||||
self._onboarding_state = {}
|
||||
if self.archivar is not None:
|
||||
self.archivar._stats["onboarding_active"] = False
|
||||
self.archivar._state.clear_onboarding_state()
|
||||
|
||||
# Onboarding für den Zielraum starten
|
||||
missing = [{
|
||||
"room_id": target_room_id,
|
||||
"name": target_room_name,
|
||||
}]
|
||||
await self._start_onboarding(missing)
|
||||
|
||||
return "" # _start_onboarding postet selbst
|
||||
@@ -3128,37 +3156,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 (
|
||||
@@ -3418,10 +3527,17 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
dm_needs_onboarding = True
|
||||
|
||||
if dm_needs_onboarding:
|
||||
# Bug A: Dedup — DM nicht doppelt anhängen wenn bereits in missing_rooms
|
||||
dm_already_in_missing = any(
|
||||
r.get("room_id") == operator_room_id for r in missing_rooms
|
||||
)
|
||||
if not dm_already_in_missing:
|
||||
dm_name = self._room_info.get(operator_room_id, {}).get("name", "DM")
|
||||
dm_room = {"room_id": operator_room_id, "name": dm_name, "is_dm": True}
|
||||
missing_rooms = list(missing_rooms) + [dm_room]
|
||||
logger.info("[rocketchat] DM '%s' wird thematisch onboardet (als letzter Raum)", dm_name)
|
||||
else:
|
||||
logger.debug("[rocketchat] Bug A: DM bereits in missing_rooms — überspringe Dedup")
|
||||
|
||||
# Guard: Wenn nach DM-Prüfung nichts zu onboarden ist → return
|
||||
if not missing_rooms:
|
||||
|
||||
@@ -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()
|
||||
|
||||
+157
-23
@@ -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)
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
"""
|
||||
V8.5 Onboarding-Bug-Fixes: Tests für Bug A (DM-Dedup), Bug B (::onboarding ohne Args),
|
||||
Bug C (Zombie-State-Validierung).
|
||||
|
||||
Dons Diagnose:
|
||||
Bug A: DM doppelt im Onboarding — check_room_map_completeness() wird zweimal gerufen
|
||||
Bug B: Private Groups (p) fehlen im Onboarding — ::onboarding ohne Args isoliert nur aktuellen Raum
|
||||
Bug C: Blockierter Auto-Trigger durch persistierten Zombie-State
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
# Ensure the archivar package is importable
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from plugin.archivar.room_map import RoomMap, RoomEntry
|
||||
from plugin.archivar.onboarding import (
|
||||
check_room_map_completeness,
|
||||
check_room_map_completeness_delta,
|
||||
acquire_onboarding_lock,
|
||||
release_onboarding_lock,
|
||||
is_onboarding_locked,
|
||||
LOCK_DIR,
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Helpers
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
def _make_room_map() -> RoomMap:
|
||||
"""Erzeugt eine RoomMap mit 2 c-Räumen (kein DM)."""
|
||||
rooms: dict[str, RoomEntry] = {
|
||||
"room_plugin": RoomEntry(
|
||||
room_id="room_plugin",
|
||||
name="#plugin-dev",
|
||||
theme="Plugin-Entwicklung",
|
||||
keywords_100=["rocketchat", "ddp"],
|
||||
keywords_context=["gateway", "deployment"],
|
||||
catch_all=False,
|
||||
),
|
||||
"room_bat": RoomEntry(
|
||||
room_id="room_bat",
|
||||
name="#bat-trading",
|
||||
theme="BAT Trading",
|
||||
keywords_100=["bat", "trading"],
|
||||
keywords_context=["docker", "api"],
|
||||
catch_all=False,
|
||||
),
|
||||
}
|
||||
return RoomMap(
|
||||
rooms=rooms,
|
||||
excluded_room_ids=set(),
|
||||
fact_store_path=Path("/tmp/test_docs"),
|
||||
version=2,
|
||||
)
|
||||
|
||||
|
||||
def _make_subscribed_rooms(extra: dict | None = None) -> dict:
|
||||
"""Erzeugt subscribed_rooms mit 2 c-Räumen, 1 p-Raum, 1 DM."""
|
||||
rooms = {
|
||||
"room_plugin": {"name": "#plugin-dev", "type": "c"},
|
||||
"room_bat": {"name": "#bat-trading", "type": "c"},
|
||||
"room_private": {"name": "private-group", "type": "p"},
|
||||
"room_dm": {"name": "andreas", "type": "d"},
|
||||
}
|
||||
if extra:
|
||||
rooms.update(extra)
|
||||
return rooms
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Bug A: DM-Dedup
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestBugADmDedup:
|
||||
"""Bug A: DM soll nicht doppelt im Onboarding-Menü erscheinen."""
|
||||
|
||||
def test_check_room_map_completeness_excludes_dm(self):
|
||||
"""check_room_map_completeness() filtert type='d' Räume aus."""
|
||||
rm = _make_room_map()
|
||||
subscribed = _make_subscribed_rooms()
|
||||
# Füge einen neuen c-Raum hinzu, der nicht in der Map ist
|
||||
subscribed["room_new_c"] = {"name": "#new-channel", "type": "c"}
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
map_path = f.name
|
||||
try:
|
||||
RoomMap.save(rm, Path(map_path))
|
||||
missing = check_room_map_completeness(rm, subscribed, map_path)
|
||||
# Sollte nur room_new_c und room_private enthalten, NICHT room_dm
|
||||
missing_ids = [m["room_id"] for m in missing]
|
||||
assert "room_new_c" in missing_ids
|
||||
assert "room_private" in missing_ids
|
||||
assert "room_dm" not in missing_ids, "DM-Raum darf nicht in missing_rooms sein"
|
||||
finally:
|
||||
os.unlink(map_path)
|
||||
|
||||
def test_dm_not_in_missing_when_already_in_map(self):
|
||||
"""Wenn DM bereits in der Map ist, wird er nicht als fehlend gemeldet."""
|
||||
rm = _make_room_map()
|
||||
# DM ist bereits in der Map
|
||||
rm.add_or_update_room(
|
||||
room_id="room_dm",
|
||||
name="DM",
|
||||
theme="Admin-DM",
|
||||
keywords_100=[],
|
||||
keywords_context=[],
|
||||
catch_all=True,
|
||||
)
|
||||
subscribed = _make_subscribed_rooms()
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
map_path = f.name
|
||||
try:
|
||||
RoomMap.save(rm, Path(map_path))
|
||||
missing = check_room_map_completeness(rm, subscribed, map_path)
|
||||
missing_ids = [m["room_id"] for m in missing]
|
||||
assert "room_dm" not in missing_ids, "DM in Map soll nicht als fehlend gemeldet werden"
|
||||
finally:
|
||||
os.unlink(map_path)
|
||||
|
||||
def test_dedup_logic_dm_already_in_missing(self):
|
||||
"""Simuliert _start_onboarding Dedup: DM nicht anhängen wenn schon in missing_rooms."""
|
||||
# missing_rooms enthält bereits den DM (z.B. von check_room_map_completeness
|
||||
# wenn DM nicht in Map ist und subscribed_with_types den DM enthält)
|
||||
missing_rooms = [
|
||||
{"room_id": "room_new_c", "name": "#new-channel"},
|
||||
{"room_id": "room_dm", "name": "DM"},
|
||||
]
|
||||
operator_room_id = "room_dm"
|
||||
|
||||
# Dedup-Logik (wie in _start_onboarding)
|
||||
dm_already_in_missing = any(
|
||||
r.get("room_id") == operator_room_id for r in missing_rooms
|
||||
)
|
||||
assert dm_already_in_missing, "DM sollte als bereits vorhanden erkannt werden"
|
||||
|
||||
if not dm_already_in_missing:
|
||||
missing_rooms.append({"room_id": operator_room_id, "name": "DM", "is_dm": True})
|
||||
|
||||
# DM soll nur EINMAL in der Liste sein
|
||||
dm_count = sum(1 for r in missing_rooms if r.get("room_id") == operator_room_id)
|
||||
assert dm_count == 1, f"DM erscheint {dm_count}x statt 1x"
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Bug B: ::onboarding ohne Args → alle fehlenden c/p-Räume
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestBugBOnboardingAllRooms:
|
||||
"""Bug B: ::onboarding ohne Args soll alle fehlenden c/p-Räume finden."""
|
||||
|
||||
def test_check_room_map_completeness_includes_private_groups(self):
|
||||
"""check_room_map_completeness() findet type='p' Räume (private groups)."""
|
||||
rm = _make_room_map()
|
||||
subscribed = _make_subscribed_rooms()
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
map_path = f.name
|
||||
try:
|
||||
RoomMap.save(rm, Path(map_path))
|
||||
missing = check_room_map_completeness(rm, subscribed, map_path)
|
||||
# room_private (type='p') ist nicht in der Map → muss in missing sein
|
||||
missing_ids = [m["room_id"] for m in missing]
|
||||
assert "room_private" in missing_ids, (
|
||||
"Private Group (type='p') muss in missing_rooms sein"
|
||||
)
|
||||
finally:
|
||||
os.unlink(map_path)
|
||||
|
||||
def test_check_room_map_completeness_returns_all_missing(self):
|
||||
"""Wenn mehrere c/p-Räume fehlen, werden ALLE zurückgegeben."""
|
||||
rm = RoomMap(
|
||||
rooms={},
|
||||
excluded_room_ids=set(),
|
||||
fact_store_path=Path("/tmp/test_docs"),
|
||||
version=2,
|
||||
) # Leere Map
|
||||
subscribed = _make_subscribed_rooms()
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
map_path = f.name
|
||||
try:
|
||||
RoomMap.save(rm, Path(map_path))
|
||||
missing = check_room_map_completeness(rm, subscribed, map_path)
|
||||
missing_ids = {m["room_id"] for m in missing}
|
||||
# Alle c/p-Räume müssen fehlen, DM nicht
|
||||
assert "room_plugin" in missing_ids
|
||||
assert "room_bat" in missing_ids
|
||||
assert "room_private" in missing_ids
|
||||
assert "room_dm" not in missing_ids
|
||||
assert len(missing) == 3, f"Erwarte 3 fehlende Räume, bekam {len(missing)}"
|
||||
finally:
|
||||
os.unlink(map_path)
|
||||
|
||||
def test_check_room_map_completeness_empty_when_complete(self):
|
||||
"""Wenn alle c/p-Räume in der Map sind → leere Liste."""
|
||||
rm = _make_room_map()
|
||||
# room_private auch in die Map aufnehmen
|
||||
rm.add_or_update_room(
|
||||
room_id="room_private",
|
||||
name="private-group",
|
||||
theme="Private Gruppe",
|
||||
keywords_100=["intern"],
|
||||
keywords_context=[],
|
||||
catch_all=False,
|
||||
)
|
||||
subscribed = _make_subscribed_rooms()
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
map_path = f.name
|
||||
try:
|
||||
RoomMap.save(rm, Path(map_path))
|
||||
missing = check_room_map_completeness(rm, subscribed, map_path)
|
||||
assert missing == [], f"Map vollständig, erwarte [], bekam {missing}"
|
||||
finally:
|
||||
os.unlink(map_path)
|
||||
|
||||
def test_single_room_rule_auto_assigns(self):
|
||||
"""Single-Room-Regel: Nur 1 c/p-Raum → automatisch als Catch-All."""
|
||||
rm = RoomMap(
|
||||
rooms={},
|
||||
excluded_room_ids=set(),
|
||||
fact_store_path=Path("/tmp/test_docs"),
|
||||
version=2,
|
||||
) # Leere Map
|
||||
subscribed = {
|
||||
"room_only": {"name": "#only-channel", "type": "c"},
|
||||
"room_dm": {"name": "andreas", "type": "d"},
|
||||
}
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
map_path = f.name
|
||||
try:
|
||||
RoomMap.save(rm, Path(map_path))
|
||||
# Vor reload: add_or_update_room hat room_only in-memory hinzugefügt
|
||||
missing = check_room_map_completeness(rm, subscribed, map_path)
|
||||
# Single-Room-Regel: Raum wird automatisch eingetragen → keine missing
|
||||
assert missing == [], f"Single-Room-Regel: erwarte [], bekam {missing}"
|
||||
# Hinweis: reload() lädt vom default path, nicht von map_path.
|
||||
# In Produktion ist map_path der tatsächliche room-map.json Pfad.
|
||||
finally:
|
||||
os.unlink(map_path)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Bug C: Zombie-State-Validierung
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestBugCZombieState:
|
||||
"""Bug C: Persistierter Zombie-State wird beim Start validiert und verworfen."""
|
||||
|
||||
def setup_method(self):
|
||||
"""Clean up any leftover locks before each test."""
|
||||
import glob
|
||||
for lock_file in glob.glob(str(LOCK_DIR / "onboarding-*.lock")):
|
||||
try:
|
||||
os.unlink(lock_file)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def teardown_method(self):
|
||||
"""Clean up locks after each test."""
|
||||
self.setup_method()
|
||||
|
||||
def test_zombie_state_detected_operator_not_subscribed(self):
|
||||
"""Zombie-State: Operator-Raum nicht mehr subscribed → verwerfen."""
|
||||
# Simuliere: operator_room_id existiert nicht in _room_info
|
||||
persisted_state = {
|
||||
"phase": "fakt_store",
|
||||
"operator_room_id": "room_gone",
|
||||
"missing_rooms": [{"room_id": "room_x", "name": "#x"}],
|
||||
}
|
||||
# _room_info hat diesen Raum nicht
|
||||
room_info = {"room_plugin": {"name": "#plugin-dev", "type": "c"}}
|
||||
|
||||
op_room = persisted_state.get("operator_room_id", "")
|
||||
op_room_subscribed = op_room in room_info
|
||||
assert not op_room_subscribed, "Operator-Raum nicht subscribed → Zombie"
|
||||
|
||||
def test_zombie_state_detected_lock_not_active(self):
|
||||
"""Zombie-State: Kein aktiver Lock → verwerfen."""
|
||||
persisted_state = {
|
||||
"phase": "fakt_store",
|
||||
"operator_room_id": "room_dm",
|
||||
"missing_rooms": [{"room_id": "room_x", "name": "#x"}],
|
||||
}
|
||||
room_info = {"room_dm": {"name": "DM", "type": "d"}}
|
||||
|
||||
op_room = persisted_state.get("operator_room_id", "")
|
||||
op_room_subscribed = op_room in room_info
|
||||
assert op_room_subscribed, "Operator-Raum ist subscribed"
|
||||
|
||||
# Prüfe Lock — keiner aktiv
|
||||
lock_active = False
|
||||
for room in persisted_state.get("missing_rooms", []):
|
||||
if is_onboarding_locked(room.get("room_id", "")):
|
||||
lock_active = True
|
||||
break
|
||||
assert not lock_active, "Kein Lock aktiv → Zombie"
|
||||
|
||||
def test_valid_state_restored_when_lock_active(self):
|
||||
"""Gültiger State: Operator subscribed + Lock aktiv → wiederherstellen."""
|
||||
# Erstelle einen echten Lock
|
||||
room_id = "room_test_valid"
|
||||
acquired = acquire_onboarding_lock(room_id)
|
||||
assert acquired, "Lock sollte erworben werden"
|
||||
|
||||
try:
|
||||
persisted_state = {
|
||||
"phase": "fakt_store",
|
||||
"operator_room_id": "room_dm",
|
||||
"missing_rooms": [{"room_id": room_id, "name": "#test"}],
|
||||
}
|
||||
room_info = {"room_dm": {"name": "DM", "type": "d"}}
|
||||
|
||||
op_room = persisted_state.get("operator_room_id", "")
|
||||
op_room_subscribed = op_room in room_info
|
||||
assert op_room_subscribed
|
||||
|
||||
lock_active = False
|
||||
for room in persisted_state.get("missing_rooms", []):
|
||||
if is_onboarding_locked(room.get("room_id", "")):
|
||||
lock_active = True
|
||||
break
|
||||
assert lock_active, "Lock ist aktiv → State gültig"
|
||||
finally:
|
||||
release_onboarding_lock(room_id)
|
||||
|
||||
def test_zombie_state_with_phase_fakt_store_no_interview(self):
|
||||
"""Zombie: phase=fakt_store aber kein aktives Interview → verwerfen."""
|
||||
# Dies simuliert ::setfakt das einen State mit phase=fakt_store setzt,
|
||||
# aber kein Interview läuft (keine missing_rooms, kein Lock)
|
||||
persisted_state = {
|
||||
"phase": "fakt_store",
|
||||
"operator_room_id": "room_dm",
|
||||
}
|
||||
room_info = {"room_dm": {"name": "DM", "type": "d"}}
|
||||
|
||||
op_room = persisted_state.get("operator_room_id", "")
|
||||
op_room_subscribed = op_room in room_info
|
||||
assert op_room_subscribed
|
||||
|
||||
# Keine missing_rooms → kein Lock kann aktiv sein
|
||||
missing = persisted_state.get("missing_rooms", [])
|
||||
lock_active = False
|
||||
for room in missing:
|
||||
if is_onboarding_locked(room.get("room_id", "")):
|
||||
lock_active = True
|
||||
break
|
||||
assert not lock_active, "Keine missing_rooms → kein Lock → Zombie"
|
||||
|
||||
def test_lock_acquire_release_cycle(self):
|
||||
"""Lock acquire → is_locked → release Zyklus funktioniert."""
|
||||
room_id = "room_test_cycle"
|
||||
# Initial: kein Lock
|
||||
assert not is_onboarding_locked(room_id)
|
||||
|
||||
# Erwerben
|
||||
assert acquire_onboarding_lock(room_id)
|
||||
assert is_onboarding_locked(room_id)
|
||||
|
||||
# Zweiter Erwerb scheitert
|
||||
assert not acquire_onboarding_lock(room_id)
|
||||
|
||||
# Freigeben
|
||||
release_onboarding_lock(room_id)
|
||||
assert not is_onboarding_locked(room_id)
|
||||
|
||||
def test_lock_cleanup_on_state_clear(self):
|
||||
"""Wenn State gecleart wird, werden Locks freigegeben."""
|
||||
room_ids = ["room_test_a", "room_test_b"]
|
||||
for rid in room_ids:
|
||||
acquire_onboarding_lock(rid)
|
||||
|
||||
# Simuliere _cmd_onboarding Cleanup
|
||||
for rid in room_ids:
|
||||
release_onboarding_lock(rid)
|
||||
|
||||
for rid in room_ids:
|
||||
assert not is_onboarding_locked(rid), f"Lock für {rid} sollte freigegeben sein"
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Bug B + Bug A Integration: check_room_map_completeness_delta
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestDeltaCheck:
|
||||
"""Delta-Check für einzelne neue Räume (DDP-Event-Pfad)."""
|
||||
|
||||
def test_delta_check_ignores_dm(self):
|
||||
"""Delta-Check ignoriert type='d' Räume."""
|
||||
rm = _make_room_map()
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
map_path = f.name
|
||||
try:
|
||||
RoomMap.save(rm, Path(map_path))
|
||||
result = check_room_map_completeness_delta(
|
||||
rm, room_id="room_new_dm", room_name="DM", room_type="d", map_path=map_path
|
||||
)
|
||||
assert result is None, "DM-Raum muss ignoriert werden"
|
||||
finally:
|
||||
os.unlink(map_path)
|
||||
|
||||
def test_delta_check_finds_new_channel(self):
|
||||
"""Delta-Check findet neuen Channel (type='c')."""
|
||||
rm = _make_room_map()
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
map_path = f.name
|
||||
try:
|
||||
RoomMap.save(rm, Path(map_path))
|
||||
result = check_room_map_completeness_delta(
|
||||
rm, room_id="room_new_c", room_name="#new-channel",
|
||||
room_type="c", map_path=map_path
|
||||
)
|
||||
assert result is not None
|
||||
assert result["room_id"] == "room_new_c"
|
||||
assert result["name"] == "#new-channel"
|
||||
finally:
|
||||
os.unlink(map_path)
|
||||
|
||||
def test_delta_check_finds_new_private_group(self):
|
||||
"""Delta-Check findet neue Private Group (type='p')."""
|
||||
rm = _make_room_map()
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
map_path = f.name
|
||||
try:
|
||||
RoomMap.save(rm, Path(map_path))
|
||||
result = check_room_map_completeness_delta(
|
||||
rm, room_id="room_new_p", room_name="private-group",
|
||||
room_type="p", map_path=map_path
|
||||
)
|
||||
assert result is not None
|
||||
assert result["room_id"] == "room_new_p"
|
||||
finally:
|
||||
os.unlink(map_path)
|
||||
|
||||
def test_delta_check_skips_existing_room(self):
|
||||
"""Delta-Check: Raum bereits in Map → None."""
|
||||
rm = _make_room_map()
|
||||
with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as f:
|
||||
map_path = f.name
|
||||
try:
|
||||
RoomMap.save(rm, Path(map_path))
|
||||
result = check_room_map_completeness_delta(
|
||||
rm, room_id="room_plugin", room_name="#plugin-dev",
|
||||
room_type="c", map_path=map_path
|
||||
)
|
||||
assert result is None, "Bereits in Map → None"
|
||||
finally:
|
||||
os.unlink(map_path)
|
||||
Reference in New Issue
Block a user