Compare commits
3 Commits
463e29d594
...
4ad3facfae
| Author | SHA1 | Date | |
|---|---|---|---|
| 4ad3facfae | |||
| b1a2500d55 | |||
| f10973810a |
+464
-12
@@ -271,10 +271,11 @@ class DDPClient:
|
||||
PING_INTERVAL = 8.0
|
||||
|
||||
|
||||
def __init__(self, host: str, on_message_cb=None, on_connected_cb=None):
|
||||
def __init__(self, host: str, on_message_cb=None, on_connected_cb=None, on_room_event_cb=None):
|
||||
self.host = host
|
||||
self._on_message = on_message_cb
|
||||
self._on_connected = on_connected_cb
|
||||
self._on_room_event = on_room_event_cb # A1b: DDP room events callback
|
||||
self.sock: Optional[socket.socket] = None
|
||||
self.connected = False
|
||||
self._running = False
|
||||
@@ -397,6 +398,9 @@ class DDPClient:
|
||||
args = fields.get("args", [])
|
||||
if args and isinstance(args, list) and len(args) >= 1:
|
||||
self._msg_queue.put(args[0])
|
||||
# A1b: stream-notify-room events (rooms-changed, roomMemberAdded)
|
||||
elif msg_type in ("changed", "added") and data.get("collection") == "stream-notify-room":
|
||||
self._handle_ddp_message(data)
|
||||
except Exception:
|
||||
pass
|
||||
elif opcode == 0x08:
|
||||
@@ -476,6 +480,64 @@ class DDPClient:
|
||||
pass
|
||||
return True
|
||||
|
||||
def subscribe_room_events(self) -> Optional[str]:
|
||||
"""A1b: Subscribe to stream-notify-room for rooms-changed events.
|
||||
|
||||
Rocket.Chat sendet rooms-changed Events wenn der Bot einem
|
||||
neuen Raum hinzugefügt wird (roomMemberAdded) oder sich die
|
||||
Raumliste ändert.
|
||||
|
||||
Returns:
|
||||
Subscription-ID oder None wenn nicht connected.
|
||||
"""
|
||||
if not self.connected:
|
||||
return None
|
||||
sub_id = f"sub{self._next_sub_id}"
|
||||
self._next_sub_id += 1
|
||||
# Rocket.Chat stream-notify-room: erster Param = user-id/event-name
|
||||
# __my_messages__ ist der Fallback, der für den aktuellen User funktioniert
|
||||
self._send_json({
|
||||
"msg": "sub",
|
||||
"name": "stream-notify-room",
|
||||
"params": ["__my_messages__/rooms-changed", "rooms-changed", False],
|
||||
"id": sub_id,
|
||||
})
|
||||
logger.debug("DDP: Subscribed to stream-notify-room (rooms-changed) — sub_id=%s", sub_id)
|
||||
return sub_id
|
||||
|
||||
def _handle_ddp_message(self, data: dict) -> None:
|
||||
"""A1b: Parse stream-notify-room events and dispatch to callback.
|
||||
|
||||
Extrahiert rooms-changed Events und ruft _on_room_event auf.
|
||||
|
||||
Args:
|
||||
data: Die geparste DDP-JSON-Message.
|
||||
"""
|
||||
if self._on_room_event is None:
|
||||
return
|
||||
|
||||
fields = data.get("fields", {})
|
||||
event_name = fields.get("eventName", "")
|
||||
|
||||
if event_name != "rooms-changed":
|
||||
return
|
||||
|
||||
args = fields.get("args", [])
|
||||
if not args or not isinstance(args, list) or len(args) < 2:
|
||||
return
|
||||
|
||||
room_id = args[0]
|
||||
room_data = args[1] if isinstance(args[1], dict) else {}
|
||||
|
||||
event = {
|
||||
"room_id": room_id,
|
||||
"name": room_data.get("name", ""),
|
||||
"type": room_data.get("type", "c"),
|
||||
}
|
||||
logger.debug("DDP: rooms-changed event — room=%s, name=%s, type=%s",
|
||||
room_id[:12], event["name"], event["type"])
|
||||
self._on_room_event(event)
|
||||
|
||||
def set_status(self, status: str) -> bool:
|
||||
if not self.connected:
|
||||
return False
|
||||
@@ -758,6 +820,60 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
)
|
||||
return "\n".join(lines)
|
||||
|
||||
def _on_ddp_room_event(self, event: dict) -> None:
|
||||
"""A1b: Callback für DDP rooms-changed Events.
|
||||
|
||||
Wird vom DDPClient._handle_ddp_message aufgerufen wenn ein
|
||||
rooms-changed Event empfangen wird. Prüft ob der Raum neu ist
|
||||
und startet ggf. das Onboarding-Interview.
|
||||
|
||||
Args:
|
||||
event: Dict mit {"room_id": str, "name": str, "type": str}.
|
||||
"""
|
||||
room_id = event.get("room_id", "")
|
||||
room_name = event.get("name", "")
|
||||
room_type = event.get("type", "c")
|
||||
|
||||
if not room_id:
|
||||
return
|
||||
|
||||
# Nur im Multiroom-Modus mit aktivem Archivar
|
||||
if not _MULTIROOM() or self.archivar is None:
|
||||
return
|
||||
|
||||
# Prüfe ob Onboarding bereits aktiv ist
|
||||
if self.archivar._stats.get("onboarding_active", False):
|
||||
logger.debug("[rocketchat] A1b: Onboarding bereits aktiv — DDP-Event ignoriert: room=%s", room_id[:12])
|
||||
return
|
||||
|
||||
# P1-3: Lock prüfen — symmetrisch zu lazy_onboarding_check
|
||||
# Verhindert doppelte Interviews für denselben Raum
|
||||
from archivar.onboarding import is_onboarding_locked
|
||||
if is_onboarding_locked(room_id):
|
||||
logger.debug("[rocketchat] A1b: Onboarding-Lock aktiv — DDP-Event ignoriert: room=%s", room_id[:12])
|
||||
return
|
||||
|
||||
# Prüfe ob der Raum in der Map fehlt (Delta-Check)
|
||||
missing = self.archivar.check_room_map_completeness_delta(
|
||||
room_id=room_id,
|
||||
room_name=room_name,
|
||||
room_type=room_type,
|
||||
)
|
||||
|
||||
if missing is None:
|
||||
logger.debug("[rocketchat] A1b: Raum bereits in Map oder ignoriert: room=%s", room_id[:12])
|
||||
return
|
||||
|
||||
# Telemetrie: DDP-Event-Pfad
|
||||
logger.info(
|
||||
"[rocketchat] A1b: DDP-Event-Pfad — neuer Raum entdeckt: "
|
||||
"room=%s, name=%s, type=%s",
|
||||
room_id[:12], room_name, room_type,
|
||||
)
|
||||
|
||||
# Onboarding für diesen Raum starten (asynchron, nicht blockierend)
|
||||
asyncio.ensure_future(self._start_onboarding([missing]))
|
||||
|
||||
async def _post_message_with_retry(
|
||||
self, room_id: str, text: str,
|
||||
attachments: Optional[List[dict]] = None,
|
||||
@@ -1050,10 +1166,20 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
return False
|
||||
self._auth_token = self.rest.auth_token
|
||||
self._user_id = self.rest.user_id
|
||||
|
||||
# A1b: Stale-Lock-Cleanup beim Gateway-Start
|
||||
# Entfernt Onboarding-Locks die älter als 10 Minuten sind
|
||||
# (abgestürztes Onboarding-Interview soll nicht dauerhaft blockieren)
|
||||
from archivar.onboarding import cleanup_stale_locks
|
||||
removed = cleanup_stale_locks()
|
||||
if removed > 0:
|
||||
logger.info("[rocketchat] A1b: Stale-Lock-Cleanup — %d Locks entfernt", removed)
|
||||
|
||||
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
||||
self.ddp = DDPClient(
|
||||
host=host,
|
||||
on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None,
|
||||
on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events
|
||||
)
|
||||
if not self.ddp.connect_and_login(self._auth_token):
|
||||
logger.error("[rocketchat] DDP connect/login failed")
|
||||
@@ -1061,6 +1187,14 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._rooms = self.rest.get_rooms()
|
||||
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
|
||||
|
||||
# A1b: Subscribe to stream-notify-room for rooms-changed events
|
||||
if self.ddp.connected:
|
||||
room_events_sub = self.ddp.subscribe_room_events()
|
||||
if room_events_sub:
|
||||
logger.info("[rocketchat] A1b: Subscribed to stream-notify-room (rooms-changed) — sub_id=%s", room_events_sub)
|
||||
else:
|
||||
logger.warning("[rocketchat] A1b: Failed to subscribe to stream-notify-room")
|
||||
|
||||
# ── M13: Room-Map Garbage Collection ───────────────────────────
|
||||
# Läuft VOR Subscription und VOR Archivar-Init (B9).
|
||||
# Entfernt Räume aus room-map.json, in denen der Agent nicht mehr
|
||||
@@ -1219,6 +1353,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.error("[rocketchat] _reconnect_ddp: Kein auth token")
|
||||
return False
|
||||
|
||||
# A1b: Stale-Lock-Cleanup bei Reconnect (F6 Re-Review Fix 1)
|
||||
# Ohne Gateway-Restart müssen stale Locks auch bereinigt werden.
|
||||
from archivar.onboarding import cleanup_stale_locks
|
||||
removed = cleanup_stale_locks()
|
||||
if removed > 0:
|
||||
logger.info("[rocketchat] A1b: Stale-Lock-Cleanup bei Reconnect — %d Locks entfernt", removed)
|
||||
|
||||
# 1. Alte DDP-Verbindung trennen
|
||||
if self.ddp:
|
||||
self.ddp.disconnect()
|
||||
@@ -1229,11 +1370,20 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self.ddp = DDPClient(
|
||||
host=host,
|
||||
on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None,
|
||||
on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events (P0-3)
|
||||
)
|
||||
if not self.ddp.connect_and_login(self._auth_token):
|
||||
logger.error("[rocketchat] _reconnect_ddp: DDP connect/login failed")
|
||||
return False
|
||||
|
||||
# A1b: Re-subscribe to stream-notify-room for rooms-changed events (P0-3)
|
||||
if self.ddp.connected:
|
||||
room_events_sub = self.ddp.subscribe_room_events()
|
||||
if room_events_sub:
|
||||
logger.info("[rocketchat] _reconnect_ddp: A1b re-subscribed to stream-notify-room — sub_id=%s", room_events_sub)
|
||||
else:
|
||||
logger.warning("[rocketchat] _reconnect_ddp: A1b failed to re-subscribe to stream-notify-room")
|
||||
|
||||
# 3. Aktuelle Mitgliedschaft via REST
|
||||
self._rooms = self.rest.get_rooms()
|
||||
logger.info("[rocketchat] _reconnect_ddp: REST get_rooms returned %d rooms", len(self._rooms))
|
||||
@@ -1400,6 +1550,37 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im Projektraum).
|
||||
_THEMATIC_TARGET_ROOM.set("")
|
||||
|
||||
# ── A1b: Lazy-Onboarding-Check (Fallback-Pfad) ────────────────────
|
||||
# Wenn eine Nachricht aus einem Raum kommt, der nicht in room-map.json
|
||||
# steht, und kein Onboarding aktiv ist → Onboarding triggern.
|
||||
# Dies fängt Fälle ab, wo das DDP-Event nicht angekommen ist.
|
||||
# P0-4: room_type kann "unknown" sein wenn der Raum nicht in _room_info
|
||||
# ist (z.B. nach Reconnect). Der lazy_onboarding_check filtert selbst
|
||||
# DM-Räume und excluded rooms — wir müssen hier nur DM ausschließen.
|
||||
if (
|
||||
_MULTIROOM()
|
||||
and self.archivar is not None
|
||||
and not self.archivar._stats.get("onboarding_active", False)
|
||||
and room_type != "d" # P0-4: Nur DM ausschließen, "unknown" durchlassen
|
||||
):
|
||||
lazy_result = self.archivar.lazy_onboarding_check(
|
||||
room_id=room_id,
|
||||
room_name=room_name,
|
||||
room_type=room_type,
|
||||
)
|
||||
if lazy_result is not None:
|
||||
logger.info(
|
||||
"[rocketchat] A1b: Lazy-Onboarding getriggert — "
|
||||
"unbekannter Raum: room=%s, name=%s",
|
||||
room_id[:12], room_name,
|
||||
)
|
||||
await self._start_onboarding([lazy_result])
|
||||
# Nachricht nicht weiter verarbeiten — Onboarding läuft jetzt
|
||||
routing_counter.increment('lazy_onboarding_triggered')
|
||||
logger.info("ROUTING BYPASS: reason=lazy_onboarding_triggered, origin_room=%s", room_id)
|
||||
return
|
||||
# ── Ende A1b Lazy-Onboarding ─────────────────────────────────────
|
||||
|
||||
# ── CLARIFY Response Handling ───────────────────────────────────
|
||||
# Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other
|
||||
# V8.2.1 A2: Handle ARCHIVAR_CLARIFY (Nachklärung) responses
|
||||
@@ -1519,6 +1700,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
or (is_operator_room and self._onboarding_state.get("current_room_index", -1) >= 0) # v2 Interview läuft
|
||||
or (is_operator_room and self._onboarding_state.get("phase") == "butler_mode") # Fix C v7: Butler-Mode Phase
|
||||
or (is_operator_room and self._onboarding_state.get("phase") == "catch_all_change") # Catch-All Phase
|
||||
or (is_operator_room and self._onboarding_state.get("phase") == "fakt_store") # Thema 3: FAKT-Speicherort Phase
|
||||
or (is_operator_room and "=" in stripped) # v1 Legacy: Name = Thema
|
||||
or (is_operator_room and stripped.startswith("#")) # v1 Legacy: #Name = Thema
|
||||
or (is_operator_room and stripped.lower().startswith("raum:")) # v1 Legacy: Raum: Name = Thema
|
||||
@@ -2677,7 +2859,47 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.info("[rocketchat] Onboarding: Keine Räume zum Einrichten (alle bereits in Map)")
|
||||
return
|
||||
|
||||
# Initialisiere Onboarding-State
|
||||
# A1b: Onboarding-Lock für den ersten Raum erwerben
|
||||
# Verhindert parallele Interviews für denselben Raum
|
||||
from archivar.onboarding import acquire_onboarding_lock, release_onboarding_lock
|
||||
first_room_id = missing_rooms[0]["room_id"]
|
||||
if not acquire_onboarding_lock(first_room_id):
|
||||
logger.info(
|
||||
"[rocketchat] A1b: Onboarding-Lock bereits aktiv für room=%s — "
|
||||
"überspringe Start",
|
||||
first_room_id[:12],
|
||||
)
|
||||
return
|
||||
|
||||
# A1b: Begrüßungs-Flow vor dem Interview
|
||||
# Postet Begrüßung, wartet 30s (Spam-Vermeidung bei Multi-User-Join),
|
||||
# startet dann das Interview
|
||||
from archivar.onboarding import run_onboarding_greeting_flow
|
||||
|
||||
async def _start_interview():
|
||||
await self._send_onboarding_message(operator_room_id, missing_rooms)
|
||||
|
||||
# F6 Re-Review Fix 2: Lock-Release bei Onboarding-Abbruch
|
||||
# Wenn der Begrüßungs-Flow oder Interview-Start fehlschlägt
|
||||
# (User verlässt Raum, Timeout, Fehler), muss der Lock
|
||||
# freigegeben werden, damit ein erneuter Versuch möglich ist.
|
||||
try:
|
||||
await run_onboarding_greeting_flow(
|
||||
room_id=operator_room_id,
|
||||
send_callback=self._post_message_with_retry,
|
||||
start_interview_callback=_start_interview,
|
||||
room_name=self._room_info.get(operator_room_id, {}).get("name", ""),
|
||||
)
|
||||
except Exception:
|
||||
release_onboarding_lock(first_room_id)
|
||||
logger.warning(
|
||||
"[rocketchat] A1b: Onboarding abgebrochen — Lock freigegeben: room=%s",
|
||||
first_room_id[:12],
|
||||
)
|
||||
raise
|
||||
return
|
||||
|
||||
async def _send_onboarding_message(self, operator_room_id: str, missing_rooms: list) -> None:
|
||||
self._onboarding_state = {
|
||||
"missing_rooms": missing_rooms,
|
||||
"current_room_index": -1, # -1 = noch kein Raum ausgewählt
|
||||
@@ -2942,19 +3164,222 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
)
|
||||
logger.info("[rocketchat] Fix C v7: Butler-Mode gesetzt auf '%s' (Text)", mode)
|
||||
|
||||
# Onboarding abschließen
|
||||
# Thema 3: FAKT-Speicherort-Dialog statt direktem Abschluss
|
||||
self._onboarding_state = {
|
||||
"phase": "fakt_store",
|
||||
"operator_room_id": operator_room_id,
|
||||
}
|
||||
if self.archivar is not None:
|
||||
self.archivar._stats["onboarding_active"] = False
|
||||
self.archivar._state.clear_onboarding_state()
|
||||
self._onboarding_state = {}
|
||||
# FIX E: Raum-Map Summary nach Onboarding aktualisieren
|
||||
self._room_map_summary = self._build_room_map_summary()
|
||||
if self._room_map_summary:
|
||||
logger.info("[rocketchat] FIX E: Raum-Map Summary nach Onboarding aktualisiert (%d Räume)",
|
||||
len(self._room_map_summary.splitlines()) - 1)
|
||||
logger.info("[rocketchat] Onboarding v2 vollständig abgeschlossen (mit Butler-Mode)")
|
||||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||||
|
||||
# FAKT-Speicherort-Frage senden
|
||||
_build = self._get_build_custom_buttons()
|
||||
fakt_text = (
|
||||
"📁 **FAKT-Speicherort** — Wo soll ich Fakten (deine Notizen) ablegen?\n\n"
|
||||
"1️⃣ **Standard** — `.hermes/wissenssammlung` in deinem Home-Verzeichnis\n"
|
||||
"2️⃣ **Neuer Ort** — Du gibst einen Pfad an, ich lege das Verzeichnis an\n"
|
||||
"3️⃣ **Bestehender Ort** — Du gibst einen Pfad an, ich verweise darauf\n"
|
||||
"4️⃣ **Keine Sammlung** — FAKT-Nachrichten werden nicht persistiert\n\n"
|
||||
"👉 Klicke auf einen Button oder antworte mit 1–4:"
|
||||
)
|
||||
fakt_buttons = _build(
|
||||
["1️⃣ Standard", "2️⃣ Neuer Ort", "3️⃣ Bestehender Ort", "4️⃣ Keine Sammlung"],
|
||||
prefix="FAKT",
|
||||
style="primary",
|
||||
)
|
||||
fakt_attachments = [{
|
||||
"color": "#1d74f5",
|
||||
"title": "FAKT-Speicherort wählen",
|
||||
"actions": fakt_buttons,
|
||||
}]
|
||||
await self._post_message_with_retry(
|
||||
operator_room_id, fakt_text, attachments=fakt_attachments
|
||||
)
|
||||
logger.info("[rocketchat] Thema 3: FAKT-Speicherort-Frage gesendet")
|
||||
return
|
||||
|
||||
# ── Thema 3: FAKT-Speicherort-Dialog ─────────────────────────────
|
||||
if state.get("phase") == "fakt_store":
|
||||
single_line = text.strip()
|
||||
fakt_sub_phase = state.get("fakt_sub_phase", "")
|
||||
|
||||
# Sub-Phase: User gibt Pfad ein (für Option 2 oder 3)
|
||||
if fakt_sub_phase in ("new_path", "existing_path"):
|
||||
from plugin.archivar.onboarding import (
|
||||
validate_fact_store_path,
|
||||
create_and_verify_fact_store,
|
||||
verify_existing_fact_store,
|
||||
)
|
||||
from datetime import datetime, timezone
|
||||
|
||||
validation = validate_fact_store_path(single_line)
|
||||
if not validation["valid"]:
|
||||
await self._post_message_with_retry(
|
||||
operator_room_id,
|
||||
f"❌ {validation['error']}\n\nBitte gib einen gültigen absoluten Pfad ein:"
|
||||
)
|
||||
return
|
||||
|
||||
norm_path = validation["normalized_path"]
|
||||
|
||||
if fakt_sub_phase == "new_path":
|
||||
result = create_and_verify_fact_store(norm_path)
|
||||
else:
|
||||
result = verify_existing_fact_store(norm_path)
|
||||
|
||||
if not result["success"]:
|
||||
await self._post_message_with_retry(
|
||||
operator_room_id,
|
||||
f"❌ {result['error']}\n\nBitte versuche einen anderen Pfad:"
|
||||
)
|
||||
return
|
||||
|
||||
# Erfolg: Persistiere in room-map.json
|
||||
strategy = "manual"
|
||||
now_iso = datetime.now(timezone.utc).isoformat()
|
||||
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||||
from archivar.room_map import RoomMap
|
||||
from archivar.config import ROOM_MAP_PATH
|
||||
from pathlib import Path as PathLib
|
||||
RoomMap.save(self.archivar._room_map, PathLib(ROOM_MAP_PATH))
|
||||
self.archivar._room_map.reload()
|
||||
|
||||
# Aktualisiere doc_store mit neuem Pfad
|
||||
if self.archivar._doc_store is not None:
|
||||
self.archivar._doc_store.set_base_dir(PathLib(norm_path))
|
||||
else:
|
||||
from plugin.archivar.doc_store import DocumentationStore
|
||||
self.archivar._doc_store = DocumentationStore(base_dir=PathLib(norm_path))
|
||||
|
||||
logger.info(
|
||||
"[rocketchat] FAKT-Store: strategy='manual', path=%s, created_at=%s",
|
||||
norm_path, now_iso,
|
||||
)
|
||||
await self._post_message_with_retry(
|
||||
operator_room_id,
|
||||
f"✅ FAKT-Speicherort: `{norm_path}`\n"
|
||||
f"Strategie: {'Neues Verzeichnis angelegt' if fakt_sub_phase == 'new_path' else 'Bestehendes Verzeichnis referenziert'}\n"
|
||||
f"Änderbar mit `::setfakt`."
|
||||
)
|
||||
|
||||
# Onboarding abschließen
|
||||
await self._complete_onboarding(operator_room_id)
|
||||
return
|
||||
|
||||
# Haupt-Phase: Button-Klick oder Text-Antwort
|
||||
if single_line.startswith("FAKT::"):
|
||||
_, choice = single_line.split("::", 1)
|
||||
choice = choice.strip()
|
||||
else:
|
||||
choice = single_line
|
||||
|
||||
from plugin.archivar.onboarding import (
|
||||
validate_fact_store_path,
|
||||
create_and_verify_fact_store,
|
||||
get_default_fact_store_path,
|
||||
)
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# Option 1: Standard
|
||||
if "Standard" in choice or "1️⃣" in choice or choice == "1":
|
||||
default_path = get_default_fact_store_path()
|
||||
result = create_and_verify_fact_store(default_path)
|
||||
if not result["success"]:
|
||||
await self._post_message_with_retry(
|
||||
operator_room_id,
|
||||
f"❌ Standard-Pfad konnte nicht erstellt werden: {result['error']}"
|
||||
)
|
||||
return
|
||||
|
||||
strategy = "auto"
|
||||
now_iso = datetime.now(timezone.utc).isoformat()
|
||||
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||||
from archivar.room_map import RoomMap
|
||||
from archivar.config import ROOM_MAP_PATH
|
||||
from pathlib import Path as PathLib
|
||||
RoomMap.save(self.archivar._room_map, PathLib(ROOM_MAP_PATH))
|
||||
self.archivar._room_map.reload()
|
||||
|
||||
# Aktualisiere doc_store
|
||||
if self.archivar._doc_store is not None:
|
||||
self.archivar._doc_store.set_base_dir(PathLib(default_path))
|
||||
else:
|
||||
from plugin.archivar.doc_store import DocumentationStore
|
||||
self.archivar._doc_store = DocumentationStore(base_dir=PathLib(default_path))
|
||||
|
||||
logger.info(
|
||||
"[rocketchat] FAKT-Store: strategy='auto', path=%s, created_at=%s",
|
||||
default_path, now_iso,
|
||||
)
|
||||
await self._post_message_with_retry(
|
||||
operator_room_id,
|
||||
f"✅ FAKT-Speicherort: `{default_path}` (Standard)\n"
|
||||
f"Änderbar mit `::setfakt`."
|
||||
)
|
||||
await self._complete_onboarding(operator_room_id)
|
||||
return
|
||||
|
||||
# Option 2: Neuer Ort
|
||||
elif "Neuer Ort" in choice or "2️⃣" in choice or choice == "2":
|
||||
self._onboarding_state["fakt_sub_phase"] = "new_path"
|
||||
if self.archivar is not None:
|
||||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||||
await self._post_message_with_retry(
|
||||
operator_room_id,
|
||||
"📁 Bitte gib den absoluten Pfad für den neuen FAKT-Speicherort ein "
|
||||
"(z.B. `/home/bernd/meine-notizen`):"
|
||||
)
|
||||
return
|
||||
|
||||
# Option 3: Bestehender Ort
|
||||
elif "Bestehender Ort" in choice or "3️⃣" in choice or choice == "3":
|
||||
self._onboarding_state["fakt_sub_phase"] = "existing_path"
|
||||
if self.archivar is not None:
|
||||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||||
await self._post_message_with_retry(
|
||||
operator_room_id,
|
||||
"📁 Bitte gib den absoluten Pfad zum bestehenden FAKT-Speicherort ein "
|
||||
"(z.B. `/data/Wissensdatenbank`):"
|
||||
)
|
||||
return
|
||||
|
||||
# Option 4: Keine Sammlung
|
||||
elif "Keine Sammlung" in choice or "4️⃣" in choice or choice == "4":
|
||||
strategy = "none"
|
||||
now_iso = datetime.now(timezone.utc).isoformat()
|
||||
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||||
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||||
from archivar.room_map import RoomMap
|
||||
from archivar.config import ROOM_MAP_PATH
|
||||
from pathlib import Path as PathLib
|
||||
RoomMap.save(self.archivar._room_map, PathLib(ROOM_MAP_PATH))
|
||||
self.archivar._room_map.reload()
|
||||
|
||||
# Deaktiviere doc_store
|
||||
self.archivar._doc_store = None
|
||||
|
||||
logger.info(
|
||||
"[rocketchat] FAKT-Store: strategy='none', created_at=%s",
|
||||
now_iso,
|
||||
)
|
||||
await self._post_message_with_retry(
|
||||
operator_room_id,
|
||||
"✅ FAKT-Speicherort: **Keine Wissensammlung**\n"
|
||||
"FAKT-Nachrichten werden im Chat beantwortet, aber nicht persistiert.\n"
|
||||
"Änderbar mit `::setfakt`."
|
||||
)
|
||||
await self._complete_onboarding(operator_room_id)
|
||||
return
|
||||
|
||||
else:
|
||||
await self._post_message_with_retry(
|
||||
operator_room_id,
|
||||
"❌ Bitte wähle eine Option: 1 (Standard), 2 (Neuer Ort), 3 (Bestehender Ort) oder 4 (Keine Sammlung)."
|
||||
)
|
||||
return
|
||||
|
||||
# ── V8.4.2: Keyword-Konflikt-Auflösung ──────────────────────────
|
||||
conflict_phase = state.get("conflict_phase", "")
|
||||
if conflict_phase in ("keywords_100", "keywords_context"):
|
||||
@@ -3133,6 +3558,10 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
if "⏰" in action or "Später" in action:
|
||||
# Onboarding pausieren — State persistieren für Wiederaufnahme
|
||||
# A1b: Lock für alle Räume freigeben
|
||||
from archivar.onboarding import release_onboarding_lock
|
||||
for room in state.get("missing_rooms", []):
|
||||
release_onboarding_lock(room["room_id"])
|
||||
if self.archivar is not None:
|
||||
self.archivar._stats["onboarding_active"] = False
|
||||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||||
@@ -3162,6 +3591,10 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
if "Später" in action or "⏰" in action:
|
||||
# Onboarding pausieren — State persistieren
|
||||
# A1b: Lock für alle Räume freigeben
|
||||
from archivar.onboarding import release_onboarding_lock
|
||||
for room in state.get("missing_rooms", []):
|
||||
release_onboarding_lock(room["room_id"])
|
||||
if self.archivar is not None:
|
||||
self.archivar._stats["onboarding_active"] = False
|
||||
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||||
@@ -3644,6 +4077,25 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
await self._post_message_with_retry(operator_room_id, "\n".join(lines), attachments=attachments)
|
||||
logger.info("[rocketchat] Onboarding v2 abgeschlossen: alle Räume eingerichtet")
|
||||
|
||||
async def _complete_onboarding(self, operator_room_id: str) -> None:
|
||||
"""Thema 3: Onboarding final abschließen (nach FAKT-Speicherort-Dialog)."""
|
||||
# A1b: Onboarding-Lock für alle onboardeten Räume freigeben
|
||||
from archivar.onboarding import release_onboarding_lock
|
||||
if self._onboarding_state:
|
||||
missing = self._onboarding_state.get("missing_rooms", [])
|
||||
for room in missing:
|
||||
release_onboarding_lock(room["room_id"])
|
||||
if self.archivar is not None:
|
||||
self.archivar._stats["onboarding_active"] = False
|
||||
self.archivar._state.clear_onboarding_state()
|
||||
self._onboarding_state = {}
|
||||
# FIX E: Raum-Map Summary nach Onboarding aktualisieren
|
||||
self._room_map_summary = self._build_room_map_summary()
|
||||
if self._room_map_summary:
|
||||
logger.info("[rocketchat] FIX E: Raum-Map Summary nach Onboarding aktualisiert (%d Räume)",
|
||||
len(self._room_map_summary.splitlines()) - 1)
|
||||
logger.info("[rocketchat] Onboarding v2 vollständig abgeschlossen (mit FAKT-Speicherort)")
|
||||
|
||||
@staticmethod
|
||||
def _derive_keywords(room_name: str, theme: str) -> list:
|
||||
"""Leitet Stichworte aus Raumname und Thema ab.
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -175,8 +178,18 @@ class ArchivarMessageHandler:
|
||||
self._state = ArchivarState(ARCHIVAR_STATE_PATH)
|
||||
self._state.load()
|
||||
|
||||
# doc_store writes to fact_store_path from room_map
|
||||
self._doc_store = DocumentationStore(base_dir=self._room_map.fact_store_path)
|
||||
# Thema 3: Strategy-aware DocumentationStore
|
||||
strategy = self._room_map.fact_store_strategy
|
||||
if strategy == "none":
|
||||
self._doc_store = None
|
||||
logger.info("FAKT-Store: strategy='none' — kein DocumentationStore")
|
||||
else:
|
||||
fact_path = self._room_map.fact_store_path
|
||||
if strategy == "auto":
|
||||
# mkdir -p falls Pfad nicht existiert
|
||||
fact_path.mkdir(parents=True, exist_ok=True)
|
||||
logger.info("FAKT-Store: strategy='auto' — Verzeichnis erstellt: %s", fact_path)
|
||||
self._doc_store = DocumentationStore(base_dir=fact_path)
|
||||
|
||||
# Cache for subscribed room IDs (set later via set_subscribed_room_ids)
|
||||
self._subscribed_room_ids_cache: Optional[set] = None
|
||||
@@ -411,16 +424,22 @@ class ArchivarMessageHandler:
|
||||
self._stats["meta"] += 1
|
||||
elif decision.is_unrouteable:
|
||||
self._stats["classified"] += 1
|
||||
stored = self._doc_store.store(
|
||||
text=text,
|
||||
category=decision.category,
|
||||
confidence=decision.confidence,
|
||||
reason=decision.unrouteable_reason,
|
||||
)
|
||||
logger.info(
|
||||
"Unrouteable [%s] stored in doc_store: %s",
|
||||
decision.category, stored,
|
||||
)
|
||||
if self._doc_store is not None:
|
||||
stored = self._doc_store.store(
|
||||
text=text,
|
||||
category=decision.category,
|
||||
confidence=decision.confidence,
|
||||
reason=decision.unrouteable_reason,
|
||||
)
|
||||
logger.info(
|
||||
"Unrouteable [%s] stored in doc_store: %s",
|
||||
decision.category, stored,
|
||||
)
|
||||
else:
|
||||
logger.info(
|
||||
"Unrouteable [%s] NOT stored — fact_store_strategy='none'",
|
||||
decision.category,
|
||||
)
|
||||
elif decision.is_fallback:
|
||||
self._stats["fallback"] += 1
|
||||
elif decision.is_catch_all:
|
||||
@@ -447,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(
|
||||
@@ -1061,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)
|
||||
|
||||
@@ -1068,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")
|
||||
}
|
||||
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,
|
||||
)
|
||||
|
||||
# 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
|
||||
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.
|
||||
|
||||
# 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"]
|
||||
})
|
||||
Thin wrapper — delegates to standalone function in archivar.onboarding.
|
||||
|
||||
return missing
|
||||
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 ───────────────────────────────────────────────────
|
||||
|
||||
@@ -1161,8 +1205,8 @@ class ArchivarMessageHandler:
|
||||
self._router.set_subscribed_room_ids(room_ids)
|
||||
|
||||
@property
|
||||
def doc_store(self) -> DocumentationStore:
|
||||
"""Documentation store for unrouteable messages."""
|
||||
def doc_store(self) -> Optional[DocumentationStore]:
|
||||
"""Documentation store for unrouteable messages (None if strategy='none')."""
|
||||
return self._doc_store
|
||||
|
||||
@property
|
||||
|
||||
@@ -822,6 +822,23 @@ class ArchivarState:
|
||||
)
|
||||
return True
|
||||
|
||||
def topic_revive(self, room_id: str, topic: str) -> bool:
|
||||
"""A1b V7-3: Wiederbelebe ein verblasstes 'jetzt'-Topic (Alias).
|
||||
|
||||
Semantischer Alias für ``restore_never_route()``.
|
||||
'Rückbezug darf jetzt NICHT nur verlängern, sondern muss es
|
||||
WIEDERBELEBEN können, wenn es bereits verblasst ist.'
|
||||
|
||||
Args:
|
||||
room_id: Die ID des Raums.
|
||||
topic: Das Thema.
|
||||
|
||||
Returns:
|
||||
True wenn erfolgreich wiederbelebt, False wenn Eintrag
|
||||
nicht existiert oder bereits AKTIV ist.
|
||||
"""
|
||||
return self.restore_never_route(room_id, topic)
|
||||
|
||||
# Neue Methoden für das selbstlernende Keyword-Gewicht-System
|
||||
|
||||
# ── V8.2 A2: Ring-State für Strategie-Modus ────────────────────────
|
||||
|
||||
@@ -57,6 +57,16 @@ CONFIDENCE_THRESHOLDS: dict = {
|
||||
"STAY_IN_ROOM": 0.6, # Unter 60% bleibt die Nachricht im Raum
|
||||
}
|
||||
|
||||
# ── A1b: Satzeinleitungs-LLM-Validierung ─────────────────────────────────────
|
||||
# Schwelle, ab der eine Satzeinleitung als "hart" gilt und KEINE
|
||||
# LLM-Validierung benötigt. Weiche Muster (Konfidenz < Schwelle) werden
|
||||
# via LLM validiert (Stufe 4/5).
|
||||
|
||||
SENTENCE_MARKER_LLM_THRESHOLD: float = 0.7
|
||||
"""Konfidenz-Schwelle für LLM-Validierung von Satzeinleitungen.
|
||||
Muster mit Konfidenz < 0.7 gelten als 'weich' und werden via LLM validiert.
|
||||
Empirisch anpassbar nach 2 Wochen .45-Daten."""
|
||||
|
||||
"""
|
||||
Nachrichten mit confidence >= 0.9 werden automatisch geroutet.
|
||||
Nachrichten mit confidence 0.6-0.9 benötigen eine Klärung mit Buttons.
|
||||
|
||||
@@ -131,3 +131,14 @@ class DocumentationStore:
|
||||
def base_dir(self) -> Path:
|
||||
"""Base directory for stored documents."""
|
||||
return self._base_dir
|
||||
|
||||
def set_base_dir(self, new_base_dir: Path) -> None:
|
||||
"""Thema 3: Ändere das Basisverzeichnis zur Laufzeit.
|
||||
|
||||
Setzt nur den Pfad — erstellt das Verzeichnis NICHT.
|
||||
Das Verzeichnis wird erst bei ``store()`` via ``mkdir -p`` erstellt.
|
||||
|
||||
Args:
|
||||
new_base_dir: Neues Basisverzeichnis.
|
||||
"""
|
||||
self._base_dir = Path(new_base_dir)
|
||||
|
||||
@@ -0,0 +1,492 @@
|
||||
"""
|
||||
FAKT-Speicherort-Dialog beim Onboarding (Thema 3).
|
||||
|
||||
Stellt die Pfad-Validierung und den 4-Optionen-Dialog für den
|
||||
FAKT-Speicherort bereit. Wird vom Adapter nach der Butler-Mode-Frage
|
||||
aufgerufen.
|
||||
|
||||
Sicherheitsanforderungen:
|
||||
- Pfad muss absolut sein
|
||||
- Keine '..' (Path-Traversal)
|
||||
- System-Verzeichnisse blockiert: /etc, /var, /usr, /boot, /sys, /proc
|
||||
- HOME-relativ wird normalisiert
|
||||
"""
|
||||
|
||||
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",
|
||||
"/var",
|
||||
"/usr",
|
||||
"/boot",
|
||||
"/sys",
|
||||
"/proc",
|
||||
]
|
||||
|
||||
|
||||
def validate_fact_store_path(raw_path: str) -> Dict[str, Any]:
|
||||
"""Validiere einen FAKT-Speicherort-Pfad.
|
||||
|
||||
Args:
|
||||
raw_path: Der vom Benutzer eingegebene Pfad (kann HOME-relativ sein).
|
||||
|
||||
Returns:
|
||||
Dict mit:
|
||||
- valid (bool): True wenn der Pfad gültig ist
|
||||
- error (str | None): Fehlermeldung wenn invalid
|
||||
- normalized_path (str | None): Normalisierter absoluter Pfad
|
||||
"""
|
||||
if not raw_path or not raw_path.strip():
|
||||
return {"valid": False, "error": "Pfad darf nicht leer sein.", "normalized_path": None}
|
||||
|
||||
raw_path = raw_path.strip()
|
||||
|
||||
# Prüfe: keine '..' (Path-Traversal) — VOR der Normalisierung prüfen
|
||||
if ".." in raw_path:
|
||||
return {
|
||||
"valid": False,
|
||||
"error": "Path-Traversal ('..') ist nicht erlaubt.",
|
||||
"normalized_path": None,
|
||||
}
|
||||
|
||||
# Prüfe: muss absolut sein oder mit ~ beginnen
|
||||
if not (raw_path.startswith("/") or raw_path.startswith("~")):
|
||||
return {
|
||||
"valid": False,
|
||||
"error": "Der Pfad muss absolut sein (z.B. /home/bernd/wissenssammlung).",
|
||||
"normalized_path": None,
|
||||
}
|
||||
|
||||
# HOME-relativ normalisieren
|
||||
expanded = os.path.expanduser(raw_path)
|
||||
|
||||
# In absoluten Pfad umwandeln
|
||||
try:
|
||||
abs_path = os.path.abspath(expanded)
|
||||
except (ValueError, OSError) as e:
|
||||
return {"valid": False, "error": f"Ungültiger Pfad: {e}", "normalized_path": None}
|
||||
|
||||
# Prüfe: System-Verzeichnisse blockiert
|
||||
resolved = str(Path(abs_path).resolve())
|
||||
for blocked in BLOCKED_PREFIXES:
|
||||
if resolved == blocked or resolved.startswith(blocked + "/") or resolved.startswith(blocked + os.sep):
|
||||
return {
|
||||
"valid": False,
|
||||
"error": f"System-Verzeichnis '{blocked}' ist blockiert. Bitte wähle einen Pfad unter /home oder /tmp.",
|
||||
"normalized_path": None,
|
||||
}
|
||||
|
||||
return {"valid": True, "error": None, "normalized_path": resolved}
|
||||
|
||||
|
||||
def create_and_verify_fact_store(path: str) -> Dict[str, Any]:
|
||||
"""Erstelle das FAKT-Speicherort-Verzeichnis und prüfe Schreibbarkeit.
|
||||
|
||||
Args:
|
||||
path: Normalisierter absoluter Pfad.
|
||||
|
||||
Returns:
|
||||
Dict mit:
|
||||
- success (bool): True wenn Verzeichnis erstellt und schreibbar
|
||||
- error (str | None): Fehlermeldung bei Misserfolg
|
||||
"""
|
||||
try:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
except OSError as e:
|
||||
return {"success": False, "error": f"Konnte Verzeichnis nicht erstellen: {e}"}
|
||||
|
||||
# Schreibtest
|
||||
try:
|
||||
test_file = os.path.join(path, ".hermes_write_test")
|
||||
with open(test_file, "w") as f:
|
||||
f.write("test")
|
||||
os.remove(test_file)
|
||||
except OSError as e:
|
||||
return {"success": False, "error": f"Schreibtest fehlgeschlagen: {e}"}
|
||||
|
||||
return {"success": True, "error": None}
|
||||
|
||||
|
||||
def verify_existing_fact_store(path: str) -> Dict[str, Any]:
|
||||
"""Prüfe ob ein bestehendes Verzeichnis referenzierbar und schreibbar ist.
|
||||
|
||||
Args:
|
||||
path: Normalisierter absoluter Pfad.
|
||||
|
||||
Returns:
|
||||
Dict mit:
|
||||
- success (bool): True wenn Verzeichnis existiert und schreibbar
|
||||
- error (str | None): Fehlermeldung bei Misserfolg
|
||||
"""
|
||||
if not os.path.isdir(path):
|
||||
return {"success": False, "error": f"Verzeichnis existiert nicht: {path}"}
|
||||
|
||||
# Schreibtest
|
||||
try:
|
||||
test_file = os.path.join(path, ".hermes_write_test")
|
||||
with open(test_file, "w") as f:
|
||||
f.write("test")
|
||||
os.remove(test_file)
|
||||
except OSError as e:
|
||||
return {"success": False, "error": f"Schreibtest fehlgeschlagen: {e}"}
|
||||
|
||||
return {"success": True, "error": None}
|
||||
|
||||
|
||||
def get_default_fact_store_path() -> str:
|
||||
"""Gibt den Standard-FAKT-Speicherort zurück (Option 1).
|
||||
|
||||
Returns:
|
||||
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}
|
||||
@@ -126,6 +126,8 @@ class RoomMap:
|
||||
fact_store_path: Path,
|
||||
version: int = 1,
|
||||
butler_mode: str = "cognitive",
|
||||
fact_store_strategy: str = "manual",
|
||||
fact_store_created_at: Optional[str] = None,
|
||||
) -> None:
|
||||
"""Initialize from pre-parsed data.
|
||||
|
||||
@@ -136,6 +138,8 @@ class RoomMap:
|
||||
self._fact_store_path = fact_store_path
|
||||
self._version = version
|
||||
self._butler_mode = butler_mode # Fix C v7: 'cognitive' | 'strict' | 'off'
|
||||
self._fact_store_strategy = fact_store_strategy # Thema 3: 'auto' | 'manual' | 'none'
|
||||
self._fact_store_created_at = fact_store_created_at # Thema 3: ISO-Timestamp
|
||||
|
||||
# ── Properties ───────────────────────────────────────────────────
|
||||
|
||||
@@ -180,6 +184,36 @@ class RoomMap:
|
||||
raise ValueError(f"Invalid butler_mode: {mode}")
|
||||
self._butler_mode = mode
|
||||
|
||||
# ── Thema 3: FAKT-Speicherort-Properties ──────────────────────────
|
||||
|
||||
@property
|
||||
def fact_store_strategy(self) -> str:
|
||||
"""Thema 3: FAKT-Speicherort-Strategie — 'auto', 'manual', oder 'none'."""
|
||||
return self._fact_store_strategy
|
||||
|
||||
def set_fact_store_strategy(self, strategy: str) -> None:
|
||||
"""Thema 3: Setze die FAKT-Speicherort-Strategie.
|
||||
|
||||
Args:
|
||||
strategy: 'auto', 'manual', or 'none'.
|
||||
"""
|
||||
if strategy not in ("auto", "manual", "none"):
|
||||
raise ValueError(f"Invalid fact_store_strategy: {strategy}")
|
||||
self._fact_store_strategy = strategy
|
||||
|
||||
@property
|
||||
def fact_store_created_at(self) -> Optional[str]:
|
||||
"""Thema 3: ISO-Timestamp der FAKT-Speicherort-Erstellung (Telemetrie)."""
|
||||
return self._fact_store_created_at
|
||||
|
||||
def set_fact_store_created_at(self, timestamp: Optional[str]) -> None:
|
||||
"""Thema 3: Setze den FAKT-Speicherort-Erstellungszeitpunkt.
|
||||
|
||||
Args:
|
||||
timestamp: ISO-Format Timestamp oder None.
|
||||
"""
|
||||
self._fact_store_created_at = timestamp
|
||||
|
||||
# ── Lookup Methods ────────────────────────────────────────────────
|
||||
|
||||
def find_room_by_keywords(self, text: str, min_score: int = 1, origin_room_id: Optional[str] = None) -> Optional[RoomEntry]:
|
||||
@@ -459,6 +493,8 @@ class RoomMap:
|
||||
self._fact_store_path = new_map._fact_store_path
|
||||
self._version = new_map._version
|
||||
self._butler_mode = new_map._butler_mode # Fix C v7
|
||||
self._fact_store_strategy = new_map._fact_store_strategy # Thema 3
|
||||
self._fact_store_created_at = new_map._fact_store_created_at # Thema 3
|
||||
|
||||
@staticmethod
|
||||
def save(room_map: 'RoomMap', path: Optional[Path] = None) -> None:
|
||||
@@ -488,7 +524,11 @@ class RoomMap:
|
||||
"excluded_rooms": list(room_map._excluded_room_ids),
|
||||
"fact_store_path": str(room_map._fact_store_path),
|
||||
"butler_mode": room_map._butler_mode, # Fix C v7
|
||||
"fact_store_strategy": room_map._fact_store_strategy, # Thema 3
|
||||
}
|
||||
# Thema 3: fact_store_created_at nur persistieren wenn gesetzt
|
||||
if room_map._fact_store_created_at is not None:
|
||||
data["fact_store_created_at"] = room_map._fact_store_created_at
|
||||
|
||||
for room_id, room_entry in room_map._rooms.items():
|
||||
data["rooms"][room_id] = {
|
||||
@@ -760,6 +800,9 @@ class RoomMap:
|
||||
os.path.expanduser(data.get("fact_store_path", "~/archivar_docs"))
|
||||
)
|
||||
butler_mode = data.get("butler_mode", "cognitive") # Fix C v7
|
||||
# Thema 3: FAKT-Speicherort-Felder
|
||||
fact_store_strategy = data.get("fact_store_strategy", "manual") # Migration: default 'manual'
|
||||
fact_store_created_at = data.get("fact_store_created_at", None)
|
||||
|
||||
return cls(
|
||||
rooms=rooms,
|
||||
@@ -767,6 +810,8 @@ class RoomMap:
|
||||
fact_store_path=fact_store,
|
||||
version=version,
|
||||
butler_mode=butler_mode,
|
||||
fact_store_strategy=fact_store_strategy,
|
||||
fact_store_created_at=fact_store_created_at,
|
||||
)
|
||||
|
||||
|
||||
|
||||
+499
-2
@@ -28,6 +28,7 @@ from .config import (
|
||||
FAISS_CONFLICT_DIFF,
|
||||
ARCHIVAR_RED_FLAG,
|
||||
RED_FLAG_PROMPT,
|
||||
SENTENCE_MARKER_LLM_THRESHOLD,
|
||||
)
|
||||
from .room_map import RoomMap, RoomEntry
|
||||
from .room_index import RoomIndexManager
|
||||
@@ -35,6 +36,11 @@ from .booster import KeywordBooster
|
||||
from .archivar_state import ArchivarState
|
||||
from .routing_counter import routing_counter
|
||||
from .routing_telemetry import routing_telemetry
|
||||
from .sentence_markers import (
|
||||
detect_sentence_marker,
|
||||
SentenceMarkerResult,
|
||||
MarkerClass,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -115,6 +121,52 @@ ANTWORTE NUR mit EINEM der folgenden Formate:
|
||||
|
||||
Antwort:"""
|
||||
|
||||
# ── A1b: LLM-Validierung für Weich-Muster (Stufe 4/5) ────────────────────────
|
||||
# Wird NUR bei Konfidenz < 0.8 aufgerufen (weiche Muster, indirekte Muster).
|
||||
# Das LLM validiert die Satzeinleitungs-Klassifikation, trifft aber KEINE
|
||||
# Routing-Entscheidung. Das Routing bleibt bei FAISS + Classifier.
|
||||
# V7-4 ist ein Kontext-Signal, kein Routing-Signal.
|
||||
|
||||
_SENTENCE_MARKER_VALIDATION_PROMPT: str = """\
|
||||
Du bist ein Konversationsanalysator. Deine Aufgabe: Validiere, ob eine \
|
||||
Satzeinleitung einen echten THEMENWECHSEL, einen RÜCKBEZUG auf ein früheres \
|
||||
Thema oder KEINE klare Einleitung darstellt.
|
||||
|
||||
KONVERSATIONSHISTORIE (letzte Nachrichten):
|
||||
{history}
|
||||
|
||||
AKTUELLE NACHRICHT:
|
||||
{current_message}
|
||||
|
||||
ERKANNTE SATZEINLEITUNG (Regex):
|
||||
- Klasse: {marker_class}
|
||||
- Konfidenz (Regex): {regex_confidence}
|
||||
- Gematchter Text: {matched_text}
|
||||
- Extrahiertes Referenz-Topic: {referenz_topic}
|
||||
|
||||
V7-3 STATE (jetzt-Topic-Fenster):
|
||||
{v7_3_state}
|
||||
|
||||
UNTERSCHEIDUNG:
|
||||
- THEMENWECHSEL: Der Nutzer beginnt ein NEUES Thema. Das alte 'jetzt'-Topic \
|
||||
soll verblassen. Signalwörter: 'anderes Thema', 'kurze Frage zu etwas anderem', \
|
||||
'wechsel zum Thema', 'komplett anderes Thema'.
|
||||
- RUECKBEZUG: Der Nutzer will ein FRÜHERES Thema WIEDER AUFGREIFEN. Das alte \
|
||||
'jetzt'-Topic soll wiederbelebt werden. Signalwörter: 'nochmal auf', \
|
||||
'zurückkommen', 'zurück zu', 'bezüglich', 'wie wir vorhin über'.
|
||||
- UNENTSCHIEDBAR: Die Einleitung ist zu vage oder mehrdeutig. Keine Aktion.
|
||||
|
||||
WICHTIG:
|
||||
- 'Da fällt mir ein,' kann Themenwechsel ODER Rückbezug sein — prüfe den Kontext.
|
||||
- 'In dem Zusammenhang —' ist meist ein Rückbezug, aber nicht immer.
|
||||
- 'Übrigens,' ist meist ein Themenwechsel, aber nicht immer.
|
||||
- Bei UNENTSCHIEDBAR: konservativ behandeln = keine 'jetzt'-Manipulation.
|
||||
|
||||
ANTWORTE NUR mit EINEM JSON-Objekt (kein Markdown, kein extra Text):
|
||||
{{"action": "themenwechsel"|"rueckbezug"|"unentscheidbar", "confidence": 0.0-1.0, "referenz_topic": "topic-slug oder null"}}
|
||||
|
||||
Antwort:"""
|
||||
|
||||
# ── Meta-Fragen-Erkennung ───────────────────────────────────────────────────
|
||||
# Meta-Fragen sind Fragen über das Archivar-System selbst. Sie würden sonst als
|
||||
# FRAGE klassifiziert und im Zielraum landen, wo sie irrelevant sind.
|
||||
@@ -449,6 +501,312 @@ class BidirectionalRouter:
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
# ── Schritt 0.6: A1b Stufe 0 — Satzeinleitungs-Erkennung ──────
|
||||
# Läuft VOR allen anderen Stufen (Regex, kein Embedding, kein LLM).
|
||||
# Drei Erkennungs-Klassen:
|
||||
# Hart-Themenwechsel → jetzt verblasst (immediate)
|
||||
# Hart-Rückbezug → jetzt wiederbelebt (immediate)
|
||||
# Weich → unsicher → normaler Flow (LLM-Validierung in Stufe 4/5)
|
||||
sentence_marker = detect_sentence_marker(text)
|
||||
if sentence_marker is not None:
|
||||
routing_telemetry.start_timer()
|
||||
logger.info(
|
||||
"A1b Stufe 0: Satzeinleitung erkannt — class=%s, "
|
||||
"confidence=%.2f, action=%s, topic=%s, pattern=%s",
|
||||
sentence_marker.marker_class.value,
|
||||
sentence_marker.confidence,
|
||||
sentence_marker.action,
|
||||
sentence_marker.referenz_topic or "N/A",
|
||||
sentence_marker.matched_pattern,
|
||||
)
|
||||
routing_telemetry.record(
|
||||
stage='stufe0',
|
||||
score=sentence_marker.confidence,
|
||||
decision=sentence_marker.action,
|
||||
target=sentence_marker.referenz_topic or '',
|
||||
origin=origin_room_id,
|
||||
duration_ms=routing_telemetry.elapsed_ms(),
|
||||
)
|
||||
routing_counter.increment(
|
||||
f'stufe0_{sentence_marker.marker_class.value}'
|
||||
)
|
||||
|
||||
if sentence_marker.marker_class == MarkerClass.HART_THEMENWECHSEL:
|
||||
# ── Hart-Themenwechsel: jetzt verblasst ──────────
|
||||
# Alle AKTIVEN never_route-Einträge für diesen Raum
|
||||
# auf VERBLASST setzen (Themenwechsel blendet 'jetzt' aus).
|
||||
topics = self._state.get_never_route_topics(origin_room_id)
|
||||
verblasst_count = 0
|
||||
for topic, entry in topics.items():
|
||||
if entry.get("state") == "AKTIV":
|
||||
entry["state"] = "VERBLASST"
|
||||
verblasst_count += 1
|
||||
logger.info(
|
||||
"A1b Stufe 0: Themenwechsel — '%s' AKTIV → VERBLASST",
|
||||
topic,
|
||||
)
|
||||
if verblasst_count > 0:
|
||||
self._state.save()
|
||||
logger.info(
|
||||
"A1b Stufe 0: %d never_route Einträge verblasst "
|
||||
"(Themenwechsel)",
|
||||
verblasst_count,
|
||||
)
|
||||
routing_counter.increment('stufe0_themenwechsel_stay')
|
||||
logger.info(
|
||||
"ROUTING DECISION: reason=stufe0_themenwechsel, "
|
||||
"origin_room=%s, stay=True",
|
||||
origin_room_id,
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=1.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
elif sentence_marker.marker_class == MarkerClass.HART_RUECKBEZUG:
|
||||
# ── Hart-Rückbezug: jetzt wiederbelebt ───────────
|
||||
# Wenn referenz_topic extrahiert wurde und ein VERBLASSTER
|
||||
# Eintrag existiert → wiederbeleben (VERBLASST → AKTIV).
|
||||
if sentence_marker.referenz_topic is not None:
|
||||
topic = sentence_marker.referenz_topic
|
||||
entry = self._state.get_never_route_entry(
|
||||
origin_room_id, topic
|
||||
)
|
||||
if entry is not None:
|
||||
if entry.get("state") == "VERBLASST":
|
||||
restored = self._state.topic_revive(
|
||||
origin_room_id, topic
|
||||
)
|
||||
if restored:
|
||||
logger.info(
|
||||
"A1b Stufe 0: Rückbezug auf '%s' → "
|
||||
"VERBLASST → AKTIV (wiederbelebt), "
|
||||
"stay_in_room",
|
||||
topic,
|
||||
)
|
||||
routing_counter.increment(
|
||||
'stufe0_rueckbezug_restore'
|
||||
)
|
||||
logger.info(
|
||||
"ROUTING DECISION: reason=stufe0_rueckbezug_restore, "
|
||||
"origin_room=%s, stay=True",
|
||||
origin_room_id,
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=1.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
elif entry.get("state") == "AKTIV":
|
||||
# Bereits AKTIV → verlängern
|
||||
self._state.extend_never_route(
|
||||
origin_room_id, topic
|
||||
)
|
||||
logger.info(
|
||||
"A1b Stufe 0: Rückbezug auf '%s' → "
|
||||
"never_route verlängert (bereits AKTIV), "
|
||||
"stay_in_room",
|
||||
topic,
|
||||
)
|
||||
routing_counter.increment(
|
||||
'stufe0_rueckbezug_extend'
|
||||
)
|
||||
logger.info(
|
||||
"ROUTING DECISION: reason=stufe0_rueckbezug_extend, "
|
||||
"origin_room=%s, stay=True",
|
||||
origin_room_id,
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=1.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
else:
|
||||
# Kein never_route Eintrag → normaler Flow
|
||||
logger.debug(
|
||||
"A1b Stufe 0: Rückbezug auf '%s' aber kein "
|
||||
"never_route Eintrag → normaler Flow",
|
||||
topic,
|
||||
)
|
||||
else:
|
||||
# Kein Topic extrahierbar → normaler Flow
|
||||
logger.debug(
|
||||
"A1b Stufe 0: Rückbezug ohne Topic → normaler Flow"
|
||||
)
|
||||
|
||||
elif sentence_marker.marker_class == MarkerClass.WEICH:
|
||||
# ── Weich-Muster: LLM-Validierung (Stufe 4/5) ────
|
||||
# Konfidenz < SENTENCE_MARKER_LLM_THRESHOLD → LLM
|
||||
# validiert die Klassifikation und manipuliert
|
||||
# V7-3-State entsprechend.
|
||||
if sentence_marker.confidence < SENTENCE_MARKER_LLM_THRESHOLD:
|
||||
logger.info(
|
||||
"A1b Stufe 4/5: Weich-Muster (conf=%.2f < %.2f) → "
|
||||
"LLM-Validierung gestartet",
|
||||
sentence_marker.confidence,
|
||||
SENTENCE_MARKER_LLM_THRESHOLD,
|
||||
)
|
||||
routing_telemetry.start_timer()
|
||||
llm_result = await validate_sentence_marker(
|
||||
marker_result=sentence_marker,
|
||||
current_message=text,
|
||||
room_id=origin_room_id,
|
||||
conversation_history=self._conversation_history,
|
||||
state=self._state,
|
||||
classifier=self._classifier,
|
||||
llm_semaphore=self._llm_semaphore,
|
||||
)
|
||||
if llm_result is not None:
|
||||
llm_action = llm_result.get("action", "unentscheidbar")
|
||||
llm_confidence = llm_result.get("confidence", 0.0)
|
||||
llm_topic = llm_result.get("referenz_topic")
|
||||
|
||||
# ── R1: Telemetrie für LLM-Validierung ──
|
||||
routing_telemetry.record(
|
||||
stage='stufe0_llm',
|
||||
score=llm_confidence,
|
||||
decision=llm_action,
|
||||
target=llm_topic or '',
|
||||
origin=origin_room_id,
|
||||
duration_ms=routing_telemetry.elapsed_ms(),
|
||||
)
|
||||
routing_counter.increment(
|
||||
f'stufe0_llm_{llm_action}'
|
||||
)
|
||||
|
||||
if llm_action == "themenwechsel":
|
||||
# LLM bestätigt Themenwechsel → jetzt verblasst
|
||||
topics = self._state.get_never_route_topics(
|
||||
origin_room_id
|
||||
)
|
||||
verblasst_count = 0
|
||||
for topic, entry in topics.items():
|
||||
if entry.get("state") == "AKTIV":
|
||||
entry["state"] = "VERBLASST"
|
||||
verblasst_count += 1
|
||||
logger.info(
|
||||
"A1b Stufe 4/5: LLM-Themenwechsel — "
|
||||
"'%s' AKTIV → VERBLASST",
|
||||
topic,
|
||||
)
|
||||
if verblasst_count > 0:
|
||||
self._state.save()
|
||||
logger.info(
|
||||
"A1b Stufe 4/5: %d never_route Einträge "
|
||||
"verblasst (LLM-Themenwechsel)",
|
||||
verblasst_count,
|
||||
)
|
||||
routing_counter.increment(
|
||||
'stufe0_llm_themenwechsel_stay'
|
||||
)
|
||||
logger.info(
|
||||
"ROUTING DECISION: "
|
||||
"reason=stufe0_llm_themenwechsel, "
|
||||
"origin_room=%s, stay=True",
|
||||
origin_room_id,
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=1.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
|
||||
elif llm_action == "rueckbezug":
|
||||
# LLM bestätigt Rückbezug → wiederbeleben
|
||||
if llm_topic is not None:
|
||||
entry = self._state.get_never_route_entry(
|
||||
origin_room_id, llm_topic
|
||||
)
|
||||
if entry is not None:
|
||||
if entry.get("state") == "VERBLASST":
|
||||
restored = self._state.topic_revive(
|
||||
origin_room_id, llm_topic
|
||||
)
|
||||
if restored:
|
||||
logger.info(
|
||||
"A1b Stufe 4/5: LLM-Rückbezug "
|
||||
"auf '%s' → VERBLASST → AKTIV "
|
||||
"(wiederbelebt), stay_in_room",
|
||||
llm_topic,
|
||||
)
|
||||
routing_counter.increment(
|
||||
'stufe0_llm_rueckbezug_restore'
|
||||
)
|
||||
logger.info(
|
||||
"ROUTING DECISION: "
|
||||
"reason=stufe0_llm_rueckbezug_restore, "
|
||||
"origin_room=%s, stay=True",
|
||||
origin_room_id,
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=1.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
elif entry.get("state") == "AKTIV":
|
||||
self._state.extend_never_route(
|
||||
origin_room_id, llm_topic
|
||||
)
|
||||
logger.info(
|
||||
"A1b Stufe 4/5: LLM-Rückbezug "
|
||||
"auf '%s' → never_route verlängert "
|
||||
"(bereits AKTIV), stay_in_room",
|
||||
llm_topic,
|
||||
)
|
||||
routing_counter.increment(
|
||||
'stufe0_llm_rueckbezug_extend'
|
||||
)
|
||||
logger.info(
|
||||
"ROUTING DECISION: "
|
||||
"reason=stufe0_llm_rueckbezug_extend, "
|
||||
"origin_room=%s, stay=True",
|
||||
origin_room_id,
|
||||
)
|
||||
return RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=1.0,
|
||||
stay_in_room=True,
|
||||
)
|
||||
else:
|
||||
logger.debug(
|
||||
"A1b Stufe 4/5: LLM-Rückbezug auf "
|
||||
"'%s' aber kein never_route Eintrag → "
|
||||
"normaler Flow",
|
||||
llm_topic,
|
||||
)
|
||||
else:
|
||||
logger.debug(
|
||||
"A1b Stufe 4/5: LLM-Rückbezug ohne "
|
||||
"Topic → normaler Flow"
|
||||
)
|
||||
else:
|
||||
# unentscheidbar → normaler Flow
|
||||
logger.debug(
|
||||
"A1b Stufe 4/5: LLM unentscheidbar → "
|
||||
"normaler Flow"
|
||||
)
|
||||
else:
|
||||
# LLM-Validierung fehlgeschlagen → normaler Flow
|
||||
logger.debug(
|
||||
"A1b Stufe 4/5: LLM-Validierung fehlgeschlagen "
|
||||
"→ normaler Flow"
|
||||
)
|
||||
else:
|
||||
# Konfidenz >= Schwelle → kein LLM nötig
|
||||
logger.debug(
|
||||
"A1b Stufe 0: Weich-Muster aber conf=%.2f >= %.2f → "
|
||||
"kein LLM, normaler Flow",
|
||||
sentence_marker.confidence,
|
||||
SENTENCE_MARKER_LLM_THRESHOLD,
|
||||
)
|
||||
|
||||
# ── Schritt 1: Raum-Zustand prüfen ───────────────────────────
|
||||
room_state_decision = self._state.should_stay_in_room(origin_room_id)
|
||||
if room_state_decision == "always":
|
||||
@@ -481,7 +839,7 @@ class BidirectionalRouter:
|
||||
# ── V7-4: Rekursive Einleitungen erkennen + wiederherstellen ──
|
||||
# Nach expire_stale_entries, VOR Meta-Fragen-Erkennung.
|
||||
# Wenn rekursiver Bezug erkannt UND es gibt einen VERBLASSTEN
|
||||
# Stick für ein Thema → restore_never_route + stay_in_room.
|
||||
# Stick für ein Thema → topic_revive + stay_in_room.
|
||||
# V7-5 W3: LLM-Bypass wenn keine never_route-Einträge für den
|
||||
# Raum existieren (Performance — spart ~2.4s LLM-Latenz).
|
||||
recursive_topic = None
|
||||
@@ -502,7 +860,7 @@ class BidirectionalRouter:
|
||||
)
|
||||
if verblasst_entry and verblasst_entry.get("state") == "VERBLASST":
|
||||
# ── Wiederherstellung: VERBLASST → AKTIV ──────────
|
||||
restored = self._state.restore_never_route(
|
||||
restored = self._state.topic_revive(
|
||||
origin_room_id, recursive_topic
|
||||
)
|
||||
if restored:
|
||||
@@ -1685,6 +2043,145 @@ def _strip_red_flag_prefix(response: str) -> str:
|
||||
return cleaned.strip()
|
||||
|
||||
|
||||
# ── A1b: LLM-Validierung für Weich-Muster (Stufe 4/5) ──────────────────────
|
||||
|
||||
|
||||
async def validate_sentence_marker(
|
||||
marker_result: SentenceMarkerResult,
|
||||
current_message: str,
|
||||
room_id: str,
|
||||
conversation_history: Any,
|
||||
state: ArchivarState,
|
||||
classifier: Any,
|
||||
llm_semaphore: asyncio.Semaphore,
|
||||
) -> Optional[dict]:
|
||||
"""Validiere eine Satzeinleitungs-Erkennung via LLM (Stufe 4/5).
|
||||
|
||||
Wird NUR bei Konfidenz < 0.8 aufgerufen (weiche Muster).
|
||||
Das LLM validiert die Klassifikation, trifft aber KEINE Routing-Entscheidung.
|
||||
|
||||
Args:
|
||||
marker_result: Das Ergebnis der Regex-Erkennung (Stufe 0).
|
||||
current_message: Der aktuelle Nachrichtentext.
|
||||
room_id: Rocket.Chat Raum-ID.
|
||||
conversation_history: ConversationHistory-Instanz (für Kontext).
|
||||
state: ArchivarState-Instanz (für V7-3-State).
|
||||
classifier: IntentClassifier-Instanz (für _llm_raw).
|
||||
llm_semaphore: asyncio.Semaphore für Ollama-Concurrency.
|
||||
|
||||
Returns:
|
||||
Dict mit {action, confidence, referenz_topic} oder None bei Fehler.
|
||||
"""
|
||||
import json as _json
|
||||
|
||||
# ── Konversationshistorie (letzte 3-5 Nachrichten) ─────────────────
|
||||
history_context = "(keine Historie)"
|
||||
if conversation_history is not None:
|
||||
try:
|
||||
buf = conversation_history._buffers.get(room_id)
|
||||
if buf:
|
||||
recent = list(buf)[-5:]
|
||||
history_lines = []
|
||||
for entry in recent:
|
||||
role = getattr(entry, "role", "user")
|
||||
msg_text = getattr(entry, "text", "")
|
||||
history_lines.append(f"[{role}] {msg_text}")
|
||||
if history_lines:
|
||||
history_context = "\n".join(history_lines)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ── V7-3 State ────────────────────────────────────────────────────
|
||||
v7_3_state = "(keine never_route Einträge)"
|
||||
try:
|
||||
topics = state.get_never_route_topics(room_id)
|
||||
if topics:
|
||||
lines = []
|
||||
for topic, entry in topics.items():
|
||||
st = entry.get("state", "?")
|
||||
lines.append(f" - {topic}: {st}")
|
||||
v7_3_state = "\n".join(lines)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ── Prompt bauen ──────────────────────────────────────────────────
|
||||
prompt = _SENTENCE_MARKER_VALIDATION_PROMPT.format(
|
||||
history=history_context,
|
||||
current_message=current_message,
|
||||
marker_class=marker_result.marker_class.value,
|
||||
regex_confidence=f"{marker_result.confidence:.2f}",
|
||||
matched_text=marker_result.matched_text,
|
||||
referenz_topic=marker_result.referenz_topic or "N/A",
|
||||
v7_3_state=v7_3_state,
|
||||
)
|
||||
|
||||
# ── LLM-Aufruf mit 5s Timeout ─────────────────────────────────────
|
||||
try:
|
||||
async with llm_semaphore:
|
||||
llm_result = await asyncio.wait_for(
|
||||
classifier._llm_raw(prompt),
|
||||
timeout=5.0,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
logger.warning(
|
||||
"A1b Stufe 4/5: LLM-Validierung Timeout (5s) → Fallback: unentscheidbar"
|
||||
)
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"A1b Stufe 4/5: LLM-Validierung fehlgeschlagen: %s → Fallback: unentscheidbar",
|
||||
e,
|
||||
)
|
||||
return None
|
||||
|
||||
if llm_result is None:
|
||||
logger.warning("A1b Stufe 4/5: LLM returned None → Fallback: unentscheidbar")
|
||||
return None
|
||||
|
||||
# ── Parse JSON-Antwort ────────────────────────────────────────────
|
||||
try:
|
||||
response_text = llm_result.strip()
|
||||
# Entferne mögliche Markdown-Code-Blöcke
|
||||
if response_text.startswith("```"):
|
||||
lines = response_text.split("\n")
|
||||
response_text = "\n".join(lines[1:]) if len(lines) > 1 else response_text
|
||||
if response_text.endswith("```"):
|
||||
response_text = response_text[:-3]
|
||||
result = _json.loads(response_text)
|
||||
except (_json.JSONDecodeError, ValueError) as e:
|
||||
logger.warning(
|
||||
"A1b Stufe 4/5: JSON-Parse-Fehler: %s — raw: %.200s",
|
||||
e, llm_result,
|
||||
)
|
||||
return None
|
||||
|
||||
# ── Validierung ───────────────────────────────────────────────────
|
||||
action = result.get("action", "unentscheidbar")
|
||||
if action not in ("themenwechsel", "rueckbezug", "unentscheidbar"):
|
||||
logger.warning(
|
||||
"A1b Stufe 4/5: Unbekannte action '%s' → unentscheidbar", action
|
||||
)
|
||||
action = "unentscheidbar"
|
||||
|
||||
confidence = float(result.get("confidence", 0.5))
|
||||
confidence = max(0.0, min(1.0, confidence))
|
||||
|
||||
referenz_topic = result.get("referenz_topic")
|
||||
if referenz_topic == "null" or referenz_topic == "None":
|
||||
referenz_topic = None
|
||||
|
||||
logger.info(
|
||||
"A1b Stufe 4/5: LLM-Validierung — action=%s, confidence=%.2f, topic=%s",
|
||||
action, confidence, referenz_topic or "N/A",
|
||||
)
|
||||
|
||||
return {
|
||||
"action": action,
|
||||
"confidence": confidence,
|
||||
"referenz_topic": referenz_topic,
|
||||
}
|
||||
|
||||
|
||||
# ── Module-level alias für externe Nutzer (adapter.py) ──────────────
|
||||
# Zentralisierte Topic-Extraktion: adapter.py importiert diese Funktion
|
||||
# statt die Logik an mehreren Stellen zu duplizieren.
|
||||
|
||||
@@ -0,0 +1,307 @@
|
||||
"""
|
||||
A1b: Satzeinleitungs-Erkennung — Stufe 0 (Vorprüfung).
|
||||
|
||||
Regex-basierte Erkennung von Satzeinleitungen, die VOR Stufe 1 (FAISS) läuft.
|
||||
Drei Erkennungs-Klassen mit unterschiedlichen Konfidenz-Werten:
|
||||
|
||||
| Klasse | Beispiel | Aktion in V7-3 | Aufwand |
|
||||
|-------------------|-------------------------------------------|------------------------|------------------|
|
||||
| Hart-Themenwechsel| 'Kurze Frage zu etwas anderem:' | jetzt verblasst (immediate) | Regex reicht |
|
||||
| Hart-Rückbezug | 'Lass uns nochmal auf LAN-Doku zurückkommen.' | jetzt wiederbelebt (immediate) | Regex + Named-Entity |
|
||||
| Weich | 'Da fällt mir ein,' | unsicher → Stufe 4/5 | Regex + LLM-Validierung |
|
||||
|
||||
Design-Entscheidungen:
|
||||
- Global konfiguriert (nicht pro Raum) — mit optionalen Raum-Override
|
||||
- Widersprüchliche Einleitungen: LETZTER Satzanfang gewinnt
|
||||
- Konfidenz-Threshold: 0.7 (empirisch anpassbar nach 2 Wochen .45-Daten)
|
||||
- Sammlung empirisch erweitern via Tagesstart
|
||||
|
||||
Usage::
|
||||
|
||||
from .sentence_markers import detect_sentence_marker, SentenceMarkerResult
|
||||
|
||||
result = detect_sentence_marker("Kurze Frage zu etwas anderem: Wie geht das?")
|
||||
if result is not None:
|
||||
print(f"Klasse: {result.marker_class}, Konfidenz: {result.confidence}")
|
||||
print(f"Aktion: {result.action}, Referenz-Topic: {result.referenz_topic}")
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from enum import Enum
|
||||
from typing import Optional, List
|
||||
|
||||
|
||||
class MarkerClass(Enum):
|
||||
"""Erkennungs-Klasse für Satzeinleitungen."""
|
||||
|
||||
HART_THEMENWECHSEL = "hart_themenwechsel"
|
||||
"""Hart-Themenwechsel: Regex reicht, hohe Konfidenz (>0.8)."""
|
||||
|
||||
HART_RUECKBEZUG = "hart_rueckbezug"
|
||||
"""Hart-Rückbezug: Regex + Named-Entity-Extraktion, hohe Konfidenz (>0.8)."""
|
||||
|
||||
WEICH = "weich"
|
||||
"""Weich-Rückbezug/Weich-Wechsel: unsicher, LLM-Validierung nötig (0.3-0.8)."""
|
||||
|
||||
|
||||
@dataclass
|
||||
class SentenceMarkerResult:
|
||||
"""Ergebnis der Satzeinleitungs-Erkennung.
|
||||
|
||||
Attributes:
|
||||
marker_class: Die erkannte Klasse (HART_THEMENWECHSEL, HART_RUECKBEZUG, WEICH).
|
||||
confidence: Konfidenz (0.0-1.0).
|
||||
action: V7-3-Aktion: 'themenwechsel', 'rueckbezug', 'unsicher'.
|
||||
referenz_topic: Extrahiertes Referenz-Topic (nur bei HART_RUECKBEZUG).
|
||||
matched_pattern: Das gematchte Regex-Pattern (für Telemetrie).
|
||||
matched_text: Der gematchte Textausschnitt (für Debugging).
|
||||
"""
|
||||
|
||||
marker_class: MarkerClass
|
||||
confidence: float
|
||||
action: str # 'themenwechsel', 'rueckbezug', 'unsicher'
|
||||
referenz_topic: Optional[str] = None
|
||||
matched_pattern: str = ""
|
||||
matched_text: str = ""
|
||||
|
||||
|
||||
# ── Gruppe A: Hart-Themenwechsel ─────────────────────────────────────────────
|
||||
# Direkte, formelle und charmante/lockere Themenwechsel.
|
||||
# Konfidenz: 0.90 (sehr hoch — Regex reicht).
|
||||
|
||||
HART_THEMENWECHSEL_PATTERNS: List[str] = [
|
||||
# Direkte, formelle Themenwechsel
|
||||
r"kurze\s+frage\s+zu\s+etwas\s+anderem",
|
||||
r"mal\s+ein\s+anderes?\s+thema",
|
||||
r"wechsel\s+zum\s+thema",
|
||||
r"komplett\s+anderes?\s+thema",
|
||||
r"jetzt\s+aber\s+zu",
|
||||
r"ab\s+jetzt\s+geht\s+es\s+um",
|
||||
# Charmante/lockere Themenwechsel
|
||||
r"nur\s+kurz\s+aussetzen",
|
||||
r"darf\s+ich\s+unterbrechen",
|
||||
r"schob.*?ganz\s+was\s+anderes",
|
||||
]
|
||||
|
||||
# ── Gruppe B: Hart-Rückbezug ──────────────────────────────────────────────────
|
||||
# Explizite Rückbezüge auf ein vorheriges Thema.
|
||||
# Konfidenz: 0.90 (sehr hoch — Regex + Named-Entity reicht).
|
||||
|
||||
HART_RUECKBEZUG_PATTERNS: List[str] = [
|
||||
r"lass\s+uns\s+nochmal\s+(?:auf|da(?:rauf|ran|zu))\b",
|
||||
r"nochmal\s+wegen",
|
||||
r"zurück\s+zu",
|
||||
r"wie\s+wir\s+vorhin\s+über",
|
||||
r"bezüglich",
|
||||
r"ich\s+nehme\s+bezug\s+auf",
|
||||
]
|
||||
|
||||
# ── Gruppe C+D: Weich-Muster ──────────────────────────────────────────────────
|
||||
# Assoziative Muster — unsicher, brauchen LLM-Validierung.
|
||||
# Konfidenz: 0.50 (niedrig — LLM muss validieren).
|
||||
|
||||
WEICH_PATTERNS: List[str] = [
|
||||
r"da\s+fällt\s+mir\s+ein",
|
||||
r"in\s+dem\s+zusammenhang",
|
||||
r"a\s+propos",
|
||||
r"übrigens",
|
||||
r"das\s+erinnert\s+mich\s+an",
|
||||
]
|
||||
|
||||
# ── Named-Entity-Extraktion für Rückbezug ─────────────────────────────────────
|
||||
# Extrahiert das Thema aus Rückbezug-Mustern wie:
|
||||
# "Lass uns nochmal auf LAN-Doku zurückkommen." → "LAN-Doku"
|
||||
# "Nochmal wegen DevOps: ..." → "DevOps"
|
||||
# "Zurück zu ProtonBridge: ..." → "ProtonBridge"
|
||||
|
||||
_RUECKBEZUG_TOPIC_PATTERNS: List[re.Pattern] = [
|
||||
# "Lass uns nochmal auf X zurückkommen" / "Lass uns nochmal auf X."
|
||||
re.compile(
|
||||
r"lass\s+uns\s+nochmal\s+auf\s+(.+?)(?:\s+zurückkommen|\s*$|[:,.!?])",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
# "Nochmal wegen X:" / "Nochmal wegen X."
|
||||
re.compile(
|
||||
r"nochmal\s+wegen\s+(.+?)(?:\s*$|[:,.!?])",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
# "Zurück zu X:" / "Zurück zu X."
|
||||
re.compile(
|
||||
r"zurück\s+zu\s+(.+?)(?:\s*$|[:,.!?])",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
# "Wie wir vorhin über X gesprochen haben"
|
||||
re.compile(
|
||||
r"wie\s+wir\s+vorhin\s+über\s+(.+?)(?:\s+gesprochen\s+haben|\s*$|[:,.!?])",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
# "Bezüglich X:" / "Bezüglich X."
|
||||
re.compile(
|
||||
r"bezüglich\s+(.+?)(?:\s*$|[:,.!?])",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
# "Ich nehme Bezug auf unser Gespräch über X:"
|
||||
re.compile(
|
||||
r"ich\s+nehme\s+bezug\s+auf\s+(?:unser\s+gespräch\s+)?(?:über\s+)?(.+?)(?:\s*$|[:,.!?])",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
]
|
||||
|
||||
# ── Konfidenz-Werte pro Klasse ────────────────────────────────────────────────
|
||||
|
||||
_CONFIDENCE_MAP = {
|
||||
MarkerClass.HART_THEMENWECHSEL: 0.90,
|
||||
MarkerClass.HART_RUECKBEZUG: 0.90,
|
||||
MarkerClass.WEICH: 0.50,
|
||||
}
|
||||
|
||||
# ── Action-Map: MarkerClass → V7-3-Aktion ─────────────────────────────────────
|
||||
|
||||
_ACTION_MAP = {
|
||||
MarkerClass.HART_THEMENWECHSEL: "themenwechsel",
|
||||
MarkerClass.HART_RUECKBEZUG: "rueckbezug",
|
||||
MarkerClass.WEICH: "unsicher",
|
||||
}
|
||||
|
||||
|
||||
def _compile_patterns(patterns: List[str]) -> List[re.Pattern]:
|
||||
"""Kompiliere eine Liste von Regex-Strings zu kompilierten Patterns.
|
||||
|
||||
Alle Patterns sind case-insensitive.
|
||||
"""
|
||||
return [re.compile(p, re.IGNORECASE) for p in patterns]
|
||||
|
||||
|
||||
# Kompilierte Patterns (Modul-Level, einmalig kompiliert)
|
||||
_COMPILED_THEMENWECHSEL = _compile_patterns(HART_THEMENWECHSEL_PATTERNS)
|
||||
_COMPILED_RUECKBEZUG = _compile_patterns(HART_RUECKBEZUG_PATTERNS)
|
||||
_COMPILED_WEICH = _compile_patterns(WEICH_PATTERNS)
|
||||
|
||||
|
||||
def _extract_referenz_topic(text: str) -> Optional[str]:
|
||||
"""Extrahiere das Referenz-Topic aus einem Rückbezug-Text.
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext.
|
||||
|
||||
Returns:
|
||||
Topic-Slug (lowercase, Bindestriche) oder None wenn nicht extrahierbar.
|
||||
"""
|
||||
for pattern in _RUECKBEZUG_TOPIC_PATTERNS:
|
||||
match = pattern.search(text)
|
||||
if match:
|
||||
raw_topic = match.group(1).strip()
|
||||
# Bereinige: entferne Satzzeichen am Ende, normalisiere
|
||||
raw_topic = re.sub(r"[.,!?:;]+$", "", raw_topic).strip()
|
||||
if raw_topic:
|
||||
# Normalisiere zu Topic-Slug: lowercase, Leerzeichen → Bindestrich
|
||||
topic = raw_topic.lower().replace(" ", "-")
|
||||
# Entferne Sonderzeichen außer Bindestrich
|
||||
topic = re.sub(r"[^a-z0-9äöüß-]", "", topic)
|
||||
# Entferne führende/abschließende Bindestriche
|
||||
topic = topic.strip("-")
|
||||
if topic:
|
||||
return topic
|
||||
return None
|
||||
|
||||
|
||||
def _find_last_match(
|
||||
text: str,
|
||||
) -> Optional[tuple[re.Match, str, MarkerClass]]:
|
||||
"""Finde den LETZTEN Match über alle drei Klassen hinweg.
|
||||
|
||||
Bei mehreren Treffern gewinnt der letzte (Andreas' Regel:
|
||||
'wer zuletzt spricht, hat recht').
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext.
|
||||
|
||||
Returns:
|
||||
(match, pattern_string, marker_class) oder None.
|
||||
"""
|
||||
last_match: Optional[re.Match] = None
|
||||
last_pattern: str = ""
|
||||
last_class: Optional[MarkerClass] = None
|
||||
last_end: int = -1
|
||||
|
||||
# Themenwechsel
|
||||
for i, pattern in enumerate(_COMPILED_THEMENWECHSEL):
|
||||
for match in pattern.finditer(text):
|
||||
if match.end() > last_end:
|
||||
last_match = match
|
||||
last_end = match.end()
|
||||
last_pattern = HART_THEMENWECHSEL_PATTERNS[i]
|
||||
last_class = MarkerClass.HART_THEMENWECHSEL
|
||||
|
||||
# Rückbezug
|
||||
for i, pattern in enumerate(_COMPILED_RUECKBEZUG):
|
||||
for match in pattern.finditer(text):
|
||||
if match.end() > last_end:
|
||||
last_match = match
|
||||
last_end = match.end()
|
||||
last_pattern = HART_RUECKBEZUG_PATTERNS[i]
|
||||
last_class = MarkerClass.HART_RUECKBEZUG
|
||||
|
||||
# Weich
|
||||
for i, pattern in enumerate(_COMPILED_WEICH):
|
||||
for match in pattern.finditer(text):
|
||||
if match.end() > last_end:
|
||||
last_match = match
|
||||
last_end = match.end()
|
||||
last_pattern = WEICH_PATTERNS[i]
|
||||
last_class = MarkerClass.WEICH
|
||||
|
||||
if last_match is not None and last_class is not None:
|
||||
return (last_match, last_pattern, last_class)
|
||||
return None
|
||||
|
||||
|
||||
def detect_sentence_marker(text: str) -> Optional[SentenceMarkerResult]:
|
||||
"""Erkenne Satzeinleitungen in einem Nachrichtentext (Stufe 0).
|
||||
|
||||
Durchsucht den Text nach Mustern aus drei Klassen:
|
||||
1. Hart-Themenwechsel (höchste Priorität bei Gleichstand)
|
||||
2. Hart-Rückbezug
|
||||
3. Weich-Muster
|
||||
|
||||
Bei mehreren Treffern gewinnt der LETZTE (Andreas' Regel).
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext.
|
||||
|
||||
Returns:
|
||||
SentenceMarkerResult wenn ein Muster erkannt wurde, None sonst.
|
||||
"""
|
||||
if not text or not text.strip():
|
||||
return None
|
||||
|
||||
text = text.strip()
|
||||
|
||||
# ── Alle drei Klassen durchsuchen, letzter Treffer gewinnt ──────────
|
||||
result = _find_last_match(text)
|
||||
|
||||
if result is None:
|
||||
return None
|
||||
|
||||
match, pattern_str, marker_class = result
|
||||
|
||||
# ── Extrahiere Referenz-Topic (nur bei Rückbezug) ──────────────────
|
||||
referenz_topic: Optional[str] = None
|
||||
if marker_class == MarkerClass.HART_RUECKBEZUG:
|
||||
referenz_topic = _extract_referenz_topic(text)
|
||||
|
||||
# ── Bestimme Konfidenz und Aktion ──────────────────────────────────
|
||||
confidence = _CONFIDENCE_MAP.get(marker_class, 0.5)
|
||||
action = _ACTION_MAP.get(marker_class, "unsicher")
|
||||
|
||||
return SentenceMarkerResult(
|
||||
marker_class=marker_class,
|
||||
confidence=confidence,
|
||||
action=action,
|
||||
referenz_topic=referenz_topic,
|
||||
matched_pattern=pattern_str,
|
||||
matched_text=match.group(0),
|
||||
)
|
||||
@@ -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,628 @@
|
||||
"""
|
||||
Tests für FAKT-Speicherort-Dialog beim Onboarding (Thema 3).
|
||||
|
||||
Prüft:
|
||||
- room_map.py: fact_store_strategy, fact_store_created_at Felder + Migration
|
||||
- onboarding.py: Pfad-Validierung, 4-Optionen-Dialog
|
||||
- doc_store.py: set_base_dir()
|
||||
- adapter_integration.py: strategy-aware Instanziierung
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
from plugin.archivar.room_map import (
|
||||
RoomMap,
|
||||
RoomEntry,
|
||||
RoomMapValidationError,
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# Helpers
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
def _make_map_json(
|
||||
rooms: list[dict] | None = None,
|
||||
excluded: list[str] | None = None,
|
||||
fact_store_path: str = "/tmp/test_docs",
|
||||
fact_store_strategy: str | None = None,
|
||||
fact_store_created_at: str | None = None,
|
||||
) -> str:
|
||||
"""Create a minimal valid room-map.json as a string."""
|
||||
data: dict = {
|
||||
"version": 1,
|
||||
"rooms": {},
|
||||
"excluded_rooms": excluded or [],
|
||||
"fact_store_path": fact_store_path,
|
||||
}
|
||||
if fact_store_strategy is not None:
|
||||
data["fact_store_strategy"] = fact_store_strategy
|
||||
if fact_store_created_at is not None:
|
||||
data["fact_store_created_at"] = fact_store_created_at
|
||||
for room in (rooms or []):
|
||||
room_data = {
|
||||
"name": room["name"],
|
||||
"theme": room.get("theme", ""),
|
||||
"catch_all": room.get("catch_all", False),
|
||||
}
|
||||
if "keywords_100" in room or "keywords_context" in room:
|
||||
room_data["keywords_100"] = room.get("keywords_100", [])
|
||||
room_data["keywords_context"] = room.get("keywords_context", [])
|
||||
else:
|
||||
room_data["keywords"] = room.get("keywords", [])
|
||||
data["rooms"][room["room_id"]] = room_data
|
||||
return json.dumps(data)
|
||||
|
||||
|
||||
def _tmp_map(content: str) -> Path:
|
||||
tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False, encoding="utf-8")
|
||||
tmp.write(content)
|
||||
tmp.close()
|
||||
return Path(tmp.name)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# RoomMap: fact_store_strategy + fact_store_created_at
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestFactStoreFields:
|
||||
"""RoomMap: fact_store_strategy und fact_store_created_at."""
|
||||
|
||||
def test_load_with_strategy_auto(self):
|
||||
"""Map mit fact_store_strategy='auto' laden."""
|
||||
json_str = _make_map_json(
|
||||
rooms=[
|
||||
{"room_id": "r1", "name": "#Dev", "theme": "dev", "keywords": []},
|
||||
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||
],
|
||||
fact_store_strategy="auto",
|
||||
fact_store_created_at="2026-07-18T12:00:00",
|
||||
)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
rm = RoomMap.load(path)
|
||||
assert rm.fact_store_strategy == "auto"
|
||||
assert rm.fact_store_created_at == "2026-07-18T12:00:00"
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def test_load_with_strategy_manual(self):
|
||||
"""Map mit fact_store_strategy='manual' laden."""
|
||||
json_str = _make_map_json(
|
||||
rooms=[
|
||||
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||
],
|
||||
fact_store_strategy="manual",
|
||||
)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
rm = RoomMap.load(path)
|
||||
assert rm.fact_store_strategy == "manual"
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def test_load_with_strategy_none(self):
|
||||
"""Map mit fact_store_strategy='none' laden."""
|
||||
json_str = _make_map_json(
|
||||
rooms=[
|
||||
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||
],
|
||||
fact_store_strategy="none",
|
||||
)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
rm = RoomMap.load(path)
|
||||
assert rm.fact_store_strategy == "none"
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def test_migration_no_strategy_defaults_to_manual(self):
|
||||
"""Bestehende Installation ohne strategy → 'manual' (Migration)."""
|
||||
json_str = _make_map_json(
|
||||
rooms=[
|
||||
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||
],
|
||||
# KEIN fact_store_strategy gesetzt
|
||||
)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
rm = RoomMap.load(path)
|
||||
assert rm.fact_store_strategy == "manual", (
|
||||
"Migration: Bestehende Installationen ohne strategy → 'manual'"
|
||||
)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def test_migration_no_created_at_defaults_to_none(self):
|
||||
"""Bestehende Installation ohne created_at → None."""
|
||||
json_str = _make_map_json(
|
||||
rooms=[
|
||||
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||
],
|
||||
)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
rm = RoomMap.load(path)
|
||||
assert rm.fact_store_created_at is None
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def test_save_persists_strategy_and_created_at(self):
|
||||
"""RoomMap.save() persistiert fact_store_strategy und fact_store_created_at."""
|
||||
json_str = _make_map_json(
|
||||
rooms=[
|
||||
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||
],
|
||||
fact_store_strategy="auto",
|
||||
fact_store_created_at="2026-07-18T12:00:00",
|
||||
)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
rm = RoomMap.load(path)
|
||||
# Ändere die Felder
|
||||
rm.set_fact_store_strategy("manual")
|
||||
rm.set_fact_store_created_at("2026-07-18T13:00:00")
|
||||
|
||||
# Speichere
|
||||
RoomMap.save(rm, path)
|
||||
|
||||
# Lade neu und prüfe
|
||||
rm2 = RoomMap.load(path)
|
||||
assert rm2.fact_store_strategy == "manual"
|
||||
assert rm2.fact_store_created_at == "2026-07-18T13:00:00"
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def test_set_fact_store_strategy_invalid_raises(self):
|
||||
"""Ungültige strategy → ValueError."""
|
||||
json_str = _make_map_json(
|
||||
rooms=[
|
||||
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||
],
|
||||
)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
rm = RoomMap.load(path)
|
||||
with pytest.raises(ValueError, match="Invalid fact_store_strategy"):
|
||||
rm.set_fact_store_strategy("invalid")
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def test_reload_preserves_strategy_fields(self):
|
||||
"""reload() aktualisiert fact_store_strategy und fact_store_created_at."""
|
||||
json_str = _make_map_json(
|
||||
rooms=[
|
||||
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||
],
|
||||
fact_store_strategy="auto",
|
||||
fact_store_created_at="2026-07-18T12:00:00",
|
||||
)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
rm = RoomMap.load(path)
|
||||
# Ändere die Datei auf Disk
|
||||
modified = json.loads(json_str)
|
||||
modified["fact_store_strategy"] = "none"
|
||||
modified["fact_store_created_at"] = "2026-07-18T14:00:00"
|
||||
with open(path, "w") as f:
|
||||
json.dump(modified, f)
|
||||
|
||||
rm.reload(path)
|
||||
assert rm.fact_store_strategy == "none"
|
||||
assert rm.fact_store_created_at == "2026-07-18T14:00:00"
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# Pfad-Validierung (onboarding.py)
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestFactStorePathValidation:
|
||||
"""Pfad-Validierung für den FAKT-Speicherort-Dialog."""
|
||||
|
||||
def test_validate_absolute_path_ok(self):
|
||||
"""Absoluter Pfad ist gültig."""
|
||||
from plugin.archivar.onboarding import validate_fact_store_path
|
||||
result = validate_fact_store_path("/tmp/test_fakt_store")
|
||||
assert result["valid"] is True
|
||||
assert result["error"] is None
|
||||
|
||||
def test_validate_relative_path_fails(self):
|
||||
"""Relativer Pfad wird abgelehnt."""
|
||||
from plugin.archivar.onboarding import validate_fact_store_path
|
||||
result = validate_fact_store_path("relative/path")
|
||||
assert result["valid"] is False
|
||||
assert "absolut" in result["error"].lower()
|
||||
|
||||
def test_validate_path_traversal_fails(self):
|
||||
"""Path-Traversal mit '..' wird abgelehnt."""
|
||||
from plugin.archivar.onboarding import validate_fact_store_path
|
||||
result = validate_fact_store_path("/home/../etc/passwd")
|
||||
assert result["valid"] is False
|
||||
assert ".." in result["error"].lower() or "traversal" in result["error"].lower()
|
||||
|
||||
def test_validate_system_dir_blocked(self):
|
||||
"""System-Verzeichnisse werden blockiert."""
|
||||
from plugin.archivar.onboarding import validate_fact_store_path
|
||||
for blocked in ["/etc/config", "/var/data", "/usr/local", "/boot/efi", "/sys/class", "/proc/cpuinfo"]:
|
||||
result = validate_fact_store_path(blocked)
|
||||
assert result["valid"] is False, f"Should block {blocked}"
|
||||
assert "system" in result["error"].lower() or "blockiert" in result["error"].lower()
|
||||
|
||||
def test_validate_home_relative_normalized(self):
|
||||
"""HOME-relativer Pfad wird normalisiert."""
|
||||
from plugin.archivar.onboarding import validate_fact_store_path
|
||||
result = validate_fact_store_path("~/.hermes/wissenssammlung")
|
||||
assert result["valid"] is True
|
||||
assert result["normalized_path"] is not None
|
||||
assert result["normalized_path"].startswith("/")
|
||||
assert "~" not in result["normalized_path"]
|
||||
|
||||
def test_validate_empty_path_fails(self):
|
||||
"""Leerer Pfad wird abgelehnt."""
|
||||
from plugin.archivar.onboarding import validate_fact_store_path
|
||||
result = validate_fact_store_path("")
|
||||
assert result["valid"] is False
|
||||
|
||||
def test_validate_path_with_spaces_ok(self):
|
||||
"""Pfad mit Leerzeichen ist gültig (wird escaped)."""
|
||||
from plugin.archivar.onboarding import validate_fact_store_path
|
||||
result = validate_fact_store_path("/tmp/my fact store")
|
||||
assert result["valid"] is True
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# doc_store.py: set_base_dir()
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestDocStoreSetBaseDir:
|
||||
"""DocumentationStore.set_base_dir() Methode."""
|
||||
|
||||
def test_set_base_dir_changes_path(self):
|
||||
"""set_base_dir() ändert das Basisverzeichnis."""
|
||||
from plugin.archivar.doc_store import DocumentationStore
|
||||
store = DocumentationStore(base_dir=Path("/tmp/old_docs"))
|
||||
assert str(store.base_dir) == "/tmp/old_docs"
|
||||
|
||||
store.set_base_dir(Path("/tmp/new_docs"))
|
||||
assert str(store.base_dir) == "/tmp/new_docs"
|
||||
|
||||
def test_set_base_dir_creates_directory(self):
|
||||
"""set_base_dir() erstellt das Verzeichnis nicht (nur store() tut das)."""
|
||||
from plugin.archivar.doc_store import DocumentationStore
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
new_dir = Path(tmpdir) / "subdir" / "docs"
|
||||
store = DocumentationStore(base_dir=Path(tmpdir))
|
||||
store.set_base_dir(new_dir)
|
||||
# set_base_dir soll NUR den Pfad setzen, NICHT mkdir
|
||||
assert str(store.base_dir) == str(new_dir)
|
||||
# Verzeichnis existiert noch nicht (wird erst bei store() erstellt)
|
||||
assert not new_dir.exists()
|
||||
|
||||
def test_store_uses_new_base_dir_after_set(self):
|
||||
"""Nach set_base_dir() schreibt store() ins neue Verzeichnis."""
|
||||
from plugin.archivar.doc_store import DocumentationStore
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
new_dir = Path(tmpdir) / "fakt_store"
|
||||
store = DocumentationStore(base_dir=Path(tmpdir))
|
||||
store.set_base_dir(new_dir)
|
||||
|
||||
path = store.store(
|
||||
text="Test message",
|
||||
category="FAKT",
|
||||
confidence=0.95,
|
||||
reason="test",
|
||||
)
|
||||
assert new_dir.name in path
|
||||
assert Path(path).exists()
|
||||
assert Path(path).parent.name == "fakt"
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# adapter_integration.py: strategy-aware Instanziierung
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestStrategyAwareDocStore:
|
||||
"""ArchivarMessageHandler: strategy-aware DocumentationStore."""
|
||||
|
||||
def test_strategy_none_no_doc_store(self):
|
||||
"""Bei strategy='none' wird kein DocumentationStore instanziiert."""
|
||||
from plugin.archivar.adapter_integration import ArchivarMessageHandler
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
# Erstelle eine RoomMap mit strategy='none'
|
||||
json_str = _make_map_json(
|
||||
rooms=[
|
||||
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||
],
|
||||
fact_store_strategy="none",
|
||||
)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
with patch('plugin.archivar.adapter_integration.ROOM_MAP_PATH', str(path)):
|
||||
with patch('plugin.archivar.room_map.DEFAULT_MAP_PATH', str(path)):
|
||||
handler = ArchivarMessageHandler()
|
||||
# Bei strategy='none' sollte _doc_store None sein
|
||||
assert handler._doc_store is None, (
|
||||
"Bei strategy='none' soll kein DocumentationStore erstellt werden"
|
||||
)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def test_strategy_auto_creates_doc_store(self):
|
||||
"""Bei strategy='auto' wird DocumentationStore erstellt."""
|
||||
from plugin.archivar.adapter_integration import ArchivarMessageHandler
|
||||
from unittest.mock import patch
|
||||
|
||||
json_str = _make_map_json(
|
||||
rooms=[
|
||||
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||
],
|
||||
fact_store_strategy="auto",
|
||||
)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
with patch('plugin.archivar.adapter_integration.ROOM_MAP_PATH', str(path)):
|
||||
with patch('plugin.archivar.room_map.DEFAULT_MAP_PATH', str(path)):
|
||||
handler = ArchivarMessageHandler()
|
||||
assert handler._doc_store is not None, (
|
||||
"Bei strategy='auto' soll DocumentationStore erstellt werden"
|
||||
)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def test_strategy_manual_creates_doc_store(self):
|
||||
"""Bei strategy='manual' wird DocumentationStore erstellt."""
|
||||
from plugin.archivar.adapter_integration import ArchivarMessageHandler
|
||||
from unittest.mock import patch
|
||||
|
||||
json_str = _make_map_json(
|
||||
rooms=[
|
||||
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||
],
|
||||
fact_store_strategy="manual",
|
||||
)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
with patch('plugin.archivar.adapter_integration.ROOM_MAP_PATH', str(path)):
|
||||
with patch('plugin.archivar.room_map.DEFAULT_MAP_PATH', str(path)):
|
||||
handler = ArchivarMessageHandler()
|
||||
assert handler._doc_store is not None, (
|
||||
"Bei strategy='manual' soll DocumentationStore erstellt werden"
|
||||
)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
def test_strategy_auto_mkdir_if_missing(self):
|
||||
"""Bei strategy='auto' wird mkdir -p ausgeführt falls Pfad nicht existiert."""
|
||||
from plugin.archivar.adapter_integration import ArchivarMessageHandler
|
||||
from unittest.mock import patch
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
nonexistent = Path(tmpdir) / "nonexistent" / "fakt"
|
||||
json_str = _make_map_json(
|
||||
rooms=[
|
||||
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
|
||||
],
|
||||
fact_store_path=str(nonexistent),
|
||||
fact_store_strategy="auto",
|
||||
)
|
||||
path = _tmp_map(json_str)
|
||||
try:
|
||||
with patch('plugin.archivar.adapter_integration.ROOM_MAP_PATH', str(path)):
|
||||
with patch('plugin.archivar.room_map.DEFAULT_MAP_PATH', str(path)):
|
||||
handler = ArchivarMessageHandler()
|
||||
# Bei strategy='auto' soll das Verzeichnis erstellt worden sein
|
||||
assert nonexistent.exists(), (
|
||||
"Bei strategy='auto' soll mkdir -p ausgeführt werden"
|
||||
)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
# Adapter-Level: FAKT-Speicherort-Buttons im is_onboarding-Check (P0-Fix)
|
||||
# ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestFaktStoreOnboardingAdapter:
|
||||
"""Adapter-Level: FAKT-Speicherort-Buttons werden als Onboarding erkannt.
|
||||
|
||||
P0-Bug: Der is_onboarding-Check in _process_incoming (Zeile 1516-1527)
|
||||
hatte keine Bedingung für die fakt_store-Phase. FAKT-Buttons (FAKT::1️⃣ etc.)
|
||||
fielen durch und wurden nicht als Onboarding-Antwort verarbeitet.
|
||||
|
||||
Fix: Zeile 1522 — ``or (is_operator_room and self._onboarding_state.get("phase") == "fakt_store")``
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def adapter(self, tmp_path):
|
||||
"""Build a mock RocketChatAdapter with fakt_store onboarding state."""
|
||||
import asyncio
|
||||
import threading
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
os.environ["MULTIROOM_AGENT"] = "true"
|
||||
os.environ["ARCHIVAR_STATE_PATH"] = str(tmp_path / "archivar_state.json")
|
||||
os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com"
|
||||
os.environ["ROCKETCHAT_USER"] = "testbot"
|
||||
os.environ["ROCKETCHAT_PASSWORD"] = "testpass"
|
||||
|
||||
# Create a minimal room-map.json
|
||||
map_path = tmp_path / "room-map.json"
|
||||
map_data = {
|
||||
"version": 1,
|
||||
"rooms": {
|
||||
"admin": {
|
||||
"name": "DM Admin",
|
||||
"theme": "admin",
|
||||
"keywords": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": str(tmp_path / "docs"),
|
||||
}
|
||||
map_path.write_text(json.dumps(map_data))
|
||||
os.environ["ARCHIVAR_ROOM_MAP_PATH"] = str(map_path)
|
||||
|
||||
from plugin.adapter import RocketChatAdapter, RocketChatREST
|
||||
from archivar.conversation_history import ConversationHistory
|
||||
from archivar.multiroom_context import MultiRoomContextRing
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
from archivar.room_map import RoomMap
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
|
||||
adapter.config = MagicMock()
|
||||
adapter.config.extra = {}
|
||||
adapter.platform = "rocketchat"
|
||||
adapter.base_url = os.getenv("ROCKETCHAT_BASE_URL", "")
|
||||
adapter.user = os.getenv("ROCKETCHAT_USER", "")
|
||||
adapter.password = os.getenv("ROCKETCHAT_PASSWORD", "")
|
||||
adapter.rest = RocketChatREST(adapter.base_url)
|
||||
adapter.ddp = None
|
||||
adapter._auth_token = None
|
||||
adapter._user_id = None
|
||||
adapter._rooms = []
|
||||
adapter._subscribed_rooms = set()
|
||||
adapter._listen_task = None
|
||||
adapter._status_timer = None
|
||||
adapter._last_activity = 0.0
|
||||
adapter._shutdown_event = threading.Event()
|
||||
adapter._room_info = {}
|
||||
adapter._pending_clarifies = {}
|
||||
adapter._user_rooms = {}
|
||||
adapter._rooms_with_pending_questions = set()
|
||||
adapter._excluded_room_ids = set()
|
||||
adapter._last_server_activity = 0.0
|
||||
adapter._health_check_timer = None
|
||||
adapter._last_ddp_ping_ok = False
|
||||
adapter._running = False
|
||||
|
||||
adapter._conversation_history = ConversationHistory(max_size=10)
|
||||
adapter._multiroom_context = MultiRoomContextRing(max_entries=10)
|
||||
adapter.archivar = ArchivarMessageHandler(
|
||||
send_callback=lambda *a, **kw: None,
|
||||
button_send_callback=lambda *a, **kw: None,
|
||||
conversation_history=adapter._conversation_history,
|
||||
)
|
||||
adapter.archivar._room_map = RoomMap.load(Path(str(map_path)))
|
||||
|
||||
adapter._pending_move_requests = {}
|
||||
adapter._session_room_preferences = {}
|
||||
adapter._recent_auto_routes = {}
|
||||
adapter._explicit_switch_sticky = {}
|
||||
adapter._clarify_state = {}
|
||||
adapter._onboarding_state = {}
|
||||
adapter._room_map_summary = ""
|
||||
|
||||
mock_rest = MagicMock(spec=RocketChatREST)
|
||||
mock_rest.auth_token = "fake-token"
|
||||
mock_rest.user_id = "fake-user-id"
|
||||
mock_rest.post_message = MagicMock(return_value="msg_12345")
|
||||
mock_rest.get_rooms = MagicMock(return_value=[
|
||||
{"id": "dm_room", "name": "DM Admin", "type": "d"},
|
||||
])
|
||||
adapter.rest = mock_rest
|
||||
|
||||
# Mock _process_onboarding_response to track calls
|
||||
adapter._process_onboarding_response = AsyncMock()
|
||||
adapter._post_message_with_retry = AsyncMock(return_value=True)
|
||||
|
||||
# Set onboarding_active in archivar stats
|
||||
adapter.archivar._stats["onboarding_active"] = True
|
||||
|
||||
return adapter
|
||||
|
||||
def test_fakt_button_standard_recognized_as_onboarding(self, adapter):
|
||||
"""FAKT::1️⃣ Standard im Operator-Room → is_onboarding=True → _process_onboarding_response aufgerufen."""
|
||||
adapter._onboarding_state = {
|
||||
"phase": "fakt_store",
|
||||
"operator_room_id": "dm_room",
|
||||
}
|
||||
|
||||
msg_obj = {
|
||||
"msg": "FAKT::1️⃣ Standard",
|
||||
"rid": "dm_room",
|
||||
"u": {"username": "bernd"},
|
||||
"_id": "msg_001",
|
||||
}
|
||||
|
||||
asyncio.run(adapter._process_incoming(msg_obj))
|
||||
|
||||
adapter._process_onboarding_response.assert_called_once()
|
||||
call_args = adapter._process_onboarding_response.call_args
|
||||
assert call_args[0][0] == "FAKT::1️⃣ Standard"
|
||||
assert call_args[0][1] == "dm_room"
|
||||
|
||||
def test_fakt_button_new_path_recognized_as_onboarding(self, adapter):
|
||||
"""FAKT::2️⃣ Neuer Ort im Operator-Room → is_onboarding=True."""
|
||||
adapter._onboarding_state = {
|
||||
"phase": "fakt_store",
|
||||
"operator_room_id": "dm_room",
|
||||
}
|
||||
|
||||
msg_obj = {
|
||||
"msg": "FAKT::2️⃣ Neuer Ort",
|
||||
"rid": "dm_room",
|
||||
"u": {"username": "bernd"},
|
||||
"_id": "msg_002",
|
||||
}
|
||||
|
||||
asyncio.run(adapter._process_incoming(msg_obj))
|
||||
|
||||
adapter._process_onboarding_response.assert_called_once()
|
||||
call_args = adapter._process_onboarding_response.call_args
|
||||
assert call_args[0][0] == "FAKT::2️⃣ Neuer Ort"
|
||||
|
||||
def test_fakt_button_none_recognized_as_onboarding(self, adapter):
|
||||
"""FAKT::4️⃣ Keine Sammlung im Operator-Room → is_onboarding=True."""
|
||||
adapter._onboarding_state = {
|
||||
"phase": "fakt_store",
|
||||
"operator_room_id": "dm_room",
|
||||
}
|
||||
|
||||
msg_obj = {
|
||||
"msg": "FAKT::4️⃣ Keine Sammlung",
|
||||
"rid": "dm_room",
|
||||
"u": {"username": "bernd"},
|
||||
"_id": "msg_003",
|
||||
}
|
||||
|
||||
asyncio.run(adapter._process_incoming(msg_obj))
|
||||
|
||||
adapter._process_onboarding_response.assert_called_once()
|
||||
call_args = adapter._process_onboarding_response.call_args
|
||||
assert call_args[0][0] == "FAKT::4️⃣ Keine Sammlung"
|
||||
|
||||
def test_fakt_button_wrong_room_not_onboarding(self, adapter):
|
||||
"""FAKT-Button in falschem Raum → is_onboarding=False → _process_onboarding_response NICHT aufgerufen."""
|
||||
adapter._onboarding_state = {
|
||||
"phase": "fakt_store",
|
||||
"operator_room_id": "dm_room",
|
||||
}
|
||||
|
||||
# Nachricht kommt aus einem anderen Raum (#general)
|
||||
msg_obj = {
|
||||
"msg": "FAKT::1️⃣ Standard",
|
||||
"rid": "general_room",
|
||||
"u": {"username": "bernd"},
|
||||
"_id": "msg_004",
|
||||
}
|
||||
|
||||
asyncio.run(adapter._process_incoming(msg_obj))
|
||||
|
||||
adapter._process_onboarding_response.assert_not_called()
|
||||
@@ -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
|
||||
@@ -0,0 +1,394 @@
|
||||
"""
|
||||
A1b: Satzeinleitungs-Erkennung — Unit-Tests für sentence_markers.py.
|
||||
|
||||
Tests für:
|
||||
- Alle 3 Erkennungs-Klassen (Hart-Themenwechsel, Hart-Rückbezug, Weich)
|
||||
- Jedes einzelne Muster aus Rainers Sammlung
|
||||
- Konfidenz-Werte pro Klasse
|
||||
- Named-Entity-Extraktion bei Rückbezug
|
||||
- False-Positive-Vermeidung (keine falschen Treffer)
|
||||
- Leerer Text, Sonderzeichen, Edge Cases
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
||||
|
||||
from sentence_markers import (
|
||||
detect_sentence_marker,
|
||||
SentenceMarkerResult,
|
||||
MarkerClass,
|
||||
HART_THEMENWECHSEL_PATTERNS,
|
||||
HART_RUECKBEZUG_PATTERNS,
|
||||
WEICH_PATTERNS,
|
||||
)
|
||||
|
||||
|
||||
class TestMarkerClass(unittest.TestCase):
|
||||
"""MarkerClass Enum Tests."""
|
||||
|
||||
def test_three_classes_exist(self):
|
||||
self.assertEqual(MarkerClass.HART_THEMENWECHSEL.value, "hart_themenwechsel")
|
||||
self.assertEqual(MarkerClass.HART_RUECKBEZUG.value, "hart_rueckbezug")
|
||||
self.assertEqual(MarkerClass.WEICH.value, "weich")
|
||||
|
||||
|
||||
class TestHartThemenwechselPatterns(unittest.TestCase):
|
||||
"""Gruppe A: Hart-Themenwechsel — Regex reicht, hohe Konfidenz."""
|
||||
|
||||
def test_kurze_frage_zu_etwas_anderem(self):
|
||||
result = detect_sentence_marker("Kurze Frage zu etwas anderem: Wie geht das?")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_THEMENWECHSEL)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
|
||||
def test_mal_ein_anderes_thema(self):
|
||||
result = detect_sentence_marker("Mal ein anderes Thema: Hast du den Stand?")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_THEMENWECHSEL)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
|
||||
def test_wechsel_zum_thema(self):
|
||||
result = detect_sentence_marker("Wechsel zum Thema LAN-Doku: Was fehlt noch?")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_THEMENWECHSEL)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
|
||||
def test_komplett_anderes_thema(self):
|
||||
result = detect_sentence_marker("Komplett anderes Thema: Wann ist das Meeting?")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_THEMENWECHSEL)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
|
||||
def test_jetzt_aber_zu(self):
|
||||
result = detect_sentence_marker("Jetzt aber zu DevOps: Wie steht der Pipeline?")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_THEMENWECHSEL)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
|
||||
def test_ab_jetzt_geht_es_um(self):
|
||||
result = detect_sentence_marker("Ab jetzt geht es um die Doku: Was fehlt?")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_THEMENWECHSEL)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
|
||||
def test_nur_kurz_aussetzen(self):
|
||||
result = detect_sentence_marker("Nur kurz aussetzen, eine Frage: Wie geht das?")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_THEMENWECHSEL)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
|
||||
def test_darf_ich_unterbrechen(self):
|
||||
result = detect_sentence_marker("Darf ich unterbrechen? Ich habe eine Frage.")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_THEMENWECHSEL)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
|
||||
def test_schob_ganz_was_anderes(self):
|
||||
result = detect_sentence_marker("Schob, ganz was anderes: Wie läuft's?")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_THEMENWECHSEL)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
|
||||
def test_case_insensitive_themenwechsel(self):
|
||||
result = detect_sentence_marker("mal ein ANDERES THEMA: test")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_THEMENWECHSEL)
|
||||
|
||||
def test_no_false_positive_normal_text(self):
|
||||
"""Normaler Text ohne Einleitung → kein Treffer."""
|
||||
result = detect_sentence_marker("Kannst du mir die Doku zeigen?")
|
||||
self.assertIsNone(result)
|
||||
|
||||
def test_no_false_positive_question(self):
|
||||
result = detect_sentence_marker("Was ist der Status vom Plugin?")
|
||||
self.assertIsNone(result)
|
||||
|
||||
|
||||
class TestHartRueckbezugPatterns(unittest.TestCase):
|
||||
"""Gruppe B: Hart-Rückbezug — Regex + Named-Entity-Extraktion."""
|
||||
|
||||
def test_lass_uns_nochmal_auf_zurueckkommen(self):
|
||||
result = detect_sentence_marker(
|
||||
"Lass uns nochmal auf LAN-Doku zurückkommen."
|
||||
)
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_RUECKBEZUG)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
self.assertIsNotNone(result.referenz_topic)
|
||||
self.assertIn("lan-doku", result.referenz_topic.lower())
|
||||
|
||||
def test_nochmal_wegen(self):
|
||||
result = detect_sentence_marker("Nochmal wegen DevOps: Wie war der Stand?")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_RUECKBEZUG)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
self.assertIsNotNone(result.referenz_topic)
|
||||
self.assertIn("devops", result.referenz_topic.lower())
|
||||
|
||||
def test_zurueck_zu(self):
|
||||
result = detect_sentence_marker("Zurück zu ProtonBridge: Der Bug ist noch da.")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_RUECKBEZUG)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
self.assertIsNotNone(result.referenz_topic)
|
||||
self.assertIn("protonbridge", result.referenz_topic.lower())
|
||||
|
||||
def test_wie_wir_vorhin_ueber_gesprochen_haben(self):
|
||||
result = detect_sentence_marker(
|
||||
"Wie wir vorhin über LAN-Doku gesprochen haben: Der Stand ist..."
|
||||
)
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_RUECKBEZUG)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
self.assertIsNotNone(result.referenz_topic)
|
||||
self.assertIn("lan-doku", result.referenz_topic.lower())
|
||||
|
||||
def test_bezueglich(self):
|
||||
result = detect_sentence_marker("Bezüglich RC-Plugin: Gibt's ein Update?")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_RUECKBEZUG)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
self.assertIsNotNone(result.referenz_topic)
|
||||
self.assertIn("rc-plugin", result.referenz_topic.lower())
|
||||
|
||||
def test_ich_nehme_bezug_auf(self):
|
||||
result = detect_sentence_marker(
|
||||
"Ich nehme Bezug auf unser Gespräch über BAT-Team: Wer macht was?"
|
||||
)
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_RUECKBEZUG)
|
||||
self.assertGreaterEqual(result.confidence, 0.8)
|
||||
self.assertIsNotNone(result.referenz_topic)
|
||||
self.assertIn("bat-team", result.referenz_topic.lower())
|
||||
|
||||
def test_rueckbezug_case_insensitive(self):
|
||||
result = detect_sentence_marker("LASS UNS NOCHMAL AUF LAN-DOKU ZURÜCKKOMMEN.")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_RUECKBEZUG)
|
||||
|
||||
def test_rueckbezug_no_topic_extracted(self):
|
||||
"""Rückbezug ohne erkennbares Topic → trotzdem erkannt, topic=None."""
|
||||
result = detect_sentence_marker("Lass uns nochmal darauf zurückkommen.")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_RUECKBEZUG)
|
||||
# Kein Topic extrahierbar
|
||||
self.assertIsNone(result.referenz_topic)
|
||||
|
||||
def test_no_false_positive_normal_question(self):
|
||||
result = detect_sentence_marker("Kannst du mir nochmal die Doku zeigen?")
|
||||
# 'nochmal' allein ist kein Rückbezug-Muster
|
||||
self.assertIsNone(result)
|
||||
|
||||
|
||||
class TestWeichPatterns(unittest.TestCase):
|
||||
"""Gruppe C+D: Weich-Muster — niedrige Konfidenz, LLM-Validierung nötig."""
|
||||
|
||||
def test_da_faellt_mir_ein(self):
|
||||
result = detect_sentence_marker("Da fällt mir ein, wir müssen noch die Doku updaten.")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.WEICH)
|
||||
self.assertLess(result.confidence, 0.8)
|
||||
self.assertGreaterEqual(result.confidence, 0.3)
|
||||
|
||||
def test_in_dem_zusammenhang(self):
|
||||
result = detect_sentence_marker("In dem Zusammenhang — was ist mit dem Gateway?")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.WEICH)
|
||||
self.assertLess(result.confidence, 0.8)
|
||||
self.assertGreaterEqual(result.confidence, 0.3)
|
||||
|
||||
def test_a_propos(self):
|
||||
result = detect_sentence_marker("A propos LAN-Doku, hast du den neuen Stand?")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.WEICH)
|
||||
self.assertLess(result.confidence, 0.8)
|
||||
self.assertGreaterEqual(result.confidence, 0.3)
|
||||
|
||||
def test_uebrigens(self):
|
||||
result = detect_sentence_marker("Übrigens, das Meeting ist verschoben.")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.WEICH)
|
||||
self.assertLess(result.confidence, 0.8)
|
||||
self.assertGreaterEqual(result.confidence, 0.3)
|
||||
|
||||
def test_das_erinnert_mich_an(self):
|
||||
result = detect_sentence_marker("Das erinnert mich an unser DevOps-Problem.")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.WEICH)
|
||||
self.assertLess(result.confidence, 0.8)
|
||||
self.assertGreaterEqual(result.confidence, 0.3)
|
||||
|
||||
def test_weich_case_insensitive(self):
|
||||
result = detect_sentence_marker("DA FÄLLT MIR EIN, wir müssen noch was machen.")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.WEICH)
|
||||
|
||||
def test_no_false_positive_weich(self):
|
||||
"""Normaler Text ohne weiche Einleitung → kein Treffer."""
|
||||
result = detect_sentence_marker("Mir fällt auf, dass der Code nicht läuft.")
|
||||
# 'Mir fällt auf' ist NICHT 'Da fällt mir ein'
|
||||
self.assertIsNone(result)
|
||||
|
||||
|
||||
class TestEdgeCases(unittest.TestCase):
|
||||
"""Edge Cases für sentence_markers."""
|
||||
|
||||
def test_empty_text(self):
|
||||
self.assertIsNone(detect_sentence_marker(""))
|
||||
|
||||
def test_whitespace_only(self):
|
||||
self.assertIsNone(detect_sentence_marker(" "))
|
||||
|
||||
def test_very_short_text(self):
|
||||
self.assertIsNone(detect_sentence_marker("Hi"))
|
||||
|
||||
def test_marker_in_middle_of_text(self):
|
||||
"""Marker mitten im Text (nicht am Anfang) wird trotzdem erkannt."""
|
||||
result = detect_sentence_marker(
|
||||
"Ich wollte sagen: Kurze Frage zu etwas anderem: Wie geht das?"
|
||||
)
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_THEMENWECHSEL)
|
||||
|
||||
def test_multiple_markers_last_wins(self):
|
||||
"""Bei mehreren Markern: letzter gewinnt (Andreas' Regel)."""
|
||||
result = detect_sentence_marker(
|
||||
"Kurze Frage zu etwas anderem: Lass uns nochmal auf LAN-Doku zurückkommen."
|
||||
)
|
||||
self.assertIsNotNone(result)
|
||||
# Letzter Marker ist HART_RUECKBEZUG
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_RUECKBEZUG)
|
||||
|
||||
def test_themenwechsel_then_rueckbezug_last_wins(self):
|
||||
"""Themenwechsel dann Rückbezug → Rückbezug gewinnt."""
|
||||
result = detect_sentence_marker(
|
||||
"Mal ein anderes Thema: Nein, lass uns nochmal auf DevOps zurückkommen."
|
||||
)
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_RUECKBEZUG)
|
||||
|
||||
def test_sentence_marker_result_fields(self):
|
||||
"""Alle Felder von SentenceMarkerResult sind gesetzt."""
|
||||
result = detect_sentence_marker("Kurze Frage zu etwas anderem: Test")
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(result.marker_class, MarkerClass.HART_THEMENWECHSEL)
|
||||
self.assertIsInstance(result.confidence, float)
|
||||
self.assertIsInstance(result.action, str)
|
||||
self.assertIn(result.action, ["themenwechsel", "rueckbezug", "unsicher"])
|
||||
|
||||
|
||||
class TestConfidenceThresholds(unittest.TestCase):
|
||||
"""Konfidenz-Schwellenwerte pro Klasse."""
|
||||
|
||||
def test_hart_themenwechsel_confidence_above_08(self):
|
||||
for text in [
|
||||
"Kurze Frage zu etwas anderem: Test",
|
||||
"Mal ein anderes Thema: Test",
|
||||
"Komplett anderes Thema: Test",
|
||||
]:
|
||||
result = detect_sentence_marker(text)
|
||||
self.assertIsNotNone(result, f"Kein Treffer für: {text}")
|
||||
self.assertGreaterEqual(
|
||||
result.confidence, 0.8,
|
||||
f"Konfidenz {result.confidence} < 0.8 für: {text}"
|
||||
)
|
||||
|
||||
def test_hart_rueckbezug_confidence_above_08(self):
|
||||
for text in [
|
||||
"Lass uns nochmal auf LAN-Doku zurückkommen.",
|
||||
"Nochmal wegen DevOps: Update?",
|
||||
"Zurück zu ProtonBridge: Status?",
|
||||
]:
|
||||
result = detect_sentence_marker(text)
|
||||
self.assertIsNotNone(result, f"Kein Treffer für: {text}")
|
||||
self.assertGreaterEqual(
|
||||
result.confidence, 0.8,
|
||||
f"Konfidenz {result.confidence} < 0.8 für: {text}"
|
||||
)
|
||||
|
||||
def test_weich_confidence_between_03_and_08(self):
|
||||
for text in [
|
||||
"Da fällt mir ein, wir müssen noch was machen.",
|
||||
"In dem Zusammenhang — was ist mit dem Gateway?",
|
||||
"Übrigens, das Meeting ist verschoben.",
|
||||
]:
|
||||
result = detect_sentence_marker(text)
|
||||
self.assertIsNotNone(result, f"Kein Treffer für: {text}")
|
||||
self.assertGreaterEqual(
|
||||
result.confidence, 0.3,
|
||||
f"Konfidenz {result.confidence} < 0.3 für: {text}"
|
||||
)
|
||||
self.assertLess(
|
||||
result.confidence, 0.8,
|
||||
f"Konfidenz {result.confidence} >= 0.8 für weich: {text}"
|
||||
)
|
||||
|
||||
|
||||
class TestAllPatternsCovered(unittest.TestCase):
|
||||
"""Jedes Muster aus Rainers Sammlung ist abgedeckt."""
|
||||
|
||||
def test_all_themenwechsel_patterns_present(self):
|
||||
required = [
|
||||
"Kurze Frage zu etwas anderem",
|
||||
"Mal ein anderes Thema",
|
||||
"Wechsel zum Thema",
|
||||
"Komplett anderes Thema",
|
||||
"Jetzt aber zu",
|
||||
"Ab jetzt geht es um",
|
||||
"Nur kurz aussetzen",
|
||||
"Darf ich unterbrechen",
|
||||
"Schob, ganz was anderes",
|
||||
]
|
||||
for phrase in required:
|
||||
found = any(
|
||||
re.search(p, phrase, re.IGNORECASE)
|
||||
for p in HART_THEMENWECHSEL_PATTERNS
|
||||
)
|
||||
self.assertTrue(
|
||||
found,
|
||||
f"Phrase '{phrase}' wird von keinem Pattern in HART_THEMENWECHSEL_PATTERNS erkannt"
|
||||
)
|
||||
|
||||
def test_all_rueckbezug_patterns_present(self):
|
||||
required = [
|
||||
"Lass uns nochmal auf",
|
||||
"Nochmal wegen",
|
||||
"Zurück zu",
|
||||
"Wie wir vorhin über",
|
||||
"Bezüglich",
|
||||
"Ich nehme Bezug auf",
|
||||
]
|
||||
for phrase in required:
|
||||
found = any(
|
||||
re.search(p, phrase, re.IGNORECASE)
|
||||
for p in HART_RUECKBEZUG_PATTERNS
|
||||
)
|
||||
self.assertTrue(
|
||||
found,
|
||||
f"Phrase '{phrase}' wird von keinem Pattern in HART_RUECKBEZUG_PATTERNS erkannt"
|
||||
)
|
||||
|
||||
def test_all_weich_patterns_present(self):
|
||||
required = [
|
||||
"Da fällt mir ein",
|
||||
"In dem Zusammenhang",
|
||||
"A propos",
|
||||
"Übrigens",
|
||||
"Das erinnert mich an",
|
||||
]
|
||||
for phrase in required:
|
||||
found = any(
|
||||
re.search(p, phrase, re.IGNORECASE)
|
||||
for p in WEICH_PATTERNS
|
||||
)
|
||||
self.assertTrue(
|
||||
found,
|
||||
f"Phrase '{phrase}' wird von keinem Pattern in WEICH_PATTERNS erkannt"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,418 @@
|
||||
"""
|
||||
A1b: Stufe 0 Integration — Satzeinleitungs-Erkennung im Router.
|
||||
|
||||
Tests für:
|
||||
- Hart-Themenwechsel → jetzt verblasst (V7-3) + stay_in_room
|
||||
- Hart-Rückbezug → jetzt wiederbelebt (V7-3) + stay_in_room
|
||||
- Weich-Muster → normaler Flow (kein stay_in_room durch Stufe 0)
|
||||
- Stufe 0 läuft VOR Stufe 1 (FAISS) — Performance
|
||||
- Kein Marker → kein Stufe-0-Eingriff
|
||||
- Rückbezug ohne never_route-Eintrag → normaler Flow
|
||||
- Themenwechsel setzt AKTIV auf VERBLASST
|
||||
"""
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
|
||||
|
||||
from archivar_state import ArchivarState
|
||||
from sentence_markers import MarkerClass
|
||||
|
||||
# router.py uses relative imports
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
from plugin.archivar.router import BidirectionalRouter
|
||||
|
||||
|
||||
# ── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _make_mock_room_map():
|
||||
from room_map import RoomMap, RoomEntry
|
||||
|
||||
rooms = {
|
||||
"r_lan": RoomEntry(
|
||||
room_id="r_lan",
|
||||
name="#LAN-Dokumentation",
|
||||
theme="lan docs",
|
||||
keywords_100=["lan", "dokumentation", "netzwerk"],
|
||||
keywords_context=[],
|
||||
catch_all=False,
|
||||
),
|
||||
"r_proton": RoomEntry(
|
||||
room_id="r_proton",
|
||||
name="#ProtonBridge",
|
||||
theme="proton mail bridge",
|
||||
keywords_100=["protonbridge", "protonmail", "bridge"],
|
||||
keywords_context=[],
|
||||
catch_all=False,
|
||||
),
|
||||
"r_admin": RoomEntry(
|
||||
room_id="r_admin",
|
||||
name="DM Admin",
|
||||
theme="admin",
|
||||
keywords_100=[],
|
||||
keywords_context=[],
|
||||
catch_all=True,
|
||||
),
|
||||
}
|
||||
|
||||
rm = MagicMock(spec=RoomMap)
|
||||
rm.rooms = rooms
|
||||
rm.catch_all_room = rooms["r_admin"]
|
||||
rm.get_room_by_id = lambda rid: rooms.get(rid)
|
||||
rm.is_excluded = lambda rid: False
|
||||
rm.find_room_by_keywords = MagicMock(return_value=None)
|
||||
rm.is_100_percent_match = MagicMock(return_value=False)
|
||||
return rm
|
||||
|
||||
|
||||
def _make_mock_classifier():
|
||||
classifier = MagicMock()
|
||||
classifier.is_initialized = True
|
||||
classifier._llm_raw = AsyncMock(return_value="STAY")
|
||||
classifier._llm_client = None
|
||||
classifier._llm_enabled = True
|
||||
classifier.classify = AsyncMock(return_value=None)
|
||||
return classifier
|
||||
|
||||
|
||||
# ── Tests: Stufe 0 — Hart-Themenwechsel ────────────────────────────────────
|
||||
|
||||
|
||||
class TestStufe0HartThemenwechsel(unittest.TestCase):
|
||||
"""Stufe 0: Hart-Themenwechsel → jetzt verblasst + stay_in_room."""
|
||||
|
||||
def setUp(self):
|
||||
self.room_map = _make_mock_room_map()
|
||||
self.classifier = _make_mock_classifier()
|
||||
self.state = ArchivarState()
|
||||
self.state._loaded = True
|
||||
|
||||
def _make_router(self, conversation_history=None):
|
||||
return BidirectionalRouter(
|
||||
self.room_map,
|
||||
self.classifier,
|
||||
self.state,
|
||||
conversation_history=conversation_history,
|
||||
)
|
||||
|
||||
def test_themenwechsel_blendet_jetzt_aus(self):
|
||||
"""Hart-Themenwechsel setzt AKTIV → VERBLASST + stay_in_room."""
|
||||
room_id = "r_proton"
|
||||
topic = "lan-dokumentation"
|
||||
|
||||
# Setze AKTIVEN never_route Eintrag
|
||||
self.state.set_never_route(room_id, topic)
|
||||
self.assertEqual(
|
||||
self.state._never_route[room_id][topic]["state"], "AKTIV"
|
||||
)
|
||||
|
||||
router = self._make_router()
|
||||
|
||||
decision = asyncio.run(
|
||||
router.route(
|
||||
"Kurze Frage zu etwas anderem: Wie geht das?",
|
||||
origin_room_id=room_id,
|
||||
)
|
||||
)
|
||||
|
||||
# Soll stay_in_room sein
|
||||
self.assertTrue(decision.stay_in_room)
|
||||
|
||||
# Der alte AKTIV-Eintrag sollte VERBLASST sein
|
||||
entry = self.state._never_route[room_id][topic]
|
||||
self.assertEqual(entry["state"], "VERBLASST")
|
||||
|
||||
def test_themenwechsel_ohne_never_route(self):
|
||||
"""Themenwechsel ohne never_route → normaler Flow (kein Crash)."""
|
||||
room_id = "r_proton"
|
||||
router = self._make_router()
|
||||
|
||||
decision = asyncio.run(
|
||||
router.route(
|
||||
"Mal ein anderes Thema: Was gibt's Neues?",
|
||||
origin_room_id=room_id,
|
||||
)
|
||||
)
|
||||
|
||||
# Sollte nicht crashen
|
||||
self.assertIsNotNone(decision)
|
||||
|
||||
def test_themenwechsel_mehrere_eintraege(self):
|
||||
"""Themenwechsel: nur das aktuelle Topic wird VERBLASST."""
|
||||
room_id = "r_proton"
|
||||
topic_a = "lan-dokumentation"
|
||||
topic_b = "devops"
|
||||
|
||||
self.state.set_never_route(room_id, topic_a)
|
||||
self.state.set_never_route(room_id, topic_b)
|
||||
|
||||
router = self._make_router()
|
||||
|
||||
asyncio.run(
|
||||
router.route(
|
||||
"Komplett anderes Thema: Wie geht's?",
|
||||
origin_room_id=room_id,
|
||||
)
|
||||
)
|
||||
|
||||
# Beide sollten noch existieren (Themenwechsel blendet nur
|
||||
# das aktuelle 'jetzt'-Topic aus, nicht alle)
|
||||
self.assertIn(room_id, self.state._never_route)
|
||||
self.assertIn(topic_a, self.state._never_route[room_id])
|
||||
self.assertIn(topic_b, self.state._never_route[room_id])
|
||||
|
||||
|
||||
# ── Tests: Stufe 0 — Hart-Rückbezug ───────────────────────────────────────
|
||||
|
||||
|
||||
class TestStufe0HartRueckbezug(unittest.TestCase):
|
||||
"""Stufe 0: Hart-Rückbezug → jetzt wiederbelebt + stay_in_room."""
|
||||
|
||||
def setUp(self):
|
||||
self.room_map = _make_mock_room_map()
|
||||
self.classifier = _make_mock_classifier()
|
||||
self.state = ArchivarState()
|
||||
self.state._loaded = True
|
||||
|
||||
def _make_router(self, conversation_history=None):
|
||||
return BidirectionalRouter(
|
||||
self.room_map,
|
||||
self.classifier,
|
||||
self.state,
|
||||
conversation_history=conversation_history,
|
||||
)
|
||||
|
||||
def test_rueckbezug_belebt_verblasst_wieder(self):
|
||||
"""Rückbezug auf VERBLASST → AKTIV + stay_in_room."""
|
||||
room_id = "r_proton"
|
||||
# Der Satz "Lass uns nochmal auf LAN-Doku zurückkommen."
|
||||
# extrahiert "lan-doku" als Topic (aus "LAN-Doku")
|
||||
topic = "lan-doku"
|
||||
|
||||
# Setze VERBLASSTEN never_route Eintrag
|
||||
self.state.set_never_route(room_id, topic)
|
||||
self.state._never_route[room_id][topic]["state"] = "VERBLASST"
|
||||
|
||||
router = self._make_router()
|
||||
|
||||
decision = asyncio.run(
|
||||
router.route(
|
||||
"Lass uns nochmal auf LAN-Doku zurückkommen.",
|
||||
origin_room_id=room_id,
|
||||
)
|
||||
)
|
||||
|
||||
self.assertTrue(decision.stay_in_room)
|
||||
|
||||
# Eintrag sollte wieder AKTIV sein
|
||||
entry = self.state._never_route[room_id][topic]
|
||||
self.assertEqual(entry["state"], "AKTIV")
|
||||
|
||||
def test_rueckbezug_ohne_never_route(self):
|
||||
"""Rückbezug ohne never_route → normaler Flow."""
|
||||
room_id = "r_proton"
|
||||
router = self._make_router()
|
||||
|
||||
decision = asyncio.run(
|
||||
router.route(
|
||||
"Lass uns nochmal auf LAN-Doku zurückkommen.",
|
||||
origin_room_id=room_id,
|
||||
)
|
||||
)
|
||||
|
||||
self.assertIsNotNone(decision)
|
||||
|
||||
def test_rueckbezug_butler_nicht_ausgeloest(self):
|
||||
"""Rückbezug löst KEINEN Butler aus."""
|
||||
room_id = "r_proton"
|
||||
topic = "lan-dokumentation"
|
||||
|
||||
self.state.set_never_route(room_id, topic)
|
||||
self.state._never_route[room_id][topic]["state"] = "VERBLASST"
|
||||
|
||||
router = self._make_router()
|
||||
|
||||
decision = asyncio.run(
|
||||
router.route(
|
||||
"Lass uns nochmal auf LAN-Doku zurückkommen.",
|
||||
origin_room_id=room_id,
|
||||
)
|
||||
)
|
||||
|
||||
self.assertFalse(decision.move_request_sent)
|
||||
self.assertTrue(decision.stay_in_room)
|
||||
|
||||
|
||||
# ── Tests: Stufe 0 — Weich-Muster ─────────────────────────────────────────
|
||||
|
||||
|
||||
class TestStufe0WeichMuster(unittest.TestCase):
|
||||
"""Stufe 0: Weich-Muster → normaler Flow (kein Eingriff)."""
|
||||
|
||||
def setUp(self):
|
||||
self.room_map = _make_mock_room_map()
|
||||
self.classifier = _make_mock_classifier()
|
||||
self.state = ArchivarState()
|
||||
self.state._loaded = True
|
||||
|
||||
def _make_router(self, conversation_history=None):
|
||||
return BidirectionalRouter(
|
||||
self.room_map,
|
||||
self.classifier,
|
||||
self.state,
|
||||
conversation_history=conversation_history,
|
||||
)
|
||||
|
||||
def test_weich_muster_normaler_flow(self):
|
||||
"""Weich-Muster → kein Stufe-0-Eingriff, normaler Flow."""
|
||||
room_id = "r_proton"
|
||||
topic = "lan-dokumentation"
|
||||
|
||||
self.state.set_never_route(room_id, topic)
|
||||
|
||||
router = self._make_router()
|
||||
|
||||
decision = asyncio.run(
|
||||
router.route(
|
||||
"Da fällt mir ein, wir müssen noch die Doku updaten.",
|
||||
origin_room_id=room_id,
|
||||
)
|
||||
)
|
||||
|
||||
# Sollte nicht crashen — normaler Flow
|
||||
self.assertIsNotNone(decision)
|
||||
# never_route bleibt unverändert (AKTIV)
|
||||
entry = self.state._never_route[room_id][topic]
|
||||
self.assertEqual(entry["state"], "AKTIV")
|
||||
|
||||
def test_weich_muster_kein_stay_in_room_erzwungen(self):
|
||||
"""Weich-Muster erzwingt KEIN stay_in_room durch Stufe 0."""
|
||||
room_id = "r_proton"
|
||||
router = self._make_router()
|
||||
|
||||
decision = asyncio.run(
|
||||
router.route(
|
||||
"Übrigens, das Meeting ist verschoben.",
|
||||
origin_room_id=room_id,
|
||||
)
|
||||
)
|
||||
|
||||
# Sollte nicht crashen
|
||||
self.assertIsNotNone(decision)
|
||||
|
||||
|
||||
# ── Tests: Stufe 0 — Kein Marker ──────────────────────────────────────────
|
||||
|
||||
|
||||
class TestStufe0KeinMarker(unittest.TestCase):
|
||||
"""Stufe 0: Kein Marker → kein Eingriff."""
|
||||
|
||||
def setUp(self):
|
||||
self.room_map = _make_mock_room_map()
|
||||
self.classifier = _make_mock_classifier()
|
||||
self.state = ArchivarState()
|
||||
self.state._loaded = True
|
||||
|
||||
def _make_router(self, conversation_history=None):
|
||||
return BidirectionalRouter(
|
||||
self.room_map,
|
||||
self.classifier,
|
||||
self.state,
|
||||
conversation_history=conversation_history,
|
||||
)
|
||||
|
||||
def test_normale_nachricht_kein_eingriff(self):
|
||||
"""Normale Nachricht ohne Marker → kein Stufe-0-Eingriff."""
|
||||
room_id = "r_proton"
|
||||
topic = "lan-dokumentation"
|
||||
self.state.set_never_route(room_id, topic)
|
||||
|
||||
router = self._make_router()
|
||||
|
||||
decision = asyncio.run(
|
||||
router.route(
|
||||
"Kannst du mir die Doku zeigen?",
|
||||
origin_room_id=room_id,
|
||||
)
|
||||
)
|
||||
|
||||
self.assertIsNotNone(decision)
|
||||
# never_route bleibt AKTIV
|
||||
entry = self.state._never_route[room_id][topic]
|
||||
self.assertEqual(entry["state"], "AKTIV")
|
||||
|
||||
|
||||
# ── Tests: Stufe 0 — Priorität vor anderen Stufen ────────────────────────
|
||||
|
||||
|
||||
class TestStufe0Prioritaet(unittest.TestCase):
|
||||
"""Stufe 0 läuft VOR Stufe 1 (FAISS) und anderen Stufen."""
|
||||
|
||||
def setUp(self):
|
||||
self.room_map = _make_mock_room_map()
|
||||
self.classifier = _make_mock_classifier()
|
||||
self.state = ArchivarState()
|
||||
self.state._loaded = True
|
||||
|
||||
def _make_router(self, conversation_history=None):
|
||||
return BidirectionalRouter(
|
||||
self.room_map,
|
||||
self.classifier,
|
||||
self.state,
|
||||
conversation_history=conversation_history,
|
||||
)
|
||||
|
||||
def test_themenwechsel_ueberspringt_keyword_match(self):
|
||||
"""Themenwechsel → stay_in_room, Keyword-Match wird NICHT geprüft."""
|
||||
room_id = "r_proton"
|
||||
topic = "lan-dokumentation"
|
||||
self.state.set_never_route(room_id, topic)
|
||||
|
||||
router = self._make_router()
|
||||
|
||||
# Mock: find_room_by_keywords würde einen Treffer liefern
|
||||
self.room_map.find_room_by_keywords.return_value = (
|
||||
self.room_map.rooms["r_lan"]
|
||||
)
|
||||
|
||||
decision = asyncio.run(
|
||||
router.route(
|
||||
"Kurze Frage zu etwas anderem: Doku update?",
|
||||
origin_room_id=room_id,
|
||||
)
|
||||
)
|
||||
|
||||
# Stufe 0 sollte VOR Keyword-Match greifen
|
||||
self.assertTrue(decision.stay_in_room)
|
||||
# Keyword-Match wurde NICHT aufgerufen (weil Stufe 0 schon stay_in_room)
|
||||
# (find_room_by_keywords könnte aufgerufen worden sein, aber das Ergebnis
|
||||
# wird ignoriert weil Stufe 0 bereits entschieden hat)
|
||||
|
||||
def test_rueckbezug_ueberspringt_faiss(self):
|
||||
"""Rückbezug → stay_in_room, FAISS wird NICHT aufgerufen."""
|
||||
room_id = "r_proton"
|
||||
topic = "lan-dokumentation"
|
||||
self.state.set_never_route(room_id, topic)
|
||||
self.state._never_route[room_id][topic]["state"] = "VERBLASST"
|
||||
|
||||
router = self._make_router()
|
||||
|
||||
decision = asyncio.run(
|
||||
router.route(
|
||||
"Lass uns nochmal auf LAN-Doku zurückkommen.",
|
||||
origin_room_id=room_id,
|
||||
)
|
||||
)
|
||||
|
||||
self.assertTrue(decision.stay_in_room)
|
||||
self.assertFalse(decision.move_request_sent)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"rooms": {},
|
||||
"keyword_weights": {},
|
||||
"sticky_keywords": {},
|
||||
"manual_overrides": {},
|
||||
"promotion_candidates": {},
|
||||
"stay_tracker": {},
|
||||
"onboarding_state": {},
|
||||
"never_route": {
|
||||
"r_proton": {
|
||||
"lan-dokumentation": {
|
||||
"state": "AKTIV",
|
||||
"timestamp": "2026-07-13T20:34:20.149597",
|
||||
"last_extended": "2026-07-13T20:34:20.149597",
|
||||
"extension_count": 0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user