Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 948666fcdd | |||
| 2eb723fb63 |
+335
-124
@@ -457,6 +457,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self._sticky_rooms: Dict[str, float] = {} # room_id → timestamp
|
self._sticky_rooms: Dict[str, float] = {} # room_id → timestamp
|
||||||
# Clarify state: maps clarify_id → session_key for gateway resolution
|
# Clarify state: maps clarify_id → session_key for gateway resolution
|
||||||
self._clarify_state: Dict[str, str] = {}
|
self._clarify_state: Dict[str, str] = {}
|
||||||
|
# Auto-Onboarding v2: structured interview state
|
||||||
|
self._onboarding_state: Dict[str, Any] = {}
|
||||||
|
|
||||||
async def connect(self) -> bool:
|
async def connect(self) -> bool:
|
||||||
if not self.base_url or not self.user or not self.password:
|
if not self.base_url or not self.user or not self.password:
|
||||||
@@ -710,12 +712,17 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# Auto-Onboarding: Wenn onboarding_active, fange alle relevanten Antworten ab
|
# Auto-Onboarding: Wenn onboarding_active, fange alle relevanten Antworten ab
|
||||||
if self.archivar._stats.get("onboarding_active", False):
|
if self.archivar._stats.get("onboarding_active", False):
|
||||||
stripped = text.strip()
|
stripped = text.strip()
|
||||||
|
# Nur Nachrichten aus dem Operator-DM-Raum als Onboarding behandeln
|
||||||
|
operator_room = self._onboarding_state.get("operator_room_id", "")
|
||||||
|
is_operator_room = (operator_room and room_id == operator_room)
|
||||||
is_onboarding = (
|
is_onboarding = (
|
||||||
"=" in stripped # Name = Thema
|
(is_operator_room and stripped.startswith("ONBOARD:")) # v2 Button-Klick
|
||||||
or stripped.startswith("#") # #Name = Thema
|
or (is_operator_room and self._onboarding_state.get("current_room_index", -1) >= 0) # v2 Interview läuft
|
||||||
or stripped.lower().startswith("raum:") # Raum: Name = Thema
|
or (is_operator_room and "=" in stripped) # v1 Legacy: Name = Thema
|
||||||
or stripped.isdigit() # 3 (Catch-All-Wechsel)
|
or (is_operator_room and stripped.startswith("#")) # v1 Legacy: #Name = Thema
|
||||||
or stripped.lower() in ("überspringen", "skip", "nein", "no", "behalten") # Ablehnung
|
or (is_operator_room and stripped.lower().startswith("raum:")) # v1 Legacy: Raum: Name = Thema
|
||||||
|
or (is_operator_room and stripped.isdigit()) # Catch-All-Wechsel
|
||||||
|
or (is_operator_room and stripped.lower() in ("überspringen", "skip", "nein", "no", "behalten")) # Ablehnung
|
||||||
)
|
)
|
||||||
if is_onboarding:
|
if is_onboarding:
|
||||||
await self._process_onboarding_response(text, room_id)
|
await self._process_onboarding_response(text, room_id)
|
||||||
@@ -1059,8 +1066,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
return success
|
return success
|
||||||
|
|
||||||
async def _start_onboarding(self, missing_rooms: list) -> None:
|
async def _start_onboarding(self, missing_rooms: list) -> None:
|
||||||
"""Sendet EINE DM an den Operator mit der Liste fehlender Räume.
|
"""v2: Sendet Onboarding-DM mit Buttons pro fehlendem Raum.
|
||||||
|
|
||||||
|
Jeder Raum bekommt drei Buttons:
|
||||||
|
- [Projektraum einrichten] → startet strukturiertes 4-Fragen-Interview
|
||||||
|
- [Überspringen] → Raum wird ignoriert, nicht in Map
|
||||||
|
- [Später] → Onboarding pausiert, beim nächsten Connect erneut prüfen
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
missing_rooms: Liste fehlender Räume [{"room_id": "...", "name": "#Raum"}]
|
missing_rooms: Liste fehlender Räume [{"room_id": "...", "name": "#Raum"}]
|
||||||
"""
|
"""
|
||||||
@@ -1070,159 +1082,358 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if info.get("type") == "d" and "andreas" in info.get("name", "").lower():
|
if info.get("type") == "d" and "andreas" in info.get("name", "").lower():
|
||||||
operator_room_id = room_id
|
operator_room_id = room_id
|
||||||
break
|
break
|
||||||
|
|
||||||
if not operator_room_id:
|
if not operator_room_id:
|
||||||
logger.warning("[rocketchat] Operator-DM-Raum nicht gefunden, kann Onboarding nicht starten")
|
logger.warning("[rocketchat] Operator-DM-Raum nicht gefunden, kann Onboarding nicht starten")
|
||||||
return
|
return
|
||||||
|
|
||||||
# Text erstellen — OHNE # (Rocket.Chat macht Links daraus, blockiert Editieren)
|
# Initialisiere Onboarding-State
|
||||||
|
self._onboarding_state = {
|
||||||
|
"missing_rooms": missing_rooms,
|
||||||
|
"current_room_index": -1, # -1 = noch kein Raum ausgewählt
|
||||||
|
"current_question": 0, # 0 = noch keine Frage gestellt
|
||||||
|
"collected_data": {}, # room_id → {theme, keywords_100, keywords_context, catch_all}
|
||||||
|
"operator_room_id": operator_room_id,
|
||||||
|
"skipped_rooms": [], # room_ids die übersprungen wurden
|
||||||
|
}
|
||||||
|
self.archivar._stats["onboarding_active"] = True
|
||||||
|
|
||||||
|
# Baue Nachricht mit Buttons pro Raum
|
||||||
|
from . import _build_custom_buttons
|
||||||
|
|
||||||
lines = ["Folgende Räume fehlen in der Raum-Map.",
|
lines = ["Folgende Räume fehlen in der Raum-Map.",
|
||||||
"Wofür ist jeder Raum da? Antworte pro Raum mit: `Name = Thema`",
|
"Für jeden Raum kannst du ein kurzes Interview starten:",
|
||||||
""]
|
""]
|
||||||
for i, room in enumerate(missing_rooms, 1):
|
for i, room in enumerate(missing_rooms, 1):
|
||||||
clean_name = room['name'].lstrip("#")
|
clean_name = room["name"].lstrip("#")
|
||||||
lines.append(f"{i}. {clean_name} = ")
|
lines.append(f"{i}. {clean_name}")
|
||||||
|
|
||||||
lines.append("")
|
lines.append("")
|
||||||
lines.append("Beispiel: `Projektraum = Entwicklung, Code-Reviews, Austausch und Status zum Projekt`")
|
lines.append("Klicke auf einen Button, um den Raum einzurichten:")
|
||||||
text = "\n".join(lines)
|
text = "\n".join(lines)
|
||||||
|
|
||||||
# Nachricht senden
|
# Buttons pro Raum: [Projektraum einrichten] [Überspringen] [Später]
|
||||||
success = self.rest.post_message(operator_room_id, text)
|
buttons = []
|
||||||
|
for room in missing_rooms:
|
||||||
|
rid = room["room_id"]
|
||||||
|
clean_name = room["name"].lstrip("#")
|
||||||
|
# Prefix: ONBOARD:<room_id> für Korrelation
|
||||||
|
prefix = f"ONBOARD:{rid}"
|
||||||
|
buttons.extend(_build_custom_buttons(
|
||||||
|
[f"📋 {clean_name[:8]}", f"⏭️ Überspringen", f"⏰ Später"],
|
||||||
|
prefix=prefix
|
||||||
|
))
|
||||||
|
|
||||||
|
attachments = [{
|
||||||
|
"color": "#1d74f5",
|
||||||
|
"title": "Raum-Map unvollständig — Räume einrichten?",
|
||||||
|
"actions": buttons,
|
||||||
|
}]
|
||||||
|
|
||||||
|
success = self.rest.post_message(operator_room_id, text, attachments=attachments)
|
||||||
if success:
|
if success:
|
||||||
# Setze onboarding_active auf True
|
logger.info("[rocketchat] Onboarding v2 gestartet: %d Räume fehlen", len(missing_rooms))
|
||||||
self.archivar._stats["onboarding_active"] = True
|
|
||||||
logger.info("[rocketchat] Onboarding gestartet: %d Räume fehlen", len(missing_rooms))
|
|
||||||
else:
|
else:
|
||||||
logger.error("[rocketchat] Fehler beim Senden der Onboarding-Nachricht")
|
logger.error("[rocketchat] Fehler beim Senden der Onboarding-Nachricht")
|
||||||
|
|
||||||
async def _process_onboarding_response(self, text: str, room_id: str) -> None:
|
async def _process_onboarding_response(self, text: str, room_id: str) -> None:
|
||||||
"""Verarbeitet Onboarding-Antworten vom Operator.
|
"""v2: Verarbeitet Onboarding-Antworten (Button-Klicks + Text-Antworten).
|
||||||
|
|
||||||
Akzeptiert zwei Formate pro Zeile:
|
Zwei Modi:
|
||||||
1. „#Name = Thema" (empfohlen, intuitiv)
|
1. Button-Klick (ONBOARD:<room_id>::<action>) — Raumauswahl / Überspringen / Später
|
||||||
2. „Raum: #Name = Thema, Stichworte: kw1, kw2" (explizit)
|
2. Text-Antwort — Antwort auf eine der 4 Interview-Fragen
|
||||||
Fehlende Stichworte werden automatisch aus Raumname + Thema abgeleitet.
|
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
text: Die Antwortnachricht des Operators
|
text: Die Antwortnachricht des Operators (Button-Payload oder Freitext)
|
||||||
room_id: Die Raum-ID, in der die Nachricht empfangen wurde
|
room_id: Die Raum-ID, in der die Nachricht empfangen wurde
|
||||||
"""
|
"""
|
||||||
import re
|
state = self._onboarding_state
|
||||||
|
if not state:
|
||||||
# Pattern: # ist optional (Rocket.Chat macht sonst Links daraus)
|
logger.debug("[rocketchat] Onboarding state empty, ignoring response")
|
||||||
# Akzeptiert: "Name = Thema", "#Name = Thema", "Raum: Name = Thema"
|
|
||||||
pattern = re.compile(
|
|
||||||
r"(?:Raum:\s*)?"
|
|
||||||
r"(?P<name>#?[^\s=]+)\s*=\s*"
|
|
||||||
r"(?P<theme>[^,]+?)"
|
|
||||||
r"(?:,\s*(?:Keywords|Stichworte|Schlagworte):\s*(?P<keywords>.*?))?$",
|
|
||||||
re.IGNORECASE,
|
|
||||||
)
|
|
||||||
|
|
||||||
lines = text.strip().splitlines()
|
|
||||||
|
|
||||||
# ── Catch-All-Wechsel-Prüfung ─────────────────────────────────
|
|
||||||
# Wenn die Nachricht eine einzelne Zahl oder ein Ablehnungswort ist,
|
|
||||||
# interpretiere sie als Antwort auf die Catch-All-Frage.
|
|
||||||
single_line = text.strip()
|
|
||||||
if single_line.isdigit():
|
|
||||||
index = int(single_line) - 1 # 0-basiert
|
|
||||||
all_rooms = self._get_onboarding_room_list()
|
|
||||||
if 0 <= index < len(all_rooms):
|
|
||||||
rid, name = all_rooms[index]
|
|
||||||
self._set_catch_all(rid)
|
|
||||||
self.rest.post_message(room_id, f"🎯 {name} ist jetzt der Catch-All-Raum.")
|
|
||||||
logger.info("[rocketchat] Catch-All geändert zu: %s", name)
|
|
||||||
else:
|
|
||||||
self.rest.post_message(room_id, f"❌ Ungültige Nummer. Bitte 1–{len(all_rooms)} wählen.")
|
|
||||||
return
|
|
||||||
if single_line.lower() in ("überspringen", "skip", "nein", "no", "behalten"):
|
|
||||||
self.rest.post_message(room_id, "👍 Catch-All bleibt unverändert.")
|
|
||||||
logger.info("[rocketchat] Catch-All unverändert")
|
|
||||||
return
|
return
|
||||||
|
|
||||||
processed_count = 0
|
operator_room_id = state.get("operator_room_id", "")
|
||||||
total_missing = len([rid for rid, r in self._room_info.items()
|
if room_id != operator_room_id:
|
||||||
if r.get("type") in ("c", "p") and rid not in self.archivar._room_map.rooms])
|
logger.debug("[rocketchat] Onboarding response from non-operator room, ignoring")
|
||||||
|
return
|
||||||
|
|
||||||
for line in lines:
|
# ── Phase: catch_all_change (nach Abschluss aller Interviews) ────
|
||||||
line = line.strip()
|
if state.get("phase") == "catch_all_change":
|
||||||
# Skip empty lines and lines without obvious room assignment
|
single_line = text.strip()
|
||||||
if not line or "=" not in line:
|
if single_line.isdigit():
|
||||||
continue
|
index = int(single_line) - 1
|
||||||
|
all_rooms = self._get_onboarding_room_list()
|
||||||
match = pattern.match(line)
|
if 0 <= index < len(all_rooms):
|
||||||
if not match:
|
rid, name = all_rooms[index]
|
||||||
continue
|
self._set_catch_all(rid)
|
||||||
|
self.rest.post_message(operator_room_id, f"🎯 {name} ist jetzt der Catch-All-Raum.")
|
||||||
raw_name = match.group("name")
|
logger.info("[rocketchat] Catch-All geändert zu: %s", name)
|
||||||
theme = match.group("theme").strip()
|
else:
|
||||||
keywords_str = match.group("keywords")
|
self.rest.post_message(operator_room_id, f"❌ Ungültige Nummer. Bitte 1–{len(all_rooms)} wählen.")
|
||||||
|
return # onboarding_active bleibt True, warte auf korrekte Antwort
|
||||||
if keywords_str:
|
elif single_line.lower() in ("überspringen", "skip", "nein", "no", "behalten"):
|
||||||
keywords = [kw.strip() for kw in keywords_str.split(",") if kw.strip()]
|
self.rest.post_message(operator_room_id, "👍 Catch-All bleibt unverändert.")
|
||||||
|
logger.info("[rocketchat] Catch-All unverändert")
|
||||||
else:
|
else:
|
||||||
keywords = self._derive_keywords(raw_name, theme)
|
self.rest.post_message(operator_room_id, "❌ Bitte eine Raumnummer (1, 2, …) oder 'überspringen' eingeben.")
|
||||||
|
return # onboarding_active bleibt True
|
||||||
|
# Catch-All-Frage beantwortet → Onboarding wirklich abschließen
|
||||||
|
self.archivar._stats["onboarding_active"] = False
|
||||||
|
self._onboarding_state = {}
|
||||||
|
logger.info("[rocketchat] Onboarding v2 vollständig abgeschlossen")
|
||||||
|
return
|
||||||
|
|
||||||
# Finde den Raum — probiere sowohl mit als auch ohne #
|
# ── Modus 1: Button-Klick (ONBOARD:<room_id>::<action>) ──────────
|
||||||
room_id_to_add = None
|
if text.startswith("ONBOARD:") and "::" in text:
|
||||||
for rid, info in self._room_info.items():
|
prefix_part, action = text.split("::", 1)
|
||||||
if info.get("type") not in ("c", "p"):
|
target_room_id = prefix_part.split(":", 1)[1]
|
||||||
continue
|
action = action.strip()
|
||||||
rc_name = info.get("name", "")
|
|
||||||
# Match: "BAT-Team" == "#BAT-Team", "#BAT-Team" == "BAT-Team"
|
if "Überspringen" in action or "⏭️" in action:
|
||||||
if raw_name == rc_name or raw_name.lstrip("#") == rc_name.lstrip("#"):
|
# Raum überspringen
|
||||||
room_id_to_add = rid
|
state["skipped_rooms"].append(target_room_id)
|
||||||
|
logger.info("[rocketchat] Onboarding: Raum %s übersprungen", target_room_id[:8])
|
||||||
|
self._onboarding_next_room()
|
||||||
|
return
|
||||||
|
|
||||||
|
if "Später" in action or "⏰" in action:
|
||||||
|
# Onboarding pausieren
|
||||||
|
self.archivar._stats["onboarding_active"] = False
|
||||||
|
self._onboarding_state = {}
|
||||||
|
self.rest.post_message(operator_room_id,
|
||||||
|
"⏰ Onboarding pausiert. Ich frage beim nächsten Start wieder nach.")
|
||||||
|
logger.info("[rocketchat] Onboarding pausiert (Später)")
|
||||||
|
return
|
||||||
|
|
||||||
|
# "Projektraum einrichten" — Interview starten
|
||||||
|
missing = state["missing_rooms"]
|
||||||
|
for i, room in enumerate(missing):
|
||||||
|
if room["room_id"] == target_room_id:
|
||||||
|
state["current_room_index"] = i
|
||||||
|
state["current_question"] = 1
|
||||||
|
state["collected_data"][target_room_id] = {
|
||||||
|
"theme": "",
|
||||||
|
"keywords_100": [],
|
||||||
|
"keywords_context": [],
|
||||||
|
"catch_all": False,
|
||||||
|
}
|
||||||
break
|
break
|
||||||
|
|
||||||
if room_id_to_add:
|
if state["current_room_index"] >= 0:
|
||||||
self.archivar._room_map.add_or_update_room(
|
self._ask_onboarding_question(operator_room_id)
|
||||||
room_id=room_id_to_add,
|
return
|
||||||
name=raw_name,
|
|
||||||
theme=theme,
|
|
||||||
keywords=keywords
|
|
||||||
)
|
|
||||||
processed_count += 1
|
|
||||||
logger.info("[rocketchat] Raum hinzugefügt: %s = %s (keywords: %s)", raw_name, theme, keywords)
|
|
||||||
|
|
||||||
if processed_count > 0:
|
# ── Modus 2: Text-Antwort auf Interview-Frage ────────────────────
|
||||||
# RoomMap speichern und reloaden
|
current_idx = state.get("current_room_index", -1)
|
||||||
|
if current_idx < 0:
|
||||||
|
return # Kein aktives Interview
|
||||||
|
|
||||||
|
current_q = state.get("current_question", 0)
|
||||||
|
if current_q < 1 or current_q > 4:
|
||||||
|
return # Keine aktive Frage
|
||||||
|
|
||||||
|
room = state["missing_rooms"][current_idx]
|
||||||
|
rid = room["room_id"]
|
||||||
|
data = state["collected_data"].get(rid, {})
|
||||||
|
|
||||||
|
# Frage 1: theme
|
||||||
|
if current_q == 1:
|
||||||
|
theme = text.strip()
|
||||||
|
if not theme or len(theme) < 3:
|
||||||
|
self.rest.post_message(operator_room_id,
|
||||||
|
"❌ Bitte gib eine kurze Beschreibung ein (mindestens 3 Zeichen).")
|
||||||
|
return
|
||||||
|
data["theme"] = theme
|
||||||
|
state["current_question"] = 2
|
||||||
|
self._ask_onboarding_question(operator_room_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Frage 2: keywords_100
|
||||||
|
if current_q == 2:
|
||||||
|
raw = text.strip()
|
||||||
|
if raw.lower() in ("keine", "none", "-", ""):
|
||||||
|
data["keywords_100"] = []
|
||||||
|
else:
|
||||||
|
# Akzeptiere komma-getrennt oder leerzeichen-getrennt
|
||||||
|
if "," in raw:
|
||||||
|
kws = [kw.strip().lower() for kw in raw.split(",") if kw.strip()]
|
||||||
|
else:
|
||||||
|
kws = [kw.strip().lower() for kw in raw.split() if kw.strip()]
|
||||||
|
data["keywords_100"] = kws[:10]
|
||||||
|
state["current_question"] = 3
|
||||||
|
self._ask_onboarding_question(operator_room_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Frage 3: keywords_context
|
||||||
|
if current_q == 3:
|
||||||
|
raw = text.strip()
|
||||||
|
if raw.lower() in ("keine", "none", "-", ""):
|
||||||
|
data["keywords_context"] = []
|
||||||
|
else:
|
||||||
|
if "," in raw:
|
||||||
|
kws = [kw.strip().lower() for kw in raw.split(",") if kw.strip()]
|
||||||
|
else:
|
||||||
|
kws = [kw.strip().lower() for kw in raw.split() if kw.strip()]
|
||||||
|
data["keywords_context"] = kws[:10]
|
||||||
|
state["current_question"] = 4
|
||||||
|
self._ask_onboarding_question(operator_room_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Frage 4: catch_all
|
||||||
|
if current_q == 4:
|
||||||
|
answer = text.strip().lower()
|
||||||
|
is_catch_all = answer in ("ja", "yes", "j", "y", "1", "👍", "✅")
|
||||||
|
data["catch_all"] = is_catch_all
|
||||||
|
|
||||||
|
# Raum zur Map hinzufügen
|
||||||
|
room_name = room["name"]
|
||||||
|
self.archivar._room_map.add_or_update_room(
|
||||||
|
room_id=rid,
|
||||||
|
name=room_name,
|
||||||
|
theme=data["theme"],
|
||||||
|
keywords_100=data.get("keywords_100", []),
|
||||||
|
keywords_context=data.get("keywords_context", []),
|
||||||
|
catch_all=is_catch_all,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Speichern + reload
|
||||||
from .archivar.room_map import RoomMap
|
from .archivar.room_map import RoomMap
|
||||||
from .archivar.config import ROOM_MAP_PATH
|
from .archivar.config import ROOM_MAP_PATH
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
RoomMap.save(self.archivar._room_map, Path(ROOM_MAP_PATH))
|
||||||
self.archivar._room_map.reload()
|
self.archivar._room_map.reload()
|
||||||
|
|
||||||
remaining_missing = len([rid for rid, r in self._room_info.items()
|
logger.info("[rocketchat] Onboarding: Raum %s zur Map hinzugefügt (catch_all=%s)",
|
||||||
if r.get("type") in ("c", "p") and rid not in self.archivar._room_map.rooms])
|
room_name, is_catch_all)
|
||||||
|
|
||||||
if remaining_missing == 0:
|
# Feedback an Operator
|
||||||
self.archivar._stats["onboarding_active"] = False
|
catch_marker = " 🎯 Catch-All" if is_catch_all else ""
|
||||||
# Baue nummerierte Raumliste für Catch-All-Frage
|
self.rest.post_message(operator_room_id,
|
||||||
all_rooms = []
|
f"✅ {room_name} eingerichtet:{catch_marker}\n"
|
||||||
for rid, entry in self.archivar._room_map.rooms.items():
|
f"Thema: {data['theme']}\n"
|
||||||
if rid in self.archivar._room_map._excluded_room_ids:
|
f"Keywords (sicher): {', '.join(data['keywords_100']) if data['keywords_100'] else 'keine'}\n"
|
||||||
continue
|
f"Keywords (Kontext): {', '.join(data['keywords_context']) if data['keywords_context'] else 'keine'}")
|
||||||
all_rooms.append((rid, entry.name, entry.catch_all))
|
|
||||||
# Sortiere: catch_all zuerst, dann alphabetisch
|
|
||||||
all_rooms.sort(key=lambda x: (not x[2], x[1]))
|
|
||||||
|
|
||||||
lines = [f"✅ Alle {processed_count} Räume zur Map hinzugefügt."]
|
# Nächster Raum oder Abschluss
|
||||||
|
self._onboarding_next_room()
|
||||||
|
return
|
||||||
|
|
||||||
|
def _ask_onboarding_question(self, operator_room_id: str) -> None:
|
||||||
|
"""Sendet die aktuelle Interview-Frage an den Operator."""
|
||||||
|
state = self._onboarding_state
|
||||||
|
if not state:
|
||||||
|
return
|
||||||
|
|
||||||
|
current_idx = state.get("current_room_index", -1)
|
||||||
|
if current_idx < 0:
|
||||||
|
return
|
||||||
|
|
||||||
|
room = state["missing_rooms"][current_idx]
|
||||||
|
room_name = room["name"]
|
||||||
|
current_q = state.get("current_question", 0)
|
||||||
|
|
||||||
|
questions = {
|
||||||
|
1: f"**{room_name}** — Frage 1/4:\nWorum geht es in diesem Raum? (1–2 Sätze)",
|
||||||
|
2: f"**{room_name}** — Frage 2/4:\nWelche Begriffe treffen SICHER zu? (Sofort-Match, z.B. \"bat\", \"trading\")\n"
|
||||||
|
f"(Komma-getrennt, oder \"keine\" wenn keine)",
|
||||||
|
3: f"**{room_name}** — Frage 3/4:\nWelche Begriffe deuten auf das Thema hin? (Kontext-Match, z.B. \"gateway\", \"plugin\")\n"
|
||||||
|
f"(Komma-getrennt, oder \"keine\" wenn keine)",
|
||||||
|
4: f"**{room_name}** — Frage 4/4:\nSoll dieser Raum der Catch-All sein? (Ja/Nein)",
|
||||||
|
}
|
||||||
|
|
||||||
|
text = questions.get(current_q, "")
|
||||||
|
if text:
|
||||||
|
self.rest.post_message(operator_room_id, text)
|
||||||
|
|
||||||
|
def _onboarding_next_room(self) -> None:
|
||||||
|
"""Gehe zum nächsten fehlenden Raum oder schließe Onboarding ab."""
|
||||||
|
state = self._onboarding_state
|
||||||
|
if not state:
|
||||||
|
return
|
||||||
|
|
||||||
|
operator_room_id = state.get("operator_room_id", "")
|
||||||
|
missing = state["missing_rooms"]
|
||||||
|
skipped = set(state.get("skipped_rooms", []))
|
||||||
|
collected = state.get("collected_data", {})
|
||||||
|
|
||||||
|
# Finde nächsten unbearbeiteten Raum
|
||||||
|
next_idx = state.get("current_room_index", -1) + 1
|
||||||
|
while next_idx < len(missing):
|
||||||
|
rid = missing[next_idx]["room_id"]
|
||||||
|
if rid not in skipped and rid not in collected:
|
||||||
|
break
|
||||||
|
next_idx += 1
|
||||||
|
|
||||||
|
if next_idx < len(missing):
|
||||||
|
# Noch Räume übrig — zurück zur Auswahl
|
||||||
|
state["current_room_index"] = -1
|
||||||
|
state["current_question"] = 0
|
||||||
|
|
||||||
|
remaining = []
|
||||||
|
for i in range(next_idx, len(missing)):
|
||||||
|
rid = missing[i]["room_id"]
|
||||||
|
if rid not in skipped and rid not in collected:
|
||||||
|
remaining.append(missing[i])
|
||||||
|
|
||||||
|
if remaining:
|
||||||
|
from . import _build_custom_buttons
|
||||||
|
lines = [f"📋 Noch {len(remaining)} Raum/Räume übrig:",
|
||||||
|
""]
|
||||||
|
for i, room in enumerate(remaining, 1):
|
||||||
|
lines.append(f"{i}. {room['name'].lstrip('#')}")
|
||||||
lines.append("")
|
lines.append("")
|
||||||
lines.append("**Aktuelle Raum-Übersicht:**")
|
lines.append("Klicke auf einen Button:")
|
||||||
for i, (rid, name, is_catch) in enumerate(all_rooms, 1):
|
|
||||||
marker = " 🎯 (Catch-All)" if is_catch else ""
|
buttons = []
|
||||||
lines.append(f"{i}. {name}{marker}")
|
for room in remaining:
|
||||||
lines.append("")
|
rid = room["room_id"]
|
||||||
lines.append("Möchtest du den Catch-All-Raum ändern? Antworte mit der Raumnummer, oder **überspringen** zum Behalten.")
|
clean_name = room["name"].lstrip("#")
|
||||||
confirmation_text = "\n".join(lines)
|
prefix = f"ONBOARD:{rid}"
|
||||||
self.rest.post_message(room_id, confirmation_text)
|
buttons.extend(_build_custom_buttons(
|
||||||
logger.info("[rocketchat] Onboarding abgeschlossen: Alle Räume wurden hinzugefügt")
|
[f"📋 {clean_name[:8]}", f"⏭️ Überspringen", f"⏰ Später"],
|
||||||
|
prefix=prefix
|
||||||
|
))
|
||||||
|
|
||||||
|
attachments = [{
|
||||||
|
"color": "#1d74f5",
|
||||||
|
"title": "Weitere Räume einrichten?",
|
||||||
|
"actions": buttons,
|
||||||
|
}]
|
||||||
|
self.rest.post_message(operator_room_id, "\n".join(lines), attachments=attachments)
|
||||||
else:
|
else:
|
||||||
remaining_text = f"📋 {processed_count} Räume verarbeitet, {remaining_missing} fehlen noch. Bitte die restlichen Themen nennen."
|
self._finish_onboarding(operator_room_id)
|
||||||
self.rest.post_message(room_id, remaining_text)
|
else:
|
||||||
logger.info("[rocketchat] Onboarding läuft: %d von %d Räumen verarbeitet", processed_count, total_missing)
|
# Alle Räume bearbeitet
|
||||||
|
self._finish_onboarding(operator_room_id)
|
||||||
|
|
||||||
|
def _finish_onboarding(self, operator_room_id: str) -> None:
|
||||||
|
"""Onboarding abschließen: Übersicht zeigen, Catch-All-Frage stellen."""
|
||||||
|
# NICHT onboarding_active=False setzen — wir warten noch auf Catch-All-Antwort
|
||||||
|
# Stattdessen: Phase wechseln zu "catch_all_change"
|
||||||
|
self._onboarding_state = {
|
||||||
|
"phase": "catch_all_change",
|
||||||
|
"operator_room_id": operator_room_id,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Baue nummerierte Raumliste
|
||||||
|
all_rooms = []
|
||||||
|
for rid, entry in self.archivar._room_map.rooms.items():
|
||||||
|
if rid in self.archivar._room_map._excluded_room_ids:
|
||||||
|
continue
|
||||||
|
all_rooms.append((rid, entry.name, entry.catch_all))
|
||||||
|
all_rooms.sort(key=lambda x: (not x[2], x[1]))
|
||||||
|
|
||||||
|
lines = ["✅ Alle Räume zur Map hinzugefügt.",
|
||||||
|
"",
|
||||||
|
"**Aktuelle Raum-Übersicht:**"]
|
||||||
|
for i, (rid, name, is_catch) in enumerate(all_rooms, 1):
|
||||||
|
marker = " 🎯 (Catch-All)" if is_catch else ""
|
||||||
|
lines.append(f"{i}. {name}{marker}")
|
||||||
|
lines.append("")
|
||||||
|
lines.append("Möchtest du den Catch-All-Raum ändern? Antworte mit der Raumnummer, oder **überspringen** zum Behalten.")
|
||||||
|
|
||||||
|
self.rest.post_message(operator_room_id, "\n".join(lines))
|
||||||
|
logger.info("[rocketchat] Onboarding v2 abgeschlossen: alle Räume eingerichtet")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _derive_keywords(room_name: str, theme: str) -> list:
|
def _derive_keywords(room_name: str, theme: str) -> list:
|
||||||
|
|||||||
@@ -2,14 +2,14 @@
|
|||||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||||
"$id": "https://hermes-agent.nousresearch.com/schemas/room-map.schema.json",
|
"$id": "https://hermes-agent.nousresearch.com/schemas/room-map.schema.json",
|
||||||
"title": "Archivar Room Map",
|
"title": "Archivar Room Map",
|
||||||
"description": "Schema for the Archivar room-map.json — the single source of truth for thematic message routing.",
|
"description": "Schema for the Archivar room-map.json — the single source of truth for thematic message routing. Version 2 splits keywords into keywords_100 (exact-match routing) and keywords_context (contextual routing).",
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"required": ["version", "rooms"],
|
"required": ["version", "rooms"],
|
||||||
"properties": {
|
"properties": {
|
||||||
"version": {
|
"version": {
|
||||||
"type": "integer",
|
"type": "integer",
|
||||||
"description": "Schema version for future migrations.",
|
"description": "Schema version for future migrations.",
|
||||||
"minimum": 1
|
"minimum": 2
|
||||||
},
|
},
|
||||||
"rooms": {
|
"rooms": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
@@ -28,9 +28,15 @@
|
|||||||
"description": "Theme / purpose of the room.",
|
"description": "Theme / purpose of the room.",
|
||||||
"minLength": 1
|
"minLength": 1
|
||||||
},
|
},
|
||||||
"keywords": {
|
"keywords_100": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"description": "Keywords for keyword-based routing.",
|
"description": "Keywords for exact-match routing (high-confidence, low false-positive).",
|
||||||
|
"items": { "type": "string", "minLength": 1 },
|
||||||
|
"default": []
|
||||||
|
},
|
||||||
|
"keywords_context": {
|
||||||
|
"type": "array",
|
||||||
|
"description": "Keywords for contextual / semantic routing (broader match, may need disambiguation).",
|
||||||
"items": { "type": "string", "minLength": 1 },
|
"items": { "type": "string", "minLength": 1 },
|
||||||
"default": []
|
"default": []
|
||||||
},
|
},
|
||||||
@@ -56,7 +62,7 @@
|
|||||||
},
|
},
|
||||||
"keyword_overrides": {
|
"keyword_overrides": {
|
||||||
"type": "object",
|
"type": "object",
|
||||||
"description": "Admin-corrected keyword→room mappings (learned from !r overrides).",
|
"description": "Admin-corrected keyword→room mappings (learned from !r overrides). Optional.",
|
||||||
"additionalProperties": { "type": "string" }
|
"additionalProperties": { "type": "string" }
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ Usage::
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import fcntl
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
@@ -170,14 +171,23 @@ class RoomMap:
|
|||||||
text_lower = text.lower()
|
text_lower = text.lower()
|
||||||
|
|
||||||
# Stufe 1: Prüfe 100% Evidenz Keywords zuerst
|
# Stufe 1: Prüfe 100% Evidenz Keywords zuerst
|
||||||
# EIN Treffer reicht für sofortigen Match (kein min_score)
|
# Bei mehreren Räumen mit 100%-Matches: den mit den MEISTEN Treffern nehmen
|
||||||
|
best_100_room: Optional[RoomEntry] = None
|
||||||
|
best_100_score: int = 0
|
||||||
|
|
||||||
for room in self._rooms.values():
|
for room in self._rooms.values():
|
||||||
if room.catch_all:
|
if room.catch_all:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Prüfe ob 100% Keywords matchen
|
# Zähle 100%-Keyword-Treffer
|
||||||
if any(kw.lower() in text_lower for kw in room.keywords_100):
|
score_100 = sum(1 for kw in room.keywords_100 if kw.lower() in text_lower)
|
||||||
return room
|
if score_100 > best_100_score:
|
||||||
|
best_100_score = score_100
|
||||||
|
best_100_room = room
|
||||||
|
|
||||||
|
# Wenn mindestens ein 100%-Match existiert → sofort diesen Raum zurückgeben
|
||||||
|
if best_100_room is not None and best_100_score > 0:
|
||||||
|
return best_100_room
|
||||||
|
|
||||||
# Stufe 2: Origin-Priorität mit kontextabhängigen Keywords
|
# Stufe 2: Origin-Priorität mit kontextabhängigen Keywords
|
||||||
# Origin-Priorität gilt NUR für context-Keywords (100% schlagen immer durch)
|
# Origin-Priorität gilt NUR für context-Keywords (100% schlagen immer durch)
|
||||||
@@ -403,8 +413,11 @@ class RoomMap:
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def save(room_map: 'RoomMap', path: Optional[Path] = None) -> None:
|
def save(room_map: 'RoomMap', path: Optional[Path] = None) -> None:
|
||||||
"""Speichert die RoomMap in eine JSON-Datei.
|
"""Speichert die RoomMap in eine JSON-Datei mit File-Lock.
|
||||||
|
|
||||||
|
Verwendet ``fcntl.flock`` (exklusiver Lock) um parallele
|
||||||
|
Schreibzugriffe zu verhindern. Blockiert maximal 5 Sekunden.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
room_map: Die zu speichernde RoomMap-Instanz
|
room_map: Die zu speichernde RoomMap-Instanz
|
||||||
path: Pfad zur JSON-Datei. Standardwert aus Umgebungsvariablen oder DEFAULT_MAP_PATH.
|
path: Pfad zur JSON-Datei. Standardwert aus Umgebungsvariablen oder DEFAULT_MAP_PATH.
|
||||||
@@ -436,9 +449,21 @@ class RoomMap:
|
|||||||
"catch_all": room_entry.catch_all
|
"catch_all": room_entry.catch_all
|
||||||
}
|
}
|
||||||
|
|
||||||
# Schreibe die Datei
|
# Schreibe die Datei mit exklusivem File-Lock
|
||||||
with open(path, "w", encoding="utf-8") as f:
|
with open(path, "w", encoding="utf-8") as f:
|
||||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
try:
|
||||||
|
fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
|
except BlockingIOError:
|
||||||
|
logger.warning(
|
||||||
|
"RoomMap.save: file locked, retrying with blocking lock (5s timeout)"
|
||||||
|
)
|
||||||
|
fcntl.flock(f.fileno(), fcntl.LOCK_EX) # blocking
|
||||||
|
try:
|
||||||
|
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||||
|
f.flush()
|
||||||
|
os.fsync(f.fileno())
|
||||||
|
finally:
|
||||||
|
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _from_dict(cls, data: dict) -> RoomMap:
|
def _from_dict(cls, data: dict) -> RoomMap:
|
||||||
|
|||||||
+61
-21
@@ -297,10 +297,33 @@ class BidirectionalRouter:
|
|||||||
stay_in_room=True,
|
stay_in_room=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# ── Schritt 4.5: Keyword-Matching vor LLM (FIX 2) ────────────
|
||||||
|
# Wenn Embedding 'work_order' mit niedriger Konfidenz (< 0.9):
|
||||||
|
# versuche Keyword-Match bevor wir das LLM aufrufen.
|
||||||
|
# Verhindert unnötige LLM-Calls für Nachrichten mit klaren Keywords.
|
||||||
|
if result is not None and result.category == "work_order" and result.confidence < 0.9:
|
||||||
|
matched_room = self._room_map.find_room_by_keywords(text, origin_room_id=origin_room_id)
|
||||||
|
if matched_room is not None:
|
||||||
|
logger.info(
|
||||||
|
"Keyword-Match vor LLM: '%s' → %s (embedding conf=%.3f)",
|
||||||
|
text[:80], matched_room.name, result.confidence,
|
||||||
|
)
|
||||||
|
room_name = matched_room.name.replace("#", "") if matched_room.name.startswith("#") else matched_room.name
|
||||||
|
notification = f"📋 Bearbeite ich in #{room_name} — [Link]"
|
||||||
|
matched_keywords = self._extract_matched_keywords(text, matched_room)
|
||||||
|
return RoutingDecision(
|
||||||
|
category="work_order",
|
||||||
|
target_room=matched_room.room_id,
|
||||||
|
confidence=0.95,
|
||||||
|
matched_room_name=matched_room.name,
|
||||||
|
source_room_notification=notification,
|
||||||
|
matched_keywords=matched_keywords,
|
||||||
|
)
|
||||||
|
|
||||||
# ── Schritt 5: LLM-Raum-Router (zentraler Prompt) ────────────
|
# ── Schritt 5: LLM-Raum-Router (zentraler Prompt) ────────────
|
||||||
# LLM_ROOM_PROMPT erhält Nachricht + Raumliste mit Keywords,
|
# LLM_ROOM_PROMPT erhält Nachricht + Raumliste mit Keywords,
|
||||||
# liefert room_id direkt (keine Kategorien, kein Name-Matching)
|
# liefert room_id direkt (keine Kategorien, kein Name-Matching)
|
||||||
llm_room = self._llm_room_lookup(text)
|
llm_room, llm_failed = self._llm_room_lookup(text)
|
||||||
if llm_room is not None:
|
if llm_room is not None:
|
||||||
room_name = llm_room.name.replace("#", "") if llm_room.name.startswith("#") else llm_room.name
|
room_name = llm_room.name.replace("#", "") if llm_room.name.startswith("#") else llm_room.name
|
||||||
logger.info(
|
logger.info(
|
||||||
@@ -321,18 +344,33 @@ class BidirectionalRouter:
|
|||||||
move_request_target_id=llm_room.room_id,
|
move_request_target_id=llm_room.room_id,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ── Schritt 7: Kein Treffer → catch_all ──────────────────────
|
# ── Schritt 7: LLM-Fehler oder kein Treffer ──────────────────
|
||||||
logger.info(
|
if llm_failed:
|
||||||
"LLM-Raum-Router: kein Treffer für '%.80s...' → catch_all", text
|
# FIX 1: Timeout/Exception → Fallback auf Ursprungsraum, NICHT Catch-All
|
||||||
)
|
logger.warning(
|
||||||
catch_all = self._room_map.catch_all_room
|
"LLM-Raum-Router: Aufruf fehlgeschlagen für '%.80s...' → stay_in_room (Ursprungsraum)",
|
||||||
return RoutingDecision(
|
text,
|
||||||
category="direct_question",
|
)
|
||||||
target_room=catch_all.room_id if catch_all else "",
|
return RoutingDecision(
|
||||||
confidence=0.0,
|
category="direct_question",
|
||||||
is_catch_all=True,
|
target_room="",
|
||||||
stay_in_room=True,
|
confidence=0.0,
|
||||||
)
|
stay_in_room=True,
|
||||||
|
is_catch_all=False,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# LLM erfolgreich, aber kein Match → catch_all
|
||||||
|
logger.info(
|
||||||
|
"LLM-Raum-Router: kein Treffer für '%.80s...' → catch_all", text
|
||||||
|
)
|
||||||
|
catch_all = self._room_map.catch_all_room
|
||||||
|
return RoutingDecision(
|
||||||
|
category="direct_question",
|
||||||
|
target_room=catch_all.room_id if catch_all else "",
|
||||||
|
confidence=0.0,
|
||||||
|
is_catch_all=True,
|
||||||
|
stay_in_room=True,
|
||||||
|
)
|
||||||
|
|
||||||
def _check_unrouteable(self, decision: RoutingDecision) -> None:
|
def _check_unrouteable(self, decision: RoutingDecision) -> None:
|
||||||
"""Validate target_room against subscribed IDs.
|
"""Validate target_room against subscribed IDs.
|
||||||
@@ -372,7 +410,7 @@ class BidirectionalRouter:
|
|||||||
|
|
||||||
return catch_all.room_id
|
return catch_all.room_id
|
||||||
|
|
||||||
def _llm_room_lookup(self, text: str) -> Optional[RoomEntry]:
|
def _llm_room_lookup(self, text: str) -> Tuple[Optional[RoomEntry], bool]:
|
||||||
"""Fragt das LLM: „In welchen Raum gehört diese Nachricht?“
|
"""Fragt das LLM: „In welchen Raum gehört diese Nachricht?“
|
||||||
|
|
||||||
Baut eine Raum-Liste mit IDs, Namen und ALLEN Keywords aus der RoomMap
|
Baut eine Raum-Liste mit IDs, Namen und ALLEN Keywords aus der RoomMap
|
||||||
@@ -383,7 +421,9 @@ class BidirectionalRouter:
|
|||||||
text: Der Nachrichtentext.
|
text: Der Nachrichtentext.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
Den gematchten ``RoomEntry``, oder ``None`` bei Fehler/kein Match.
|
(RoomEntry, False) — LLM erfolgreich, Raum gefunden
|
||||||
|
(None, False) — LLM erfolgreich, kein Match (CATCH_ALL)
|
||||||
|
(None, True) — LLM-Aufruf fehlgeschlagen (Exception/Timeout)
|
||||||
"""
|
"""
|
||||||
# Build room list for LLM prompt: "ID | Name | Keywords"
|
# Build room list for LLM prompt: "ID | Name | Keywords"
|
||||||
room_list_parts = []
|
room_list_parts = []
|
||||||
@@ -412,29 +452,29 @@ class BidirectionalRouter:
|
|||||||
# Try LLM — expects room ID directly
|
# Try LLM — expects room ID directly
|
||||||
llm_result = self._classifier._llm_raw_sync(prompt)
|
llm_result = self._classifier._llm_raw_sync(prompt)
|
||||||
if llm_result is None:
|
if llm_result is None:
|
||||||
return None
|
return None, True # LLM-Aufruf fehlgeschlagen
|
||||||
|
|
||||||
# Parse LLM response — should be a room ID or "CATCH_ALL"
|
# Parse LLM response — should be a room ID or "CATCH_ALL"
|
||||||
response = llm_result.strip()
|
response = llm_result.strip()
|
||||||
|
|
||||||
if response.upper() in ("CATCH_ALL", "CATCH-ALL", "CATCHALL"):
|
if response.upper() in ("CATCH_ALL", "CATCH-ALL", "CATCHALL"):
|
||||||
return None
|
return None, False # LLM erfolgreich, kein Match
|
||||||
|
|
||||||
# Direct lookup by room ID (LLM returns the ID directly)
|
# Direct lookup by room ID (LLM returns the ID directly)
|
||||||
room = self._room_map.get_room_by_id(response)
|
room = self._room_map.get_room_by_id(response)
|
||||||
if room is not None:
|
if room is not None:
|
||||||
return room
|
return room, False
|
||||||
|
|
||||||
# Fallback: try name matching (for LLMs that return names instead of IDs)
|
# Fallback: try name matching (for LLMs that return names instead of IDs)
|
||||||
response_lower = response.lower()
|
response_lower = response.lower()
|
||||||
for room in self._room_map.rooms.values():
|
for room in self._room_map.rooms.values():
|
||||||
if response_lower == room.name.lower():
|
if response_lower == room.name.lower():
|
||||||
return room
|
return room, False
|
||||||
if response_lower in room.name.lower():
|
if response_lower in room.name.lower():
|
||||||
return room
|
return room, False
|
||||||
|
|
||||||
logger.debug("LLM returned unknown room: %s", response)
|
logger.debug("LLM returned unknown room: %s", response)
|
||||||
return None
|
return None, False
|
||||||
|
|
||||||
# ── Route Validation ─────────────────────────────────────────────
|
# ── Route Validation ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
|||||||
@@ -24,14 +24,15 @@ class TestAutoOnboarding(unittest.TestCase):
|
|||||||
self.temp_dir = tempfile.TemporaryDirectory()
|
self.temp_dir = tempfile.TemporaryDirectory()
|
||||||
self.temp_path = Path(self.temp_dir.name) / "room-map.json"
|
self.temp_path = Path(self.temp_dir.name) / "room-map.json"
|
||||||
|
|
||||||
# Mock-Daten für die RoomMap
|
# Mock-Daten für die RoomMap (v2 Schema)
|
||||||
self.test_data = {
|
self.test_data = {
|
||||||
"version": 1,
|
"version": 2,
|
||||||
"rooms": {
|
"rooms": {
|
||||||
"catchall_room_id": {
|
"catchall_room_id": {
|
||||||
"name": "#CatchAll",
|
"name": "#CatchAll",
|
||||||
"theme": "Catch-all room for everything else",
|
"theme": "Catch-all room for everything else",
|
||||||
"keywords": [],
|
"keywords_100": [],
|
||||||
|
"keywords_context": [],
|
||||||
"catch_all": True
|
"catch_all": True
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -136,18 +137,20 @@ class TestAutoOnboarding(unittest.TestCase):
|
|||||||
|
|
||||||
# Erstelle Testdaten mit bereits vorhandenen Räumen
|
# Erstelle Testdaten mit bereits vorhandenen Räumen
|
||||||
test_data_with_rooms = {
|
test_data_with_rooms = {
|
||||||
"version": 1,
|
"version": 2,
|
||||||
"rooms": {
|
"rooms": {
|
||||||
"catchall_room_id": {
|
"catchall_room_id": {
|
||||||
"name": "#CatchAll",
|
"name": "#CatchAll",
|
||||||
"theme": "Catch-all room for everything else",
|
"theme": "Catch-all room for everything else",
|
||||||
"keywords": [],
|
"keywords_100": [],
|
||||||
|
"keywords_context": [],
|
||||||
"catch_all": True
|
"catch_all": True
|
||||||
},
|
},
|
||||||
"room1_id": {
|
"room1_id": {
|
||||||
"name": "#Room1",
|
"name": "#Room1",
|
||||||
"theme": "First test room",
|
"theme": "First test room",
|
||||||
"keywords": ["test"],
|
"keywords_100": ["test"],
|
||||||
|
"keywords_context": [],
|
||||||
"catch_all": False
|
"catch_all": False
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -174,5 +177,124 @@ class TestAutoOnboarding(unittest.TestCase):
|
|||||||
self.assertEqual(len(missing), 0)
|
self.assertEqual(len(missing), 0)
|
||||||
|
|
||||||
|
|
||||||
|
class TestAutoOnboardingV2(unittest.TestCase):
|
||||||
|
"""v2-spezifische Tests: keywords_100/keywords_context Trennung, File-Lock."""
|
||||||
|
|
||||||
|
def setUp(self):
|
||||||
|
self.temp_dir = tempfile.TemporaryDirectory()
|
||||||
|
self.temp_path = Path(self.temp_dir.name) / "room-map.json"
|
||||||
|
|
||||||
|
self.test_data = {
|
||||||
|
"version": 2,
|
||||||
|
"rooms": {
|
||||||
|
"catchall_room_id": {
|
||||||
|
"name": "#CatchAll",
|
||||||
|
"theme": "Catch-all room",
|
||||||
|
"keywords_100": [],
|
||||||
|
"keywords_context": [],
|
||||||
|
"catch_all": True
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"excluded_rooms": [],
|
||||||
|
"fact_store_path": str(self.temp_path.parent / "docs")
|
||||||
|
}
|
||||||
|
with open(self.temp_path, 'w') as f:
|
||||||
|
json.dump(self.test_data, f)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.temp_dir.cleanup()
|
||||||
|
|
||||||
|
def test_v2_add_or_update_room_separate_keywords(self):
|
||||||
|
"""Testet dass add_or_update_room keywords_100 und keywords_context trennt."""
|
||||||
|
room_map = RoomMap._from_dict(self.test_data)
|
||||||
|
|
||||||
|
room_map.add_or_update_room(
|
||||||
|
room_id="proj_room_id",
|
||||||
|
name="#Projektraum",
|
||||||
|
theme="Entwicklung des Plugins",
|
||||||
|
keywords_100=["plugin", "gateway"],
|
||||||
|
keywords_context=["architektur", "deployment"],
|
||||||
|
catch_all=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
entry = room_map.rooms["proj_room_id"]
|
||||||
|
self.assertEqual(entry.keywords_100, ["plugin", "gateway"])
|
||||||
|
self.assertEqual(entry.keywords_context, ["architektur", "deployment"])
|
||||||
|
self.assertNotEqual(entry.keywords_100, entry.keywords_context)
|
||||||
|
|
||||||
|
def test_v2_single_room_auto_catch_all_fields(self):
|
||||||
|
"""Testet dass Single-Room-Regel v2-Felder korrekt setzt."""
|
||||||
|
room_map = RoomMap._from_dict(self.test_data)
|
||||||
|
|
||||||
|
# Simuliere: nur 1 relevanter Raum, nicht in Map
|
||||||
|
room_map.add_or_update_room(
|
||||||
|
room_id="single_room_id",
|
||||||
|
name="#SingleRoom",
|
||||||
|
theme="Automatisch zugewiesener Catch-All-Raum",
|
||||||
|
keywords_100=[],
|
||||||
|
keywords_context=[],
|
||||||
|
catch_all=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
entry = room_map.rooms["single_room_id"]
|
||||||
|
self.assertTrue(entry.catch_all)
|
||||||
|
self.assertEqual(entry.keywords_100, [])
|
||||||
|
self.assertEqual(entry.keywords_context, [])
|
||||||
|
# Altes catch_all (catchall_room_id) sollte NICHT mehr catch_all sein
|
||||||
|
self.assertFalse(room_map.rooms["catchall_room_id"].catch_all)
|
||||||
|
|
||||||
|
def test_v2_save_with_file_lock(self):
|
||||||
|
"""Testet dass RoomMap.save() mit File-Lock funktioniert."""
|
||||||
|
room_map = RoomMap._from_dict(self.test_data)
|
||||||
|
room_map.add_or_update_room(
|
||||||
|
room_id="test_room_id",
|
||||||
|
name="#TestRaum",
|
||||||
|
theme="Test-Thema",
|
||||||
|
keywords_100=["test"],
|
||||||
|
keywords_context=["versuch"],
|
||||||
|
catch_all=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Save sollte ohne Exception durchlaufen
|
||||||
|
RoomMap.save(room_map, self.temp_path)
|
||||||
|
|
||||||
|
# Reload und verifiziere
|
||||||
|
reloaded = RoomMap.load(self.temp_path)
|
||||||
|
entry = reloaded.rooms["test_room_id"]
|
||||||
|
self.assertEqual(entry.name, "#TestRaum")
|
||||||
|
self.assertEqual(entry.theme, "Test-Thema")
|
||||||
|
self.assertEqual(entry.keywords_100, ["test"])
|
||||||
|
self.assertEqual(entry.keywords_context, ["versuch"])
|
||||||
|
self.assertFalse(entry.catch_all)
|
||||||
|
|
||||||
|
def test_v2_reload_updates_in_memory(self):
|
||||||
|
"""Testet dass reload() die In-Memory-Daten aktualisiert."""
|
||||||
|
room_map = RoomMap._from_dict(self.test_data)
|
||||||
|
|
||||||
|
# Schreibe eine geänderte Map auf Disk
|
||||||
|
modified_data = dict(self.test_data)
|
||||||
|
modified_data["rooms"]["new_room_id"] = {
|
||||||
|
"name": "#NeuerRaum",
|
||||||
|
"theme": "Neues Thema",
|
||||||
|
"keywords_100": ["neu"],
|
||||||
|
"keywords_context": ["frisch"],
|
||||||
|
"catch_all": False,
|
||||||
|
}
|
||||||
|
with open(self.temp_path, 'w') as f:
|
||||||
|
json.dump(modified_data, f)
|
||||||
|
|
||||||
|
# Vor reload: new_room_id nicht in Map
|
||||||
|
self.assertNotIn("new_room_id", room_map.rooms)
|
||||||
|
|
||||||
|
# Reload
|
||||||
|
room_map.reload(self.temp_path)
|
||||||
|
|
||||||
|
# Nach reload: new_room_id in Map
|
||||||
|
self.assertIn("new_room_id", room_map.rooms)
|
||||||
|
entry = room_map.rooms["new_room_id"]
|
||||||
|
self.assertEqual(entry.keywords_100, ["neu"])
|
||||||
|
self.assertEqual(entry.keywords_context, ["frisch"])
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
+25
-78
@@ -1,102 +1,49 @@
|
|||||||
{
|
{
|
||||||
|
"_comment": "EXAMPLE ROOM MAP — Replace with your own rooms. See room-map.schema.json for the full schema.",
|
||||||
"version": 2,
|
"version": 2,
|
||||||
"rooms": {
|
"rooms": {
|
||||||
"6a049d493a62ef8f1ead2320": {
|
"ROOM_ID_1": {
|
||||||
"name": "#BAT-Team",
|
"name": "#Mein-Projektraum",
|
||||||
"theme": "Bot Agent Team, Trade, BAT, Projektarbeit an Bot Agent Team — Trading-Plattform, Multi-Agent-System, Krypto-Analysen, Wyckoff-Methodik, Boot-Window",
|
"theme": "Beschreibe hier, worum es in diesem Raum geht — 1-2 Sätze, die das Thema klar umreißen.",
|
||||||
"keywords_100": [
|
"keywords_100": [
|
||||||
"bat",
|
"projekt",
|
||||||
"bat-team",
|
"keyword1",
|
||||||
"trading",
|
"keyword2"
|
||||||
"krypto",
|
|
||||||
"wyckoff",
|
|
||||||
"boot-window",
|
|
||||||
"börse",
|
|
||||||
"exchange",
|
|
||||||
"analyst",
|
|
||||||
"control-tower"
|
|
||||||
],
|
],
|
||||||
"keywords_context": [
|
"keywords_context": [
|
||||||
"gateway",
|
"kontext1",
|
||||||
"bot"
|
"kontext2"
|
||||||
],
|
],
|
||||||
"catch_all": false
|
"catch_all": false
|
||||||
},
|
},
|
||||||
"6a19b0ff02aeecd36b1aa16c": {
|
"ROOM_ID_2": {
|
||||||
"name": "#Rocketchat-Plugin",
|
"name": "#Zweiter-Raum",
|
||||||
"theme": "Rocketchat, Hermes Gateway, RC, Projektarbeit an Rocketchat Plugin — Hermes Plugin für Rocket.Chat, DDP/WebSocket, Archivar, Deployment",
|
"theme": "Thema des zweiten Raums.",
|
||||||
"keywords_100": [
|
"keywords_100": [
|
||||||
"rocketchat",
|
"anderes-thema"
|
||||||
"rc",
|
|
||||||
"ddp",
|
|
||||||
"websocket",
|
|
||||||
"adapter",
|
|
||||||
"install.sh"
|
|
||||||
],
|
|
||||||
"keywords_context": [
|
|
||||||
"plugin",
|
|
||||||
"gateway",
|
|
||||||
"deployment",
|
|
||||||
"button",
|
|
||||||
"sync",
|
|
||||||
"archivar",
|
|
||||||
"hermes"
|
|
||||||
],
|
|
||||||
"catch_all": false
|
|
||||||
},
|
|
||||||
"6a1c56d4b73efec2bebec2db": {
|
|
||||||
"name": "#LAN-Dokumentation",
|
|
||||||
"theme": "LAN Dokumentation, Homelab, RZBLN, Doku — Dokumentation des Heimnetzwerks, Proxmox, Subnetze, IP-Adressen",
|
|
||||||
"keywords_100": [
|
|
||||||
"lan",
|
|
||||||
"dokumentation",
|
|
||||||
"homelab",
|
|
||||||
"netzwerk",
|
|
||||||
"router",
|
|
||||||
"switch",
|
|
||||||
"subnetz",
|
|
||||||
"proxmox",
|
|
||||||
"heimnetz",
|
|
||||||
"ip-adresse",
|
|
||||||
"rzbln"
|
|
||||||
],
|
],
|
||||||
"keywords_context": [],
|
"keywords_context": [],
|
||||||
"catch_all": false
|
"catch_all": false
|
||||||
},
|
},
|
||||||
"69f8beaef06dba03be82f9fc": {
|
"ROOM_ID_DM": {
|
||||||
"name": "#Protonbridge-Plugin",
|
"name": "DM mit Operator",
|
||||||
"theme": "Proton Mail Bridge, Hermes Mailschnittstelle, PB, Projektarbeit an Proton Mail Bridge Plugin — Hermes Plugin für Proton Mail Bridge, SMTP/IMAP",
|
"theme": "Direktnachrichten — Strategie, Meta-Entscheidungen, Catch-All für alle Themen ohne eigenen Raum",
|
||||||
"keywords_100": [
|
"keywords_100": [
|
||||||
"protonbridge",
|
"strategie",
|
||||||
"proton",
|
"entscheidung",
|
||||||
"mail",
|
"planung"
|
||||||
"bridge",
|
|
||||||
"email",
|
|
||||||
"smtp",
|
|
||||||
"imap",
|
|
||||||
"pb"
|
|
||||||
],
|
],
|
||||||
"keywords_context": [
|
"keywords_context": [
|
||||||
"plugin",
|
"meta",
|
||||||
"deployment"
|
"roadmap",
|
||||||
|
"priorisierung"
|
||||||
],
|
],
|
||||||
"catch_all": false
|
|
||||||
},
|
|
||||||
"69f4e777f06dba03be82dce7": {
|
|
||||||
"name": "DM mit Andreas",
|
|
||||||
"theme": "Direktnachrichten — Catch-All für alle Themen ohne eigenen Raum",
|
|
||||||
"keywords_100": [],
|
|
||||||
"keywords_context": [],
|
|
||||||
"catch_all": true
|
"catch_all": true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"excluded_rooms": [
|
"excluded_rooms": [
|
||||||
"6a049d493a62ef8f1ead2320",
|
"ROOM_ID_TEST_BOT_1",
|
||||||
"6a1c56d4b73efec2bebec2db",
|
"ROOM_ID_TEST_BOT_2"
|
||||||
"69f8beaef06dba03be82f9fc",
|
|
||||||
"6a19b0ff02aeecd36b1aa16c",
|
|
||||||
"6a0f4b2991db1dbf570a5442",
|
|
||||||
"6a21495ede3de7118e84d82e"
|
|
||||||
],
|
],
|
||||||
"fact_store_path": "/data/Wissensdatenbank/0100 Inbox"
|
"fact_store_path": "~/archivar_docs"
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user