feat: V8.5 — Onboarding ohne Gateway-Reset (DDP-Event + Lazy-Onboarding, Lock-Mechanismus, Begrüßung, Stale-Recovery)
This commit is contained in:
@@ -40,6 +40,9 @@ import re
|
||||
from pathlib import Path
|
||||
from typing import Any, Awaitable, Callable, Dict, Optional, List
|
||||
|
||||
# P1-4: Telemetrie-Import für flush() im Live-Code
|
||||
from .routing_telemetry import routing_telemetry
|
||||
|
||||
# Constants
|
||||
ROOM_MAP_PATH = "~/.hermes/hermes-agent/data/room-map.json"
|
||||
|
||||
@@ -463,6 +466,9 @@ class ArchivarMessageHandler:
|
||||
decision.needs_clarification,
|
||||
)
|
||||
|
||||
# P1-4: Telemetrie flushen — stellt sicher dass Logs im Live-Code landen
|
||||
routing_telemetry.flush()
|
||||
|
||||
return decision
|
||||
|
||||
def detect_routing_contradiction(
|
||||
@@ -1077,6 +1083,8 @@ class ArchivarMessageHandler:
|
||||
def check_room_map_completeness(self, subscribed_rooms: dict) -> list[dict]:
|
||||
"""Vergleicht subscribed rooms mit room-map.json.
|
||||
|
||||
Thin wrapper — delegates to standalone function in archivar.onboarding.
|
||||
|
||||
Args:
|
||||
subscribed_rooms: Mapping von room_id → {"name": str, "type": str} (vom Adapter)
|
||||
|
||||
@@ -1084,43 +1092,63 @@ class ArchivarMessageHandler:
|
||||
Liste fehlender Räume: [{"room_id": "...", "name": "#Raum"}]
|
||||
Leere Liste = Map vollständig.
|
||||
"""
|
||||
# Filter: Nur Räume mit type in ("c", "p") berücksichtigen
|
||||
relevant_rooms = {
|
||||
rid: info for rid, info in subscribed_rooms.items()
|
||||
if info.get("type") in ("c", "p")
|
||||
}
|
||||
|
||||
# Single-Room-Regel: Wenn nur 1 relevanter Raum existiert und dieser
|
||||
# nicht in der Map ist → automatisch als catch_all eintragen
|
||||
if len(relevant_rooms) == 1:
|
||||
single_room_id = list(relevant_rooms.keys())[0]
|
||||
if single_room_id not in self._room_map.rooms:
|
||||
# Automatisch als catch_all eintragen
|
||||
room_info = relevant_rooms[single_room_id]
|
||||
self._room_map.add_or_update_room(
|
||||
room_id=single_room_id,
|
||||
name=room_info["name"],
|
||||
theme="Automatisch zugewiesener Catch-All-Raum",
|
||||
keywords_100=[],
|
||||
keywords_context=[],
|
||||
catch_all=True
|
||||
)
|
||||
# Speichern und neu laden
|
||||
RoomMap.save(self._room_map, Path(os.path.expanduser(ROOM_MAP_PATH)))
|
||||
self._room_map.reload()
|
||||
logger.info("Single room detected — auto-assigned as catch_all: %s", room_info["name"])
|
||||
return [] # Keine weiteren Maßnahmen nötig
|
||||
|
||||
# Normale Prüfung: Welche relevanten Räume fehlen in der Map?
|
||||
missing = []
|
||||
for room_id, room_info in relevant_rooms.items():
|
||||
if room_id not in self._room_map.rooms:
|
||||
missing.append({
|
||||
"room_id": room_id,
|
||||
"name": room_info["name"]
|
||||
})
|
||||
|
||||
return missing
|
||||
from archivar.onboarding import check_room_map_completeness as _check
|
||||
return _check(
|
||||
room_map=self._room_map,
|
||||
subscribed_rooms=subscribed_rooms,
|
||||
map_path=ROOM_MAP_PATH,
|
||||
)
|
||||
|
||||
def check_room_map_completeness_delta(
|
||||
self, room_id: str, room_name: str, room_type: str
|
||||
) -> Optional[dict]:
|
||||
"""Prüft ob ein EINZELNER neuer Raum in der room-map.json fehlt.
|
||||
|
||||
Thin wrapper — delegates to standalone function in archivar.onboarding.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID des neuen Raums.
|
||||
room_name: Anzeigename des Raums (z.B. "#MeinProjekt").
|
||||
room_type: Raum-Typ ("c" = Channel, "p" = Group, "d" = DM).
|
||||
|
||||
Returns:
|
||||
Dict mit {"room_id": ..., "name": ...} wenn der Raum onboardet
|
||||
werden muss, None wenn der Raum bereits in der Map ist oder
|
||||
ignoriert wird (DM, excluded, Single-Room-Regel).
|
||||
"""
|
||||
from archivar.onboarding import check_room_map_completeness_delta as _check
|
||||
return _check(
|
||||
room_map=self._room_map,
|
||||
room_id=room_id,
|
||||
room_name=room_name,
|
||||
room_type=room_type,
|
||||
map_path=ROOM_MAP_PATH,
|
||||
)
|
||||
|
||||
def lazy_onboarding_check(
|
||||
self, room_id: str, room_name: str, room_type: str
|
||||
) -> Optional[dict]:
|
||||
"""A1b: Lazy-Onboarding-Check — Fallback wenn DDP-Event nicht ankam.
|
||||
|
||||
Thin wrapper — delegates to standalone function in archivar.onboarding.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
room_name: Anzeigename des Raums.
|
||||
room_type: Raum-Typ ("c", "p", "d").
|
||||
|
||||
Returns:
|
||||
Dict mit {"room_id": ..., "name": ...} wenn Onboarding nötig,
|
||||
None wenn Raum bekannt, DM, excluded, oder Lock bereits aktiv.
|
||||
"""
|
||||
from archivar.onboarding import lazy_onboarding_check as _check
|
||||
return _check(
|
||||
room_map=self._room_map,
|
||||
room_id=room_id,
|
||||
room_name=room_name,
|
||||
room_type=room_type,
|
||||
onboarding_active=self._stats.get("onboarding_active", False),
|
||||
)
|
||||
|
||||
# ── Configuration ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
@@ -14,11 +14,30 @@ Sicherheitsanforderungen:
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# ── Onboarding Lock Constants ────────────────────────────────────────────────
|
||||
# Lock-Dateien verhindern parallele Onboarding-Interviews für denselben Raum.
|
||||
# Stale-Lock-Cleanup beim Start: 10 Minuten Timeout (Andreas bestätigt).
|
||||
LOCK_DIR = Path(os.path.expanduser("~/.hermes/hermes-agent/data/onboarding_locks"))
|
||||
STALE_LOCK_TIMEOUT_SECONDS = 600 # 10 Minuten
|
||||
|
||||
# ── Onboarding Greeting Constants ────────────────────────────────────────────
|
||||
# Begrüßung vor Interview (Andreas bestätigt).
|
||||
# Bot postet kurze Begrüßung, dann 30s warten (Spam-Vermeidung bei Multi-User-Join).
|
||||
GREETING_TEXT = (
|
||||
"Hi, ich bin neu hier — lass uns kurz klären, "
|
||||
"wie ich euch am besten helfe"
|
||||
)
|
||||
GREETING_DELAY_SECONDS = 30
|
||||
|
||||
# System-Verzeichnisse, die blockiert werden
|
||||
BLOCKED_PREFIXES = [
|
||||
"/etc",
|
||||
@@ -146,3 +165,328 @@ def get_default_fact_store_path() -> str:
|
||||
Absoluter Pfad zu .hermes/wissenssammlung im HOME-Verzeichnis.
|
||||
"""
|
||||
return os.path.expanduser("~/.hermes/wissenssammlung")
|
||||
|
||||
|
||||
# ── Onboarding Lock Mechanism ────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _lock_file_path(room_id: str) -> Path:
|
||||
"""Gibt den Pfad zur Lock-Datei für einen Raum zurück."""
|
||||
return LOCK_DIR / f"onboarding-{room_id}.lock"
|
||||
|
||||
|
||||
def acquire_onboarding_lock(room_id: str) -> bool:
|
||||
"""Erwirbt einen Lock für das Onboarding eines Raums.
|
||||
|
||||
Erstellt eine Lock-Datei mit aktuellem Timestamp.
|
||||
Wenn die Datei bereits existiert, wird False zurückgegeben
|
||||
(ein anderes Interview läuft bereits für diesen Raum).
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
|
||||
Returns:
|
||||
True wenn der Lock erfolgreich erworben wurde, False wenn
|
||||
bereits ein Lock existiert.
|
||||
"""
|
||||
LOCK_DIR.mkdir(parents=True, exist_ok=True)
|
||||
lock_path = _lock_file_path(room_id)
|
||||
try:
|
||||
# O_CREAT | O_EXCL: atomares Create — schlägt fehl wenn Datei existiert
|
||||
fd = os.open(str(lock_path), os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
||||
with os.fdopen(fd, "w") as f:
|
||||
f.write(str(time.time()))
|
||||
logger.debug("Onboarding-Lock erworben: room=%s", room_id[:12])
|
||||
return True
|
||||
except FileExistsError:
|
||||
logger.debug("Onboarding-Lock bereits aktiv: room=%s", room_id[:12])
|
||||
return False
|
||||
|
||||
|
||||
def release_onboarding_lock(room_id: str) -> None:
|
||||
"""Gibt den Onboarding-Lock für einen Raum frei.
|
||||
|
||||
Löscht die Lock-Datei. No-op wenn kein Lock existiert.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
"""
|
||||
lock_path = _lock_file_path(room_id)
|
||||
try:
|
||||
os.remove(str(lock_path))
|
||||
logger.debug("Onboarding-Lock freigegeben: room=%s", room_id[:12])
|
||||
except FileNotFoundError:
|
||||
pass # No-op: Lock existiert nicht
|
||||
|
||||
|
||||
def is_onboarding_locked(room_id: str) -> bool:
|
||||
"""Prüft ob ein Onboarding-Lock für einen Raum existiert.
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
|
||||
Returns:
|
||||
True wenn ein Lock existiert, False sonst.
|
||||
"""
|
||||
return _lock_file_path(room_id).exists()
|
||||
|
||||
|
||||
def cleanup_stale_locks() -> int:
|
||||
"""Entfernt alle Stale-Locks, die älter als STALE_LOCK_TIMEOUT_SECONDS sind.
|
||||
|
||||
Wird beim Gateway-Start aufgerufen. Verhindert dass ein abgestürztes
|
||||
Onboarding-Interview dauerhaft blockiert.
|
||||
|
||||
Returns:
|
||||
Anzahl der entfernten Stale-Locks.
|
||||
"""
|
||||
if not LOCK_DIR.exists():
|
||||
return 0
|
||||
|
||||
now = time.time()
|
||||
removed = 0
|
||||
for lock_file in LOCK_DIR.glob("onboarding-*.lock"):
|
||||
try:
|
||||
mtime = os.path.getmtime(str(lock_file))
|
||||
age = now - mtime
|
||||
if age > STALE_LOCK_TIMEOUT_SECONDS:
|
||||
os.remove(str(lock_file))
|
||||
removed += 1
|
||||
logger.info(
|
||||
"Stale-Lock entfernt: %s (Alter: %.0fs)",
|
||||
lock_file.name, age,
|
||||
)
|
||||
except OSError as e:
|
||||
logger.warning("Fehler beim Stale-Lock-Cleanup für %s: %s", lock_file.name, e)
|
||||
if removed > 0:
|
||||
logger.info("Stale-Lock-Cleanup: %d Locks entfernt", removed)
|
||||
return removed
|
||||
|
||||
|
||||
# ── Onboarding Greeting Flow ─────────────────────────────────────────────────
|
||||
|
||||
|
||||
def build_greeting_message(room_name: str = "") -> str:
|
||||
"""Baut die Begrüßungsnachricht für das Onboarding-Interview.
|
||||
|
||||
Args:
|
||||
room_name: Optionaler Raum-Name für personalisierte Begrüßung.
|
||||
|
||||
Returns:
|
||||
Formatierte Begrüßungsnachricht.
|
||||
"""
|
||||
if room_name:
|
||||
return f"{GREETING_TEXT} — in {room_name}"
|
||||
return GREETING_TEXT
|
||||
|
||||
|
||||
async def run_onboarding_greeting_flow(
|
||||
room_id: str,
|
||||
send_callback,
|
||||
start_interview_callback,
|
||||
room_name: str = "",
|
||||
) -> None:
|
||||
"""Führt den Begrüßungs-Flow vor dem Onboarding-Interview aus.
|
||||
|
||||
1. Postet Begrüßungsnachricht im Raum
|
||||
2. Wartet GREETING_DELAY_SECONDS (30s) — Spam-Vermeidung bei Multi-User-Join
|
||||
3. Startet das Interview via Callback
|
||||
|
||||
Args:
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
send_callback: Async callable (room_id, text) -> bool zum Senden der Begrüßung.
|
||||
start_interview_callback: Async callable () -> None zum Starten des Interviews.
|
||||
room_name: Optionaler Raum-Name.
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
# 1. Begrüßung posten
|
||||
greeting = build_greeting_message(room_name=room_name)
|
||||
try:
|
||||
await send_callback(room_id, greeting)
|
||||
logger.info("Onboarding-Begrüßung gesendet: room=%s", room_id[:12])
|
||||
except Exception as e:
|
||||
logger.warning("Onboarding-Begrüßung fehlgeschlagen: %s", e)
|
||||
|
||||
# 2. 30s warten (Spam-Vermeidung bei Multi-User-Join)
|
||||
await asyncio.sleep(GREETING_DELAY_SECONDS)
|
||||
|
||||
# 3. Interview starten
|
||||
await start_interview_callback()
|
||||
|
||||
|
||||
# ── Room Map Completeness Checks ─────────────────────────────────────────────
|
||||
# Standalone functions extracted from ArchivarMessageHandler (P1-1).
|
||||
# These operate on a RoomMap instance and don't depend on the handler's state.
|
||||
|
||||
|
||||
def check_room_map_completeness(
|
||||
room_map,
|
||||
subscribed_rooms: dict,
|
||||
map_path: str,
|
||||
) -> list:
|
||||
"""Vergleicht subscribed rooms mit room-map.json.
|
||||
|
||||
Standalone version — nimmt room_map als Parameter statt self.
|
||||
|
||||
Args:
|
||||
room_map: RoomMap-Instanz.
|
||||
subscribed_rooms: Mapping von room_id → {"name": str, "type": str}.
|
||||
map_path: Pfad zur room-map.json (zum Speichern bei Single-Room-Regel).
|
||||
|
||||
Returns:
|
||||
Liste fehlender Räume: [{"room_id": "...", "name": "#Raum"}]
|
||||
Leere Liste = Map vollständig.
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
# Filter: Nur Räume mit type in ("c", "p") berücksichtigen
|
||||
relevant_rooms = {
|
||||
rid: info for rid, info in subscribed_rooms.items()
|
||||
if info.get("type") in ("c", "p")
|
||||
}
|
||||
|
||||
# Single-Room-Regel: Wenn nur 1 relevanter Raum existiert und dieser
|
||||
# nicht in der Map ist → automatisch als catch_all eintragen
|
||||
if len(relevant_rooms) == 1:
|
||||
single_room_id = list(relevant_rooms.keys())[0]
|
||||
if single_room_id not in room_map.rooms:
|
||||
room_info = relevant_rooms[single_room_id]
|
||||
room_map.add_or_update_room(
|
||||
room_id=single_room_id,
|
||||
name=room_info["name"],
|
||||
theme="Automatisch zugewiesener Catch-All-Raum",
|
||||
keywords_100=[],
|
||||
keywords_context=[],
|
||||
catch_all=True,
|
||||
)
|
||||
from archivar.room_map import RoomMap
|
||||
RoomMap.save(room_map, Path(os.path.expanduser(map_path)))
|
||||
room_map.reload()
|
||||
logger.info(
|
||||
"Single room detected — auto-assigned as catch_all: %s",
|
||||
room_info["name"],
|
||||
)
|
||||
return []
|
||||
|
||||
# Normale Prüfung: Welche relevanten Räume fehlen in der Map?
|
||||
missing = []
|
||||
for room_id, room_info in relevant_rooms.items():
|
||||
if room_id not in room_map.rooms:
|
||||
missing.append({"room_id": room_id, "name": room_info["name"]})
|
||||
|
||||
return missing
|
||||
|
||||
|
||||
def check_room_map_completeness_delta(
|
||||
room_map,
|
||||
room_id: str,
|
||||
room_name: str,
|
||||
room_type: str,
|
||||
map_path: str,
|
||||
) -> Optional[dict]:
|
||||
"""Prüft ob ein EINZELNER neuer Raum in der room-map.json fehlt.
|
||||
|
||||
Standalone version — nimmt room_map als Parameter statt self.
|
||||
|
||||
Args:
|
||||
room_map: RoomMap-Instanz.
|
||||
room_id: Rocket.Chat Raum-ID des neuen Raums.
|
||||
room_name: Anzeigename des Raums (z.B. "#MeinProjekt").
|
||||
room_type: Raum-Typ ("c" = Channel, "p" = Group, "d" = DM).
|
||||
map_path: Pfad zur room-map.json.
|
||||
|
||||
Returns:
|
||||
Dict mit {"room_id": ..., "name": ...} wenn der Raum onboardet
|
||||
werden muss, None wenn der Raum bereits in der Map ist oder
|
||||
ignoriert wird (DM, excluded, Single-Room-Regel).
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
# DM-Räume ignorieren
|
||||
if room_type == "d":
|
||||
return None
|
||||
|
||||
# Excluded rooms ignorieren
|
||||
if room_map.is_excluded(room_id):
|
||||
return None
|
||||
|
||||
# Bereits in der Map → nichts zu tun
|
||||
if room_id in room_map.rooms:
|
||||
return None
|
||||
|
||||
# Single-Room-Regel: Wenn die Map leer ist (0 Räume) und dies der
|
||||
# erste Channel/Group ist → automatisch als Catch-All eintragen
|
||||
if len(room_map.rooms) == 0:
|
||||
room_map.add_or_update_room(
|
||||
room_id=room_id,
|
||||
name=room_name,
|
||||
theme="Automatisch zugewiesener Catch-All-Raum",
|
||||
keywords_100=[],
|
||||
keywords_context=[],
|
||||
catch_all=True,
|
||||
)
|
||||
from archivar.room_map import RoomMap
|
||||
RoomMap.save(room_map, Path(os.path.expanduser(map_path)))
|
||||
room_map.reload()
|
||||
logger.info(
|
||||
"Delta-Check: Single-Room-Regel — '%s' auto-assigned as catch_all",
|
||||
room_name,
|
||||
)
|
||||
return None
|
||||
|
||||
# Raum fehlt in der Map → Onboarding nötig
|
||||
return {"room_id": room_id, "name": room_name}
|
||||
|
||||
|
||||
def lazy_onboarding_check(
|
||||
room_map,
|
||||
room_id: str,
|
||||
room_name: str,
|
||||
room_type: str,
|
||||
onboarding_active: bool = False,
|
||||
) -> Optional[dict]:
|
||||
"""A1b: Lazy-Onboarding-Check — Fallback wenn DDP-Event nicht ankam.
|
||||
|
||||
Standalone version — nimmt room_map als Parameter statt self.
|
||||
|
||||
Args:
|
||||
room_map: RoomMap-Instanz.
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
room_name: Anzeigename des Raums.
|
||||
room_type: Raum-Typ ("c", "p", "d").
|
||||
onboarding_active: Ob Onboarding bereits aktiv ist.
|
||||
|
||||
Returns:
|
||||
Dict mit {"room_id": ..., "name": ...} wenn Onboarding nötig,
|
||||
None wenn Raum bekannt, DM, excluded, oder Lock bereits aktiv.
|
||||
"""
|
||||
# DM-Räume ignorieren
|
||||
if room_type == "d":
|
||||
return None
|
||||
|
||||
# Excluded rooms ignorieren
|
||||
if room_map.is_excluded(room_id):
|
||||
return None
|
||||
|
||||
# Bereits in der Map → nichts zu tun
|
||||
if room_id in room_map.rooms:
|
||||
return None
|
||||
|
||||
# Onboarding bereits aktiv → nicht erneut triggern
|
||||
if onboarding_active:
|
||||
return None
|
||||
|
||||
# Lock prüfen: verhindert doppelte Interviews für denselben Raum
|
||||
if is_onboarding_locked(room_id):
|
||||
logger.debug("Lazy-Check: Lock bereits aktiv für room=%s", room_id[:12])
|
||||
return None
|
||||
|
||||
# Telemetrie: Lazy-Onboarding-Pfad
|
||||
logger.info(
|
||||
"A1b: Lazy-Onboarding-Pfad — unbekannter Raum: "
|
||||
"room=%s, name=%s, type=%s",
|
||||
room_id[:12], room_name, room_type,
|
||||
)
|
||||
|
||||
return {"room_id": room_id, "name": room_name}
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
"""
|
||||
Integration-Tests für A1b: Onboarding ohne Gateway-Reset.
|
||||
|
||||
Testet beide Pfade:
|
||||
1. DDP-Event-Pfad (Primär): roomMemberAdded / rooms-changed
|
||||
2. Lazy-Onboarding-Pfad (Fallback): erste Nachricht aus unbekanntem Raum
|
||||
|
||||
Plus Telemetrie: Welcher Pfad hat ausgelöst?
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock, patch, call
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||
|
||||
|
||||
class TestOnboardingTelemetry:
|
||||
"""Tests für Telemetrie: Welcher Pfad hat das Onboarding ausgelöst?"""
|
||||
|
||||
def test_ddp_path_logs_correct_telemetry(self):
|
||||
"""DDP-Event-Pfad loggt 'DDP-Event-Pfad'."""
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
from archivar.room_map import RoomMap
|
||||
|
||||
tmpdir = tempfile.TemporaryDirectory()
|
||||
map_path = Path(tmpdir.name) / "room-map.json"
|
||||
test_data = {
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"known_room": {
|
||||
"name": "#KnownRoom",
|
||||
"theme": "Bekannter Raum",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": str(Path(tmpdir.name) / "docs"),
|
||||
}
|
||||
with open(map_path, "w") as f:
|
||||
json.dump(test_data, f)
|
||||
|
||||
with patch("archivar.adapter_integration.ROOM_MAP_PATH", str(map_path)):
|
||||
with patch("archivar.room_map.DEFAULT_MAP_PATH", str(map_path)):
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
# DDP-Event-Pfad: check_room_map_completeness_delta
|
||||
with patch("archivar.adapter_integration.logger") as mock_logger:
|
||||
result = handler.check_room_map_completeness_delta(
|
||||
room_id="new_ddp_room",
|
||||
room_name="#DDPRoom",
|
||||
room_type="c",
|
||||
)
|
||||
assert result is not None
|
||||
|
||||
tmpdir.cleanup()
|
||||
|
||||
def test_lazy_path_logs_correct_telemetry(self):
|
||||
"""Lazy-Onboarding-Pfad loggt 'Lazy-Onboarding-Pfad'."""
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
from archivar.room_map import RoomMap
|
||||
|
||||
tmpdir = tempfile.TemporaryDirectory()
|
||||
map_path = Path(tmpdir.name) / "room-map.json"
|
||||
test_data = {
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"known_room": {
|
||||
"name": "#KnownRoom",
|
||||
"theme": "Bekannter Raum",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": str(Path(tmpdir.name) / "docs"),
|
||||
}
|
||||
with open(map_path, "w") as f:
|
||||
json.dump(test_data, f)
|
||||
|
||||
with patch("archivar.adapter_integration.ROOM_MAP_PATH", str(map_path)):
|
||||
with patch("archivar.room_map.DEFAULT_MAP_PATH", str(map_path)):
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
# Lazy-Pfad: lazy_onboarding_check
|
||||
with patch("archivar.adapter_integration.logger") as mock_logger:
|
||||
result = handler.lazy_onboarding_check(
|
||||
room_id="new_lazy_room",
|
||||
room_name="#LazyRoom",
|
||||
room_type="c",
|
||||
)
|
||||
assert result is not None
|
||||
|
||||
tmpdir.cleanup()
|
||||
|
||||
def test_both_paths_return_same_structure(self):
|
||||
"""Beide Pfade geben die gleiche Dict-Struktur zurück."""
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
from archivar.room_map import RoomMap
|
||||
|
||||
tmpdir = tempfile.TemporaryDirectory()
|
||||
map_path = Path(tmpdir.name) / "room-map.json"
|
||||
test_data = {
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"known_room": {
|
||||
"name": "#KnownRoom",
|
||||
"theme": "Bekannter Raum",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": str(Path(tmpdir.name) / "docs"),
|
||||
}
|
||||
with open(map_path, "w") as f:
|
||||
json.dump(test_data, f)
|
||||
|
||||
with patch("archivar.adapter_integration.ROOM_MAP_PATH", str(map_path)):
|
||||
with patch("archivar.room_map.DEFAULT_MAP_PATH", str(map_path)):
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
ddp_result = handler.check_room_map_completeness_delta(
|
||||
room_id="room_a", room_name="#RoomA", room_type="c"
|
||||
)
|
||||
lazy_result = handler.lazy_onboarding_check(
|
||||
room_id="room_b", room_name="#RoomB", room_type="c"
|
||||
)
|
||||
|
||||
# Beide haben die gleichen Keys
|
||||
assert set(ddp_result.keys()) == set(lazy_result.keys())
|
||||
assert "room_id" in ddp_result
|
||||
assert "name" in ddp_result
|
||||
|
||||
tmpdir.cleanup()
|
||||
|
||||
|
||||
class TestOnboardingIntegration:
|
||||
"""Integration-Tests: Event-Simulation + Lazy-Simulation."""
|
||||
|
||||
def setup_method(self):
|
||||
self.tmpdir = tempfile.TemporaryDirectory()
|
||||
self.map_path = Path(self.tmpdir.name) / "room-map.json"
|
||||
self.test_data = {
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"known_room": {
|
||||
"name": "#KnownRoom",
|
||||
"theme": "Bekannter Raum",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": str(Path(self.tmpdir.name) / "docs"),
|
||||
}
|
||||
with open(self.map_path, "w") as f:
|
||||
json.dump(self.test_data, f)
|
||||
|
||||
def teardown_method(self):
|
||||
self.tmpdir.cleanup()
|
||||
|
||||
def test_ddp_event_simulation_triggers_onboarding(self):
|
||||
"""Simulation: DDP rooms-changed Event → Onboarding wird getriggert."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = True
|
||||
received_events = []
|
||||
client._on_room_event = lambda event: received_events.append(event)
|
||||
|
||||
# Simuliere rooms-changed Event für neuen Raum
|
||||
event_data = {
|
||||
"msg": "changed",
|
||||
"collection": "stream-notify-room",
|
||||
"fields": {
|
||||
"eventName": "rooms-changed",
|
||||
"args": [
|
||||
"new_room_abc",
|
||||
{"type": "c", "name": "#NeuerChannel"},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
client._handle_ddp_message(event_data)
|
||||
|
||||
assert len(received_events) == 1
|
||||
event = received_events[0]
|
||||
assert event["room_id"] == "new_room_abc"
|
||||
assert event["name"] == "#NeuerChannel"
|
||||
assert event["type"] == "c"
|
||||
|
||||
def test_lazy_simulation_triggers_on_first_message(self):
|
||||
"""Simulation: Erste Nachricht aus unbekanntem Raum → Lazy-Onboarding."""
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
from archivar.room_map import RoomMap
|
||||
|
||||
with patch("archivar.adapter_integration.ROOM_MAP_PATH", str(self.map_path)):
|
||||
with patch("archivar.room_map.DEFAULT_MAP_PATH", str(self.map_path)):
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
# Erste Nachricht aus unbekanntem Raum
|
||||
result = handler.lazy_onboarding_check(
|
||||
room_id="unknown_room_xyz",
|
||||
room_name="#Unbekannt",
|
||||
room_type="c",
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert result["room_id"] == "unknown_room_xyz"
|
||||
|
||||
def test_lock_prevents_duplicate_onboarding(self):
|
||||
"""Integration: Lock verhindert parallele Onboarding-Interviews."""
|
||||
from archivar.onboarding import (
|
||||
acquire_onboarding_lock,
|
||||
release_onboarding_lock,
|
||||
is_onboarding_locked,
|
||||
)
|
||||
|
||||
room_id = "integration_room"
|
||||
|
||||
# Erstes Onboarding startet
|
||||
assert acquire_onboarding_lock(room_id) is True
|
||||
assert is_onboarding_locked(room_id) is True
|
||||
|
||||
# Zweites Onboarding wird blockiert
|
||||
assert acquire_onboarding_lock(room_id) is False
|
||||
|
||||
# Nach Abschluss: Lock freigeben
|
||||
release_onboarding_lock(room_id)
|
||||
assert is_onboarding_locked(room_id) is False
|
||||
|
||||
# Jetzt kann wieder ein Onboarding starten
|
||||
assert acquire_onboarding_lock(room_id) is True
|
||||
release_onboarding_lock(room_id)
|
||||
|
||||
def test_stale_lock_cleanup_on_start(self):
|
||||
"""Integration: Stale-Lock-Cleanup beim Start entfernt alte Locks."""
|
||||
from archivar.onboarding import (
|
||||
acquire_onboarding_lock,
|
||||
cleanup_stale_locks,
|
||||
is_onboarding_locked,
|
||||
LOCK_DIR,
|
||||
STALE_LOCK_TIMEOUT_SECONDS,
|
||||
)
|
||||
|
||||
# Erstelle einen Lock
|
||||
room_id = "stale_integration_room"
|
||||
assert acquire_onboarding_lock(room_id) is True
|
||||
|
||||
# Setze mtime auf 11 Minuten in der Vergangenheit
|
||||
lock_file = LOCK_DIR / f"onboarding-{room_id}.lock"
|
||||
stale_time = time.time() - (STALE_LOCK_TIMEOUT_SECONDS + 60)
|
||||
import os
|
||||
os.utime(str(lock_file), (stale_time, stale_time))
|
||||
|
||||
# Cleanup sollte den Stale-Lock entfernen
|
||||
removed = cleanup_stale_locks()
|
||||
assert removed >= 1
|
||||
assert not is_onboarding_locked(room_id)
|
||||
|
||||
def test_stale_recovery_on_reconnect(self):
|
||||
"""F6 Re-Review Fix 3: Stale-Recovery bei Reconnect.
|
||||
|
||||
Szenario: Lock vorhanden + älter als 10 Min → Reconnect →
|
||||
Lock wird bereinigt → Onboarding kann neu starten.
|
||||
|
||||
Dies schützt die Symmetrie von acquire/release durch CI.
|
||||
"""
|
||||
from archivar.onboarding import (
|
||||
acquire_onboarding_lock,
|
||||
cleanup_stale_locks,
|
||||
is_onboarding_locked,
|
||||
LOCK_DIR,
|
||||
STALE_LOCK_TIMEOUT_SECONDS,
|
||||
)
|
||||
|
||||
room_id = "reconnect_stale_room"
|
||||
|
||||
# Schritt 1: Lock erwerben (simuliert laufendes Onboarding)
|
||||
assert acquire_onboarding_lock(room_id) is True
|
||||
assert is_onboarding_locked(room_id) is True
|
||||
|
||||
# Schritt 2: Lock auf >10 Minuten altern lassen
|
||||
lock_file = LOCK_DIR / f"onboarding-{room_id}.lock"
|
||||
stale_time = time.time() - (STALE_LOCK_TIMEOUT_SECONDS + 120)
|
||||
import os
|
||||
os.utime(str(lock_file), (stale_time, stale_time))
|
||||
|
||||
# Schritt 3: Reconnect simuliert — cleanup_stale_locks() wird aufgerufen
|
||||
# (wie in connect() und _reconnect_ddp())
|
||||
removed = cleanup_stale_locks()
|
||||
assert removed >= 1, "Stale-Lock sollte beim Reconnect bereinigt werden"
|
||||
assert not is_onboarding_locked(room_id), (
|
||||
"Nach Stale-Cleanup darf kein Lock mehr existieren"
|
||||
)
|
||||
|
||||
# Schritt 4: Onboarding kann neu starten (acquire muss jetzt gelingen)
|
||||
assert acquire_onboarding_lock(room_id) is True, (
|
||||
"Nach Stale-Cleanup muss ein neuer Lock erworben werden können"
|
||||
)
|
||||
assert is_onboarding_locked(room_id) is True
|
||||
|
||||
# Aufräumen
|
||||
from archivar.onboarding import release_onboarding_lock
|
||||
release_onboarding_lock(room_id)
|
||||
assert not is_onboarding_locked(room_id)
|
||||
|
||||
def test_full_flow_ddp_to_onboarding(self):
|
||||
"""Integration: Vollständiger Flow DDP-Event → Delta-Check → Onboarding."""
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
from archivar.room_map import RoomMap
|
||||
|
||||
with patch("archivar.adapter_integration.ROOM_MAP_PATH", str(self.map_path)):
|
||||
with patch("archivar.room_map.DEFAULT_MAP_PATH", str(self.map_path)):
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
# Schritt 1: DDP-Event kommt rein → Delta-Check
|
||||
delta = handler.check_room_map_completeness_delta(
|
||||
room_id="flow_room",
|
||||
room_name="#FlowRoom",
|
||||
room_type="c",
|
||||
)
|
||||
assert delta is not None
|
||||
assert delta["room_id"] == "flow_room"
|
||||
|
||||
# Schritt 2: Onboarding würde jetzt gestartet (via _start_onboarding)
|
||||
# Das testen wir nicht direkt, weil es async ist und Buttons sendet.
|
||||
# Aber wir prüfen, dass der Lock-Mechanismus funktioniert.
|
||||
|
||||
def test_full_flow_lazy_to_onboarding(self):
|
||||
"""Integration: Vollständiger Flow Lazy-Check → Onboarding."""
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
from archivar.room_map import RoomMap
|
||||
|
||||
with patch("archivar.adapter_integration.ROOM_MAP_PATH", str(self.map_path)):
|
||||
with patch("archivar.room_map.DEFAULT_MAP_PATH", str(self.map_path)):
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
# Schritt 1: Nachricht aus unbekanntem Raum → Lazy-Check
|
||||
lazy = handler.lazy_onboarding_check(
|
||||
room_id="lazy_flow_room",
|
||||
room_name="#LazyFlow",
|
||||
room_type="c",
|
||||
)
|
||||
assert lazy is not None
|
||||
assert lazy["room_id"] == "lazy_flow_room"
|
||||
|
||||
# Schritt 2: Onboarding würde jetzt gestartet
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
Tests für check_room_map_completeness(delta) — Einzelraum-Prüfung (A1b).
|
||||
|
||||
Wird vom DDP-Event-Handler aufgerufen, wenn ein neuer Raum entdeckt wird
|
||||
(roomMemberAdded / rooms-changed). Prüft nur den EINEN neuen Raum,
|
||||
nicht alle subscribed rooms.
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
from archivar.room_map import RoomMap, RoomEntry
|
||||
|
||||
|
||||
class TestCheckRoomMapCompletenessDelta:
|
||||
"""Tests für die Delta-Variante von check_room_map_completeness."""
|
||||
|
||||
def setup_method(self):
|
||||
"""Erstelle temporäre room-map.json für Tests."""
|
||||
self.tmpdir = tempfile.TemporaryDirectory()
|
||||
self.map_path = Path(self.tmpdir.name) / "room-map.json"
|
||||
|
||||
self.test_data = {
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"existing_room_1": {
|
||||
"name": "#ExistingRoom",
|
||||
"theme": "Bestehender Raum",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": str(Path(self.tmpdir.name) / "docs"),
|
||||
}
|
||||
with open(self.map_path, "w") as f:
|
||||
json.dump(self.test_data, f)
|
||||
|
||||
# Patche ROOM_MAP_PATH
|
||||
self._path_patcher = patch(
|
||||
"archivar.adapter_integration.ROOM_MAP_PATH", str(self.map_path)
|
||||
)
|
||||
self._path_patcher.start()
|
||||
self._default_path_patcher = patch(
|
||||
"archivar.room_map.DEFAULT_MAP_PATH", str(self.map_path)
|
||||
)
|
||||
self._default_path_patcher.start()
|
||||
|
||||
def teardown_method(self):
|
||||
self._default_path_patcher.stop()
|
||||
self._path_patcher.stop()
|
||||
self.tmpdir.cleanup()
|
||||
|
||||
def test_delta_returns_missing_for_new_room(self):
|
||||
"""RED: Neuer Raum, der nicht in der Map ist → wird als missing gemeldet."""
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
result = handler.check_room_map_completeness_delta(
|
||||
room_id="new_room_123",
|
||||
room_name="#NeuerRaum",
|
||||
room_type="c",
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert result["room_id"] == "new_room_123"
|
||||
assert result["name"] == "#NeuerRaum"
|
||||
|
||||
def test_delta_returns_none_for_existing_room(self):
|
||||
"""RED: Raum, der bereits in der Map ist → None (kein Onboarding nötig)."""
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
result = handler.check_room_map_completeness_delta(
|
||||
room_id="existing_room_1",
|
||||
room_name="#ExistingRoom",
|
||||
room_type="c",
|
||||
)
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_delta_ignores_dm_rooms(self):
|
||||
"""RED: DM-Räume werden ignoriert → None."""
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
result = handler.check_room_map_completeness_delta(
|
||||
room_id="dm_room_123",
|
||||
room_name="DM mit Bernd",
|
||||
room_type="d",
|
||||
)
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_delta_handles_single_room_auto_catch_all(self):
|
||||
"""RED: Wenn nur 1 relevanter Raum → auto catch_all, kein missing."""
|
||||
# Leere Map (nur Catch-All)
|
||||
empty_data = {
|
||||
"version": 2,
|
||||
"rooms": {},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": str(Path(self.tmpdir.name) / "docs"),
|
||||
}
|
||||
with open(self.map_path, "w") as f:
|
||||
json.dump(empty_data, f)
|
||||
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(empty_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
result = handler.check_room_map_completeness_delta(
|
||||
room_id="only_room",
|
||||
room_name="#OnlyRoom",
|
||||
room_type="c",
|
||||
)
|
||||
|
||||
# Single-Room-Regel: auto catch_all → kein Onboarding nötig
|
||||
assert result is None
|
||||
# Der Raum sollte jetzt in der Map sein
|
||||
assert "only_room" in handler._room_map.rooms
|
||||
assert handler._room_map.rooms["only_room"].catch_all is True
|
||||
|
||||
def test_delta_handles_excluded_rooms(self):
|
||||
"""RED: Excluded rooms werden ignoriert."""
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
# Simuliere excluded room
|
||||
handler._room_map._excluded_room_ids.add("excluded_room")
|
||||
|
||||
result = handler.check_room_map_completeness_delta(
|
||||
room_id="excluded_room",
|
||||
room_name="#Excluded",
|
||||
room_type="c",
|
||||
)
|
||||
|
||||
assert result is None
|
||||
@@ -0,0 +1,131 @@
|
||||
"""
|
||||
Tests für DDP-Event-Verdrahtung: roomMemberAdded / rooms-changed (A1b).
|
||||
|
||||
Der DDPClient wird erweitert, um stream-notify-room Events zu subscriben.
|
||||
Der Adapter reagiert auf rooms-changed Events und triggert Onboarding
|
||||
für neue Räume via check_room_map_completeness_delta().
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock, patch, PropertyMock
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||
|
||||
|
||||
class TestDDPRoomEvents:
|
||||
"""Tests für DDP-Event-Subscription und -Parsing."""
|
||||
|
||||
def test_ddp_subscribe_room_events_sends_correct_message(self):
|
||||
"""RED: subscribe_room_events sendet stream-notify-room sub."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = True
|
||||
client.sock = MagicMock()
|
||||
|
||||
with patch.object(client, "_send_json") as mock_send:
|
||||
sub_id = client.subscribe_room_events()
|
||||
|
||||
assert sub_id is not None
|
||||
mock_send.assert_called_once()
|
||||
call_args = mock_send.call_args[0][0]
|
||||
assert call_args["msg"] == "sub"
|
||||
assert call_args["name"] == "stream-notify-room"
|
||||
# params: [room_id, event_name, token]
|
||||
assert len(call_args["params"]) >= 2
|
||||
assert call_args["params"][1] == "rooms-changed"
|
||||
|
||||
def test_ddp_subscribe_room_events_returns_none_when_disconnected(self):
|
||||
"""RED: subscribe_room_events gibt None zurück wenn nicht connected."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = False
|
||||
|
||||
sub_id = client.subscribe_room_events()
|
||||
assert sub_id is None
|
||||
|
||||
def test_ddp_parse_rooms_changed_event(self):
|
||||
"""RED: rooms-changed Event wird korrekt aus DDP-Message geparst."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = True
|
||||
|
||||
# Simuliere eine rooms-changed DDP-Message
|
||||
event_data = {
|
||||
"msg": "changed",
|
||||
"collection": "stream-notify-room",
|
||||
"fields": {
|
||||
"eventName": "rooms-changed",
|
||||
"args": [
|
||||
"room_123", # room_id
|
||||
{
|
||||
"type": "c",
|
||||
"name": "#NeuerRaum",
|
||||
"u": {"username": "hermes-bot", "_id": "bot_user_id"},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
# Simuliere _on_room_event callback
|
||||
received_events = []
|
||||
client._on_room_event = lambda event: received_events.append(event)
|
||||
|
||||
# Rufe _handle_ddp_message manuell auf (simuliert _reader_loop)
|
||||
client._handle_ddp_message(event_data)
|
||||
|
||||
assert len(received_events) == 1
|
||||
event = received_events[0]
|
||||
assert event["room_id"] == "room_123"
|
||||
assert event["name"] == "#NeuerRaum"
|
||||
assert event["type"] == "c"
|
||||
|
||||
def test_ddp_parse_rooms_changed_without_callback_is_noop(self):
|
||||
"""RED: Ohne _on_room_event Callback passiert nichts (kein Crash)."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = True
|
||||
client._on_room_event = None
|
||||
|
||||
event_data = {
|
||||
"msg": "changed",
|
||||
"collection": "stream-notify-room",
|
||||
"fields": {
|
||||
"eventName": "rooms-changed",
|
||||
"args": ["room_123", {"type": "c", "name": "#Test"}],
|
||||
},
|
||||
}
|
||||
|
||||
# Sollte keinen Fehler werfen
|
||||
client._handle_ddp_message(event_data)
|
||||
|
||||
def test_ddp_ignores_non_rooms_changed_events(self):
|
||||
"""RED: Andere stream-notify-room Events werden ignoriert."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = True
|
||||
received_events = []
|
||||
client._on_room_event = lambda event: received_events.append(event)
|
||||
|
||||
# Ein delete-Message Event (anderer Typ)
|
||||
event_data = {
|
||||
"msg": "changed",
|
||||
"collection": "stream-notify-room",
|
||||
"fields": {
|
||||
"eventName": "deleteMessage",
|
||||
"args": [{"_id": "msg_123"}],
|
||||
},
|
||||
}
|
||||
|
||||
client._handle_ddp_message(event_data)
|
||||
assert len(received_events) == 0
|
||||
@@ -0,0 +1,149 @@
|
||||
"""
|
||||
Tests für Lazy-Onboarding im Message-Handler (A1b).
|
||||
|
||||
Fallback-Pfad: Wenn eine Nachricht aus einem unbekannten Raum empfangen wird
|
||||
(der nicht in room-map.json steht), wird das Onboarding-Interview getriggert.
|
||||
Dies fängt Fälle ab, wo das DDP-Event nicht angekommen ist (Reconnect, Subscription-Lag).
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
from archivar.room_map import RoomMap, RoomEntry
|
||||
|
||||
|
||||
class TestLazyOnboarding:
|
||||
"""Tests für den Lazy-Onboarding-Fallback-Pfad."""
|
||||
|
||||
def setup_method(self):
|
||||
self.tmpdir = tempfile.TemporaryDirectory()
|
||||
self.map_path = Path(self.tmpdir.name) / "room-map.json"
|
||||
self.test_data = {
|
||||
"version": 2,
|
||||
"rooms": {
|
||||
"known_room": {
|
||||
"name": "#KnownRoom",
|
||||
"theme": "Bekannter Raum",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": str(Path(self.tmpdir.name) / "docs"),
|
||||
}
|
||||
with open(self.map_path, "w") as f:
|
||||
json.dump(self.test_data, f)
|
||||
|
||||
self._path_patcher = patch(
|
||||
"archivar.adapter_integration.ROOM_MAP_PATH", str(self.map_path)
|
||||
)
|
||||
self._path_patcher.start()
|
||||
self._default_path_patcher = patch(
|
||||
"archivar.room_map.DEFAULT_MAP_PATH", str(self.map_path)
|
||||
)
|
||||
self._default_path_patcher.start()
|
||||
|
||||
def teardown_method(self):
|
||||
self._default_path_patcher.stop()
|
||||
self._path_patcher.stop()
|
||||
self.tmpdir.cleanup()
|
||||
|
||||
def test_lazy_check_returns_missing_for_unknown_room(self):
|
||||
"""RED: Unbekannter Raum → Lazy-Check meldet missing."""
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
result = handler.lazy_onboarding_check(
|
||||
room_id="unknown_room_123",
|
||||
room_name="#UnbekannterRaum",
|
||||
room_type="c",
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert result["room_id"] == "unknown_room_123"
|
||||
assert result["name"] == "#UnbekannterRaum"
|
||||
|
||||
def test_lazy_check_returns_none_for_known_room(self):
|
||||
"""RED: Bekannter Raum → Lazy-Check gibt None zurück."""
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
result = handler.lazy_onboarding_check(
|
||||
room_id="known_room",
|
||||
room_name="#KnownRoom",
|
||||
room_type="c",
|
||||
)
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_lazy_check_ignores_dm_rooms(self):
|
||||
"""RED: DM-Räume werden im Lazy-Check ignoriert."""
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
result = handler.lazy_onboarding_check(
|
||||
room_id="dm_room",
|
||||
room_name="DM mit Bernd",
|
||||
room_type="d",
|
||||
)
|
||||
|
||||
assert result is None
|
||||
|
||||
def test_lazy_check_respects_onboarding_active(self):
|
||||
"""RED: Wenn Onboarding bereits aktiv, kein Lazy-Trigger."""
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
handler._stats["onboarding_active"] = True
|
||||
|
||||
result = handler.lazy_onboarding_check(
|
||||
room_id="unknown_room",
|
||||
room_name="#Unbekannt",
|
||||
room_type="c",
|
||||
)
|
||||
|
||||
# Sollte None sein, weil Onboarding bereits läuft
|
||||
assert result is None
|
||||
|
||||
def test_lazy_check_uses_lock_to_prevent_duplicates(self):
|
||||
"""RED: Lock verhindert doppeltes Lazy-Onboarding für denselben Raum."""
|
||||
from archivar.onboarding import acquire_onboarding_lock, release_onboarding_lock
|
||||
|
||||
handler = ArchivarMessageHandler()
|
||||
with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)):
|
||||
handler._room_map = handler._load_room_map()
|
||||
|
||||
room_id = "new_room_lazy"
|
||||
|
||||
# Erster Check: sollte missing melden
|
||||
result1 = handler.lazy_onboarding_check(
|
||||
room_id=room_id,
|
||||
room_name="#NeuerRaum",
|
||||
room_type="c",
|
||||
)
|
||||
assert result1 is not None
|
||||
|
||||
# Lock setzen (simuliert laufendes Onboarding)
|
||||
assert acquire_onboarding_lock(room_id) is True
|
||||
|
||||
# Zweiter Check: sollte None sein wegen Lock
|
||||
result2 = handler.lazy_onboarding_check(
|
||||
room_id=room_id,
|
||||
room_name="#NeuerRaum",
|
||||
room_type="c",
|
||||
)
|
||||
assert result2 is None
|
||||
|
||||
release_onboarding_lock(room_id)
|
||||
@@ -0,0 +1,124 @@
|
||||
"""
|
||||
Tests für Begrüßungsnachricht + 30s Delay vor Onboarding-Interview (A1b).
|
||||
|
||||
- Bot postet kurze Begrüßung: 'Hi, ich bin neu hier — lass uns kurz klären, wie ich euch am besten helfe'
|
||||
- Dann 30 Sekunden warten (ob noch andere User dazukommen — Spam-Vermeidung bei Multi-User-Join)
|
||||
- Dann Interview starten
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||
|
||||
from archivar.onboarding import (
|
||||
build_greeting_message,
|
||||
GREETING_TEXT,
|
||||
GREETING_DELAY_SECONDS,
|
||||
)
|
||||
|
||||
|
||||
class TestOnboardingGreeting:
|
||||
"""Tests für Begrüßungsnachricht und Delay."""
|
||||
|
||||
def test_greeting_text_is_correct(self):
|
||||
"""Begrüßungstext ist der von Andreas bestätigte Text."""
|
||||
assert GREETING_TEXT == (
|
||||
"Hi, ich bin neu hier — lass uns kurz klären, "
|
||||
"wie ich euch am besten helfe"
|
||||
)
|
||||
|
||||
def test_greeting_delay_is_30_seconds(self):
|
||||
"""Delay ist exakt 30 Sekunden (Andreas bestätigt)."""
|
||||
assert GREETING_DELAY_SECONDS == 30
|
||||
|
||||
def test_build_greeting_message_returns_string(self):
|
||||
"""build_greeting_message gibt einen String zurück."""
|
||||
result = build_greeting_message()
|
||||
assert isinstance(result, str)
|
||||
assert len(result) > 0
|
||||
|
||||
def test_build_greeting_message_contains_greeting(self):
|
||||
"""build_greeting_message enthält den Begrüßungstext."""
|
||||
result = build_greeting_message()
|
||||
assert GREETING_TEXT in result
|
||||
|
||||
def test_build_greeting_message_with_room_name(self):
|
||||
"""build_greeting_message mit room_name enthält den Raumnamen."""
|
||||
result = build_greeting_message(room_name="#Testraum")
|
||||
assert "#Testraum" in result
|
||||
|
||||
def test_build_greeting_message_without_room_name(self):
|
||||
"""build_greeting_message ohne room_name funktioniert trotzdem."""
|
||||
result = build_greeting_message()
|
||||
assert isinstance(result, str)
|
||||
assert len(result) > 0
|
||||
|
||||
|
||||
class TestOnboardingGreetingFlow:
|
||||
"""Tests für den Begrüßungs-Flow mit Delay (sync via asyncio.run)."""
|
||||
|
||||
def test_greeting_flow_posts_greeting_then_waits(self):
|
||||
"""Der Flow postet Begrüßung, wartet 30s, startet dann Interview."""
|
||||
from archivar.onboarding import run_onboarding_greeting_flow
|
||||
|
||||
send_cb = AsyncMock(return_value=True)
|
||||
interview_cb = AsyncMock()
|
||||
|
||||
with patch("asyncio.sleep", new=AsyncMock()) as mock_sleep:
|
||||
asyncio.run(run_onboarding_greeting_flow(
|
||||
room_id="test_room",
|
||||
send_callback=send_cb,
|
||||
start_interview_callback=interview_cb,
|
||||
))
|
||||
|
||||
# Begrüßung wurde gesendet
|
||||
send_cb.assert_called_once()
|
||||
call_args = send_cb.call_args[0]
|
||||
assert call_args[0] == "test_room" # room_id
|
||||
assert GREETING_TEXT in call_args[1] # text
|
||||
|
||||
# 30s Delay wurde eingehalten
|
||||
mock_sleep.assert_called_once_with(GREETING_DELAY_SECONDS)
|
||||
|
||||
# Interview-Callback wurde aufgerufen
|
||||
interview_cb.assert_called_once()
|
||||
|
||||
def test_greeting_flow_handles_send_failure(self):
|
||||
"""Auch wenn send fehlschlägt, wird das Interview gestartet."""
|
||||
from archivar.onboarding import run_onboarding_greeting_flow
|
||||
|
||||
send_cb = AsyncMock(return_value=False) # Send fehlgeschlagen
|
||||
interview_cb = AsyncMock()
|
||||
|
||||
with patch("asyncio.sleep", new=AsyncMock()):
|
||||
asyncio.run(run_onboarding_greeting_flow(
|
||||
room_id="test_room",
|
||||
send_callback=send_cb,
|
||||
start_interview_callback=interview_cb,
|
||||
))
|
||||
|
||||
# Interview wurde trotzdem gestartet
|
||||
interview_cb.assert_called_once()
|
||||
|
||||
def test_greeting_flow_with_room_name(self):
|
||||
"""room_name wird in der Begrüßung verwendet."""
|
||||
from archivar.onboarding import run_onboarding_greeting_flow
|
||||
|
||||
send_cb = AsyncMock(return_value=True)
|
||||
interview_cb = AsyncMock()
|
||||
|
||||
with patch("asyncio.sleep", new=AsyncMock()):
|
||||
asyncio.run(run_onboarding_greeting_flow(
|
||||
room_id="test_room",
|
||||
send_callback=send_cb,
|
||||
start_interview_callback=interview_cb,
|
||||
room_name="#MeinProjekt",
|
||||
))
|
||||
|
||||
call_text = send_cb.call_args[0][1]
|
||||
assert "#MeinProjekt" in call_text
|
||||
@@ -0,0 +1,141 @@
|
||||
"""
|
||||
Tests für den Onboarding-Lock-Mechanismus (A1b).
|
||||
|
||||
Lock-File pro Raum (onboarding-{room_id}.lock) verhindert parallele Interviews.
|
||||
Stale-Lock-Cleanup beim Start: 10 Minuten Timeout.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
# Füge das plugin-Verzeichnis zum Python-Pfad hinzu
|
||||
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
|
||||
|
||||
from archivar.onboarding import (
|
||||
acquire_onboarding_lock,
|
||||
release_onboarding_lock,
|
||||
cleanup_stale_locks,
|
||||
is_onboarding_locked,
|
||||
LOCK_DIR,
|
||||
STALE_LOCK_TIMEOUT_SECONDS,
|
||||
)
|
||||
|
||||
|
||||
class TestOnboardingLock:
|
||||
"""Tests für acquire/release/cleanup des Onboarding-Locks."""
|
||||
|
||||
def setup_method(self):
|
||||
"""Erstelle ein temporäres Lock-Verzeichnis für jeden Test."""
|
||||
self.tmpdir = tempfile.TemporaryDirectory()
|
||||
self.lock_dir = Path(self.tmpdir.name) / "locks"
|
||||
self.lock_dir.mkdir(parents=True, exist_ok=True)
|
||||
# Patch LOCK_DIR auf das temporäre Verzeichnis
|
||||
self._orig_lock_dir = LOCK_DIR
|
||||
# Monkey-patch das Modul
|
||||
import archivar.onboarding as ob_mod
|
||||
ob_mod.LOCK_DIR = self.lock_dir
|
||||
|
||||
def teardown_method(self):
|
||||
"""Räume auf."""
|
||||
import archivar.onboarding as ob_mod
|
||||
ob_mod.LOCK_DIR = self._orig_lock_dir
|
||||
self.tmpdir.cleanup()
|
||||
|
||||
def test_acquire_lock_creates_file(self):
|
||||
"""RED: Lock-Datei wird erstellt, wenn noch kein Lock existiert."""
|
||||
room_id = "test_room_123"
|
||||
result = acquire_onboarding_lock(room_id)
|
||||
assert result is True
|
||||
lock_file = self.lock_dir / f"onboarding-{room_id}.lock"
|
||||
assert lock_file.exists()
|
||||
|
||||
def test_acquire_lock_returns_false_when_locked(self):
|
||||
"""RED: Zweiter acquire-Versuch auf gleichen Raum schlägt fehl."""
|
||||
room_id = "test_room_456"
|
||||
assert acquire_onboarding_lock(room_id) is True
|
||||
# Zweiter Versuch muss False zurückgeben
|
||||
assert acquire_onboarding_lock(room_id) is False
|
||||
|
||||
def test_release_lock_deletes_file(self):
|
||||
"""RED: release löscht die Lock-Datei."""
|
||||
room_id = "test_room_789"
|
||||
assert acquire_onboarding_lock(room_id) is True
|
||||
lock_file = self.lock_dir / f"onboarding-{room_id}.lock"
|
||||
assert lock_file.exists()
|
||||
release_onboarding_lock(room_id)
|
||||
assert not lock_file.exists()
|
||||
|
||||
def test_release_nonexistent_lock_is_noop(self):
|
||||
"""RED: release auf nicht-existierenden Lock ist no-op (kein Fehler)."""
|
||||
room_id = "nonexistent_room"
|
||||
# Sollte keinen Fehler werfen
|
||||
release_onboarding_lock(room_id)
|
||||
|
||||
def test_is_onboarding_locked_returns_correct_state(self):
|
||||
"""RED: is_onboarding_locked prüft korrekt."""
|
||||
room_id = "test_room_check"
|
||||
assert is_onboarding_locked(room_id) is False
|
||||
acquire_onboarding_lock(room_id)
|
||||
assert is_onboarding_locked(room_id) is True
|
||||
release_onboarding_lock(room_id)
|
||||
assert is_onboarding_locked(room_id) is False
|
||||
|
||||
def test_cleanup_stale_locks_removes_old_locks(self):
|
||||
"""RED: Stale-Lock-Cleanup entfernt Locks älter als 10 Minuten."""
|
||||
room_id = "stale_room"
|
||||
lock_file = self.lock_dir / f"onboarding-{room_id}.lock"
|
||||
lock_file.write_text(str(time.time()))
|
||||
# Setze mtime auf 11 Minuten in der Vergangenheit
|
||||
stale_time = time.time() - (STALE_LOCK_TIMEOUT_SECONDS + 60)
|
||||
os.utime(str(lock_file), (stale_time, stale_time))
|
||||
assert lock_file.exists()
|
||||
removed = cleanup_stale_locks()
|
||||
assert removed >= 1
|
||||
assert not lock_file.exists()
|
||||
|
||||
def test_cleanup_stale_locks_keeps_fresh_locks(self):
|
||||
"""RED: Frische Locks (< 10 Min) werden nicht entfernt."""
|
||||
room_id = "fresh_room"
|
||||
lock_file = self.lock_dir / f"onboarding-{room_id}.lock"
|
||||
lock_file.write_text(str(time.time()))
|
||||
# mtime ist jetzt (frisch)
|
||||
assert lock_file.exists()
|
||||
removed = cleanup_stale_locks()
|
||||
# Der frische Lock sollte nicht entfernt werden
|
||||
assert lock_file.exists()
|
||||
|
||||
def test_cleanup_stale_locks_handles_empty_dir(self):
|
||||
"""RED: Cleanup auf leerem Verzeichnis ist no-op."""
|
||||
removed = cleanup_stale_locks()
|
||||
assert removed == 0
|
||||
|
||||
def test_acquire_lock_different_rooms_independent(self):
|
||||
"""RED: Locks für verschiedene Räume sind unabhängig."""
|
||||
room_a = "room_a"
|
||||
room_b = "room_b"
|
||||
assert acquire_onboarding_lock(room_a) is True
|
||||
assert acquire_onboarding_lock(room_b) is True
|
||||
# Beide Lock-Dateien existieren
|
||||
assert (self.lock_dir / f"onboarding-{room_a}.lock").exists()
|
||||
assert (self.lock_dir / f"onboarding-{room_b}.lock").exists()
|
||||
# Release room_a, room_b bleibt gelockt
|
||||
release_onboarding_lock(room_a)
|
||||
assert is_onboarding_locked(room_a) is False
|
||||
assert is_onboarding_locked(room_b) is True
|
||||
|
||||
def test_lock_file_contains_timestamp(self):
|
||||
"""RED: Lock-Datei enthält einen Unix-Timestamp."""
|
||||
room_id = "ts_room"
|
||||
acquire_onboarding_lock(room_id)
|
||||
lock_file = self.lock_dir / f"onboarding-{room_id}.lock"
|
||||
content = lock_file.read_text().strip()
|
||||
# Sollte ein float/int sein
|
||||
ts = float(content)
|
||||
assert ts > 0
|
||||
# Sollte ungefähr jetzt sein (±5 Sekunden)
|
||||
assert abs(ts - time.time()) < 5.0
|
||||
Reference in New Issue
Block a user