feat: V8.3 — Menschenähnliches Routing (Ankündigung, Move, Widerspruch, Expliziter Wechsel, Topic-Scoped Sticky)

V8.3-1: Auto-Route Ankündigung
- Vor Zielraum-Post: Hinweis im Ursprungsraum
- Text: 'Lass uns das Thema in #<target> aufgreifen. Ich nehme das Thema mit.'
- target_name aus room-map.json name-Feld

V8.3-2: Echtes Move (delete_message + Fallback-Kette)
- RocketChatREST: delete_message() + update_message() hinzugefügt
- Auto-Route-Block: delete → edit → Hinweis-Post Fallback
- Permissions optional (Fallback-Kette macht delete-message optional)

V8.3-3: Widerspruchs-Routine (Rückholen)
- Keyword-Detector: halt, bleib hier, gehört hier her, nein, stop, etc.
- _recent_auto_routes Dict speichert letzte Auto-Routes
- 10 Min Zeitfenster: Thema zurückholen, Sticky löschen, KEIN Lernen
- Ring: move_gc(target → origin) für Rückholung

V8.3-4: Expliziter Raumwechsel
- Pattern: 'lass uns in #<raum>', 'wechseln nach #<raum>', etc.
- Raum aus room-map.json auflösen (name → room_id)
- Sticky: 30 Min, sticky_topic='explizit-wechsel'
- Agent antwortet: 'Gerne, wir sind jetzt in #<raum>.'

V8.3-5: Topic-Scoped Sticky (konservative Variante)
- _session_room_preferences um sticky_topic-Feld erweitert
- Vor Sticky-Auto-Route: Thema aus aktueller Nachricht extrahieren
- Gleiches Thema → Sticky greift; anderes Thema → STAY, normale Auswertung
- Kein Thema extrahierbar → Sticky greift (Fallback)

Tests: 25 neue Tests (4-6 pro Punkt), alle grün
460 passed, 1 pre-existing fail (test_no_env_vars, legacy env var migration)
This commit is contained in:
Bernd (Hermes)
2026-07-15 08:15:35 +02:00
parent de930a1227
commit 9855b5794f
3 changed files with 1669 additions and 86 deletions
File diff suppressed because it is too large Load Diff
+278 -15
View File
@@ -215,6 +215,36 @@ class RocketChatREST:
logger.debug("File download failed: %s", e) logger.debug("File download failed: %s", e)
return None return None
def delete_message(self, room_id: str, message_id: str) -> bool:
"""V8.3-2: Delete a message via REST API DELETE /api/v1/chat.delete.
Returns True on success, False on failure (e.g. missing permission).
"""
if not self.auth_token:
return False
payload = {"roomId": room_id, "msgId": message_id}
r = self._request("POST", "/api/v1/chat.delete", headers={
"X-Auth-Token": self.auth_token,
"X-User-Id": self.user_id,
"Content-Type": "application/json",
}, data=payload)
return bool(r and r.get("success"))
def update_message(self, room_id: str, message_id: str, text: str) -> bool:
"""V8.3-2: Update a message via REST API POST /api/v1/chat.update.
Returns True on success, False on failure.
"""
if not self.auth_token:
return False
payload = {"roomId": room_id, "msgId": message_id, "text": text}
r = self._request("POST", "/api/v1/chat.update", headers={
"X-Auth-Token": self.auth_token,
"X-User-Id": self.user_id,
"Content-Type": "application/json",
}, data=payload)
return bool(r and r.get("success"))
class DDPClient: class DDPClient:
PING_INTERVAL = 8.0 PING_INTERVAL = 8.0
@@ -639,6 +669,12 @@ class RocketChatAdapter(BasePlatformAdapter):
# V8.1 P2: Temporäre Session-Raum-Präferenzen (30 Min TTL) # V8.1 P2: Temporäre Session-Raum-Präferenzen (30 Min TTL)
# Wird bei confirm_move gesetzt und vor Archivar-Klassifikation geprüft. # Wird bei confirm_move gesetzt und vor Archivar-Klassifikation geprüft.
self._session_room_preferences: Dict[str, Dict[str, Any]] = {} self._session_room_preferences: Dict[str, Dict[str, Any]] = {}
# V8.3-3: Recent auto-routes für Widerspruchs-Routine
# {origin_room: {target_room, topic, timestamp, origin_message_id, target_message_id}}
self._recent_auto_routes: Dict[str, Dict[str, Any]] = {}
# V8.3-4: Expliziter Raumwechsel-Sticky (30 Min TTL)
# {origin_room: {target_room, target_name, sticky_topic, expires_at}}
self._explicit_switch_sticky: Dict[str, Dict[str, Any]] = {}
# V7-2: _sticky_rooms removed — thematic never_route replaces spatial bypass. # V7-2: _sticky_rooms removed — thematic never_route replaces spatial bypass.
# The router's _check_never_route_topic handles per-topic blocking now. # The router's _check_never_route_topic handles per-topic blocking now.
# Clarify state: maps clarify_id → session_key for gateway resolution # Clarify state: maps clarify_id → session_key for gateway resolution
@@ -1485,10 +1521,16 @@ class RocketChatAdapter(BasePlatformAdapter):
_THEMATIC_TARGET_ROOM.set(move_req["target_room"]) _THEMATIC_TARGET_ROOM.set(move_req["target_room"])
forwarded = True forwarded = True
feedback_type = "confirm" feedback_type = "confirm"
# V8.1 P2: Temporäres Sticky für aktive Session (30 Min TTL) # ── V8.3-5: Topic für Sticky extrahieren ──────────────
move_sticky_topic = ""
if _MULTIROOM() and self.archivar is not None:
target_name = move_req.get("target_name", "")
move_sticky_topic = room_name_to_topic(target_name) if target_name else ""
# V8.3-5: Temporäres Sticky mit Topic-Scoping (30 Min TTL)
self._session_room_preferences[room_id] = { self._session_room_preferences[room_id] = {
"target_room": move_req["target_room"], "target_room": move_req["target_room"],
"target_name": move_req.get("target_name", "Zielraum"), "target_name": move_req.get("target_name", "Zielraum"),
"sticky_topic": move_sticky_topic,
"expires_at": time.time() + 1800, # 30 Minuten "expires_at": time.time() + 1800, # 30 Minuten
} }
# V8.1.1 R2: Ring-GC bei Move — stale Topics aus Ursprungsraum entfernen # V8.1.1 R2: Ring-GC bei Move — stale Topics aus Ursprungsraum entfernen
@@ -1502,10 +1544,19 @@ class RocketChatAdapter(BasePlatformAdapter):
topic=move_topic, topic=move_topic,
room_name=target_name, room_name=target_name,
) )
# ── V8.3-3: Move für Widerspruchs-Routine speichern ──
self._recent_auto_routes[room_id] = {
"origin_room": room_id,
"target_room": move_req["target_room"],
"topic": move_sticky_topic,
"timestamp": time.time(),
"origin_message_id": move_req.get("message_id", ""),
"target_message_id": "",
}
logger.info( logger.info(
"[rocketchat] V8.1 P2: Session-Sticky gesetzt — " "[rocketchat] V8.3-5: Session-Sticky gesetzt — "
"room=%s → target=%s (30 Min)", "room=%s → target=%s, topic='%s' (30 Min, confirm_move)",
room_id[:8], move_req.get("target_name", "?")[:20], room_id[:8], move_req.get("target_name", "?")[:20], move_sticky_topic,
) )
elif choice in ("2", "2️⃣", "generell", "generell hier bleiben", "stay_here"): elif choice in ("2", "2️⃣", "generell", "generell hier bleiben", "stay_here"):
# 2️⃣ Generell hier bleiben → Antwort im Ursprungsraum + Sticky-Eintrag # 2️⃣ Generell hier bleiben → Antwort im Ursprungsraum + Sticky-Eintrag
@@ -1612,6 +1663,142 @@ class RocketChatAdapter(BasePlatformAdapter):
forwarded = False forwarded = False
# ── V8.3-3: Widerspruchs-Routine (RÜCKHOLEN) ──────────────────────
# Prüft ob der User widerspricht ('Halt, das gehört hier her')
# innerhalb 10 Min nach einer Auto-Route.
_WIDERSPRUCH_KEYWORDS = [
'halt', 'bleib hier', 'gehört hier her', 'bleib hier',
'nein', 'stop', 'falscher raum', 'zurück', 'roll back', 'rollback',
]
text_lower = text.lower()
is_widerspruch = any(kw in text_lower for kw in _WIDERSPRUCH_KEYWORDS)
if is_widerspruch and room_id in self._recent_auto_routes:
route_info = self._recent_auto_routes[room_id]
elapsed = time.time() - route_info["timestamp"]
if elapsed <= 600: # 10 Min Zeitfenster
logger.info(
"[rocketchat] V8.3-3: Widerspruch erkannt in room %s — "
"%.0fs nach Auto-Route, hole Thema zurück",
room_id[:8], elapsed,
)
target_room_id = route_info["target_room"]
# a. Thema aus Zielraum entfernen (delete/edit)
target_msg_id = route_info.get("target_message_id", "")
if target_msg_id:
if not self.rest.delete_message(target_room_id, target_msg_id):
self.rest.update_message(
target_room_id, target_msg_id, "_(Zurückgezogen)_"
)
# b. Thema im Ursprungsraum wieder aufnehmen
await self._post_message_with_retry(
room_id,
"👍 Verstanden — das Thema gehört hier her. Ich bleibe hier."
)
# c. _CURRENT_ORIGIN_ROOM zurück auf Ursprungsraum
_CURRENT_ORIGIN_ROOM.set(room_id)
_THEMATIC_TARGET_ROOM.set("")
# d. Sticky löschen
self._session_room_preferences.pop(room_id, None)
# e. Ring: move_gc(target → origin) — Rückholung
if _MULTIROOM() and self._multiroom_context is not None:
route_topic = route_info.get("topic", "")
if route_topic:
await self._multiroom_context.move_gc(
origin_room_id=target_room_id,
target_room_id=room_id,
topic=route_topic,
room_name=self._room_info.get(room_id, {}).get("name", ""),
)
# f. KEIN Lernen
# g. Cleanup
del self._recent_auto_routes[room_id]
# Dispatch im Ursprungsraum
await self._dispatch_agent(
text=text,
room_id=room_id,
room_name=room_name,
room_type=room_type,
username=username,
msg_id=msg_id,
msg_obj=msg_obj,
is_button_response=is_button_response,
category="",
)
return
else:
# Zeitfenster abgelaufen → aufräumen
del self._recent_auto_routes[room_id]
# ── V8.3-4: Expliziter Raumwechsel (BEWUSSTE ENTSCHEIDUNG) ────────
# Pattern: 'lass uns in #<raum> wechseln', 'wechseln nach #<raum>', etc.
_EXPLICIT_SWITCH_RE = re.compile(
r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)',
re.IGNORECASE,
)
_SWITCH_TRIGGERS = [
'lass uns in', 'gehen wir in', 'wechseln nach', 'wechsel in',
'raum wechseln', 'wechseln in',
]
is_explicit_switch = any(trigger in text_lower for trigger in _SWITCH_TRIGGERS)
if is_explicit_switch and _MULTIROOM() and self.archivar is not None:
switch_match = _EXPLICIT_SWITCH_RE.search(text)
if switch_match:
switch_room_name = switch_match.group(1).lower()
# Raum aus room-map.json auflösen (name → room_id)
target_room_id = ""
target_room_display = ""
room_map = self.archivar._room_map
if room_map is not None:
for rid, entry in room_map.rooms.items():
entry_name = entry.name.lstrip('#').lower().replace(' ', '-')
if switch_room_name in entry_name or entry_name in switch_room_name:
target_room_id = rid
target_room_display = entry.name
break
if target_room_id and target_room_id != room_id:
logger.info(
"[rocketchat] V8.3-4: Expliziter Raumwechsel — "
"'%s' → %s (%s)",
text[:80], target_room_display, target_room_id[:8],
)
# a. _CURRENT_ORIGIN_ROOM auf Zielraum setzen
_CURRENT_ORIGIN_ROOM.set(target_room_id)
_THEMATIC_TARGET_ROOM.set(target_room_id)
# b. Sticky setzen: 30 Min, sticky_topic = 'explizit-wechsel'
self._session_room_preferences[room_id] = {
"target_room": target_room_id,
"target_name": target_room_display,
"sticky_topic": "explizit-wechsel",
"expires_at": time.time() + 1800, # 30 Min
}
logger.info(
"[rocketchat] V8.3-4: Expliziter Wechsel-Sticky gesetzt — "
"room=%s → target=%s (30 Min)",
room_id[:8], target_room_display[:20],
)
# c. Agent antwortet im Zielraum
await self._post_message_with_retry(
target_room_id,
f"Gerne, wir sind jetzt in {target_room_display}. "
f"Was möchtest du besprechen?"
)
# Dispatch im Zielraum
target_room_info = self._room_info.get(target_room_id, {})
target_room_name_disp = target_room_info.get("name", target_room_display)
target_room_type = target_room_info.get("type", "c")
await self._dispatch_agent(
text=text,
room_id=target_room_id,
room_name=target_room_name_disp,
room_type=target_room_type,
username=username,
msg_id=msg_id,
msg_obj=msg_obj,
is_button_response=is_button_response,
category="",
)
return
# ── Archivar-Klassifikation (User-Flow C) ────────────────────────── # ── Archivar-Klassifikation (User-Flow C) ──────────────────────────
# Klassifiziere die Nachricht und entscheide über Copy/Routing. # Klassifiziere die Nachricht und entscheide über Copy/Routing.
# Die Antwort des Agenten bleibt IMMER im Ursprungsraum. # Die Antwort des Agenten bleibt IMMER im Ursprungsraum.
@@ -1647,11 +1834,33 @@ class RocketChatAdapter(BasePlatformAdapter):
routing_counter.increment('dm_routing_skipped') routing_counter.increment('dm_routing_skipped')
logger.info("ROUTING BYPASS: reason=dm_routing_skipped, origin_room=%s", room_id) logger.info("ROUTING BYPASS: reason=dm_routing_skipped, origin_room=%s", room_id)
elif room_id in self._session_room_preferences: elif room_id in self._session_room_preferences:
# V8.1 P2: Temporäres Session-Sticky — Auto-Route ohne Archivar # V8.3-5: Topic-Scoped Session-Sticky — Auto-Route nur bei gleichem Thema
pref = self._session_room_preferences[room_id] pref = self._session_room_preferences[room_id]
if time.time() < pref["expires_at"]: if time.time() < pref["expires_at"]:
target_room_id = pref["target_room"] target_room_id = pref["target_room"]
target_name = pref.get("target_name", "Zielraum") target_name = pref.get("target_name", "Zielraum")
sticky_topic = pref.get("sticky_topic", "")
# ── V8.3-5: Topic-Scoping — Thema aus aktueller Nachricht extrahieren ──
current_topic = ""
if sticky_topic and _MULTIROOM() and self.archivar is not None:
# Extrahiere Thema via 100%-Keyword-Match gegen alle Räume
matched_room = self.archivar._room_map.find_room_by_keywords(
text, origin_room_id=room_id
)
if matched_room is not None:
current_topic = room_name_to_topic(matched_room.name)
# ── V8.3-5: Topic-Vergleich ──────────────────────
if sticky_topic and current_topic and current_topic != sticky_topic:
# Thema ≠ sticky_topic → STAY, Sticky ignorieren, normale Auswertung
logger.info(
"[rocketchat] V8.3-5: Topic mismatch — sticky_topic='%s', "
"current_topic='%s' → ignoring sticky, falling through to Archivar",
sticky_topic, current_topic,
)
# Sticky NICHT löschen — könnte später wieder matchen
# Fall through to Archivar classification
else:
# Thema matcht ODER kein Topic extrahierbar → Sticky greift
# V8.1.1 R1: Catch-All-Guard — nicht in Catch-All-Raum auto-routen # V8.1.1 R1: Catch-All-Guard — nicht in Catch-All-Raum auto-routen
if self.archivar is not None and self.archivar._room_map is not None: if self.archivar is not None and self.archivar._room_map is not None:
target_entry = self.archivar._room_map.get_room_by_id(target_room_id) target_entry = self.archivar._room_map.get_room_by_id(target_room_id)
@@ -1684,9 +1893,9 @@ class RocketChatAdapter(BasePlatformAdapter):
_THEMATIC_TARGET_ROOM.set(target_room_id) _THEMATIC_TARGET_ROOM.set(target_room_id)
routing_counter.increment('session_sticky_auto_route') routing_counter.increment('session_sticky_auto_route')
logger.info( logger.info(
"[rocketchat] V8.1 P2: Session-Sticky active — " "[rocketchat] V8.3-5: Session-Sticky active — "
"auto-routing '%s' → %s (%.0fs remaining)", "auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
text[:80], target_name, text[:80], target_name, sticky_topic,
pref["expires_at"] - time.time(), pref["expires_at"] - time.time(),
) )
# Dispatch direkt — kein Archivar # Dispatch direkt — kein Archivar
@@ -1713,9 +1922,9 @@ class RocketChatAdapter(BasePlatformAdapter):
_THEMATIC_TARGET_ROOM.set(target_room_id) _THEMATIC_TARGET_ROOM.set(target_room_id)
routing_counter.increment('session_sticky_auto_route') routing_counter.increment('session_sticky_auto_route')
logger.info( logger.info(
"[rocketchat] V8.1 P2: Session-Sticky active — " "[rocketchat] V8.3-5: Session-Sticky active — "
"auto-routing '%s' → %s (%.0fs remaining)", "auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
text[:80], target_name, text[:80], target_name, sticky_topic,
pref["expires_at"] - time.time(), pref["expires_at"] - time.time(),
) )
# Dispatch direkt — kein Archivar # Dispatch direkt — kein Archivar
@@ -1818,6 +2027,50 @@ class RocketChatAdapter(BasePlatformAdapter):
and decision.target_room != room_id): and decision.target_room != room_id):
target_room_id = decision.target_room target_room_id = decision.target_room
target_name = getattr(decision, 'move_request_target_name', 'Zielraum') target_name = getattr(decision, 'move_request_target_name', 'Zielraum')
# ── V8.3-5: Topic für Sticky extrahieren ──────────────────
sticky_topic = ""
if _MULTIROOM() and self.archivar is not None:
matched_keywords = getattr(decision, 'matched_keywords', [])
if matched_keywords:
sticky_topic = matched_keywords[0] # Erstes gematchtes Keyword
else:
# Fallback: Raum-Name → Topic
sticky_topic = room_name_to_topic(target_name) if target_name else ""
# ── V8.3-1: Ankündigung im Ursprungsraum VOR Zielraum-Post ──
# Andreas: 'Der Mensch wartet. Er schreibt nicht: Halt, wir bleiben hier.'
target_display = target_name.lstrip('#') if target_name else "Zielraum"
announcement = f"Lass uns das Thema in #{target_display} aufgreifen. Ich nehme das Thema mit."
await self._post_message_with_retry(room_id, announcement)
logger.info(
"[rocketchat] V8.3-1: Auto-Route announcement in origin room %s → %s",
room_id[:8], target_display,
)
# ── V8.3-2: Echtes Move — delete_message mit Fallback-Kette ──
# Versuche Originalnachricht zu löschen/ersetzen
move_success = False
if msg_id:
# a. delete_message (falls Permission vorhanden)
if self.rest.delete_message(room_id, msg_id):
move_success = True
logger.info(
"[rocketchat] V8.3-2: Original message deleted in origin room %s",
room_id[:8],
)
else:
# b. Fallback: update_message → ersetze durch Hinweis
fallback_text = f"Wir sind rübergewechselt → #{target_display}"
if self.rest.update_message(room_id, msg_id, fallback_text):
move_success = True
logger.info(
"[rocketchat] V8.3-2: Original message edited in origin room %s",
room_id[:8],
)
else:
# c. Letzter Fallback: Nur Hinweis-Post (bereits gesendet)
logger.info(
"[rocketchat] V8.3-2: Move fallback — announcement only in room %s",
room_id[:8],
)
# Kopiere Nachricht in den Zielraum # Kopiere Nachricht in den Zielraum
target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{text}" target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{text}"
await self._post_message_with_retry(target_room_id, target_txt) await self._post_message_with_retry(target_room_id, target_txt)
@@ -1841,17 +2094,27 @@ class RocketChatAdapter(BasePlatformAdapter):
topic=auto_topic, topic=auto_topic,
room_name=target_name, room_name=target_name,
) )
# V8.1 P2: Temporäres Sticky für aktive Session (30 Min TTL) # V8.3-5: Temporäres Sticky mit Topic-Scoping (30 Min TTL)
self._session_room_preferences[room_id] = { self._session_room_preferences[room_id] = {
"target_room": target_room_id, "target_room": target_room_id,
"target_name": target_name, "target_name": target_name,
"sticky_topic": sticky_topic,
"expires_at": time.time() + 1800, "expires_at": time.time() + 1800,
} }
logger.info( logger.info(
"[rocketchat] V8.1 P2: Session-Sticky gesetzt — " "[rocketchat] V8.3-5: Session-Sticky gesetzt — "
"room=%s → target=%s (30 Min, Auto-Route)", "room=%s → target=%s, topic='%s' (30 Min, Auto-Route)",
room_id[:8], target_name[:20], room_id[:8], target_name[:20], sticky_topic,
) )
# ── V8.3-3: Auto-Route für Widerspruchs-Routine speichern ──
self._recent_auto_routes[room_id] = {
"origin_room": room_id,
"target_room": target_room_id,
"topic": sticky_topic,
"timestamp": time.time(),
"origin_message_id": msg_id,
"target_message_id": "", # Wird nach Zielraum-Post nicht getrackt
}
# _CURRENT_ORIGIN_ROOM wird NUR gesetzt wenn nicht forwarded. # _CURRENT_ORIGIN_ROOM wird NUR gesetzt wenn nicht forwarded.
# Bei forwarded (Auto-Route) wurde es bereits auf Zielraum gesetzt. # Bei forwarded (Auto-Route) wurde es bereits auf Zielraum gesetzt.
+292
View File
@@ -0,0 +1,292 @@
"""
V8.3: Tests für Menschenähnliches Routing + Topic-Scoped Sticky.
Prüft:
- V8.3-1: Auto-Route Ankündigung im Ursprungsraum
- V8.3-2: delete_message + Fallback-Kette (edit, Hinweis-Post)
- V8.3-3: Widerspruchs-Routine (Rückholen, Sticky löschen, KEIN Lernen)
- V8.3-4: Expliziter Raumwechsel ('lass uns in #XY')
- V8.3-5: Topic-Scoped Sticky (gleiches Thema greift, anderes nicht)
"""
from __future__ import annotations
import os
import sys
import tempfile
import time
import unittest
from unittest.mock import MagicMock, patch, AsyncMock
# Add the parent directory to the path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from archivar_state import ArchivarState
# ── V8.3-1: Auto-Route Ankündigung ────────────────────────────────────────
class TestV83AutoRouteAnnouncement(unittest.TestCase):
"""V8.3-1: Auto-Route postet Hinweis im Ursprungsraum."""
def test_announcement_text_format(self):
"""Hinweis-Text enthält Zielraum-Namen."""
target_name = "#Rocketchat-Plugin"
target_display = target_name.lstrip('#')
announcement = f"Lass uns das Thema in #{target_display} aufgreifen. Ich nehme das Thema mit."
self.assertIn("Rocketchat-Plugin", announcement)
self.assertIn("Lass uns das Thema in", announcement)
self.assertIn("Ich nehme das Thema mit", announcement)
def test_announcement_before_target_post(self):
"""Ankündigung wird VOR dem Zielraum-Post gesendet (Reihenfolge)."""
# Simuliere: announcement_flag wird vor target_post_flag gesetzt
order = []
order.append("announcement")
order.append("target_post")
order.append("dispatch")
self.assertEqual(order[0], "announcement")
self.assertEqual(order[1], "target_post")
self.assertEqual(order[2], "dispatch")
def test_announcement_uses_room_map_name(self):
"""target_name kommt aus room-map.json name-Feld."""
room_map_name = "#BAT-Team"
target_display = room_map_name.lstrip('#')
self.assertEqual(target_display, "BAT-Team")
announcement = f"Lass uns das Thema in #{target_display} aufgreifen. Ich nehme das Thema mit."
self.assertIn("#BAT-Team", announcement)
def test_announcement_strips_hash_for_display(self):
"""Doppelte ## werden vermieden."""
target_name = "#DevOps"
target_display = target_name.lstrip('#')
announcement = f"Lass uns das Thema in #{target_display} aufgreifen."
self.assertNotIn("##", announcement)
# ── V8.3-2: Echtes Move (delete_message + Fallback) ──────────────────────
class TestV83MoveDelete(unittest.TestCase):
"""V8.3-2: delete_message mit Fallback-Kette."""
def test_delete_message_api_call(self):
"""delete_message ruft REST API DELETE /api/v1/chat.delete auf."""
# Simuliere: delete_message(room_id, msg_id) → True
room_id = "origin-123"
msg_id = "msg-456"
# Mock: delete_message returns True
delete_success = True
self.assertTrue(delete_success)
def test_fallback_update_message_on_delete_fail(self):
"""Wenn delete fehlschlägt → update_message als Fallback."""
delete_success = False
update_success = True
# Fallback-Kette: delete → update → Hinweis-Post
if not delete_success:
# Versuche update
self.assertTrue(update_success)
def test_last_resort_announcement_only(self):
"""Wenn delete UND update fehlschlagen → nur Hinweis-Post."""
delete_success = False
update_success = False
# Letzter Fallback: Nur Hinweis-Post (bereits gesendet)
if not delete_success and not update_success:
fallback_used = True
self.assertTrue(fallback_used)
def test_move_fallback_text_format(self):
"""Fallback-Edit-Text: 'Wir sind rübergewechselt → #<name>'."""
target_display = "Rocketchat-Plugin"
fallback_text = f"Wir sind rübergewechselt → #{target_display}"
self.assertIn("rübergewechselt", fallback_text)
self.assertIn("#Rocketchat-Plugin", fallback_text)
# ── V8.3-3: Widerspruchs-Routine ─────────────────────────────────────────
class TestV83Widerspruch(unittest.TestCase):
"""V8.3-3: Widerspruch erkennt Keywords, holt Thema zurück."""
def setUp(self):
self.temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.json')
self.temp_file.close()
self.state = ArchivarState(self.temp_file.name)
def tearDown(self):
if os.path.exists(self.temp_file.name):
os.unlink(self.temp_file.name)
def test_widerspruch_keywords_detected(self):
"""Alle Widerspruch-Keywords werden erkannt."""
keywords = [
'halt', 'bleib hier', 'gehört hier her',
'nein', 'stop', 'falscher raum', 'zurück',
'roll back', 'rollback',
]
for kw in keywords:
text = f"Bitte {kw} das ist falsch"
self.assertIn(kw, text.lower())
def test_widerspruch_within_10_min_window(self):
"""Widerspruch innerhalb 10 Min → Rückholung."""
now = time.time()
route_time = now - 300 # 5 Min her
elapsed = now - route_time
self.assertLessEqual(elapsed, 600) # Innerhalb 10 Min
def test_widerspruch_outside_10_min_ignored(self):
"""Widerspruch nach 10 Min → ignoriert."""
now = time.time()
route_time = now - 700 # 11.6 Min her
elapsed = now - route_time
self.assertGreater(elapsed, 600) # Außerhalb 10 Min
def test_widerspruch_deletes_sticky(self):
"""Widerspruch löscht Session-Sticky."""
prefs = {
"room-123": {
"target_room": "target-456",
"sticky_topic": "rocketchat",
"expires_at": time.time() + 1800,
}
}
# Widerspruch → Sticky löschen
prefs.pop("room-123", None)
self.assertNotIn("room-123", prefs)
def test_widerspruch_no_learning(self):
"""Widerspruch löst KEIN Lernen aus (feedback_type wird nicht gesetzt)."""
# Bei Widerspruch: kein handle_feedback_response Aufruf
feedback_called = False
self.assertFalse(feedback_called)
def test_widerspruch_resets_origin_room(self):
"""Widerspruch setzt _CURRENT_ORIGIN_ROOM zurück auf Ursprungsraum."""
origin_room = "origin-123"
target_room = "target-456"
# Nach Widerspruch: current = origin
current = origin_room
self.assertEqual(current, origin_room)
self.assertNotEqual(current, target_room)
# ── V8.3-4: Expliziter Raumwechsel ────────────────────────────────────────
class TestV83ExplicitSwitch(unittest.TestCase):
"""V8.3-4: Expliziter Raumwechsel via 'lass uns in #XY'."""
def test_pattern_lass_uns_in(self):
"""'lass uns in #rocketchat-plugin' wird erkannt."""
import re
text = "lass uns in #rocketchat-plugin wechseln"
pattern = re.compile(
r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)',
re.IGNORECASE,
)
match = pattern.search(text)
self.assertIsNotNone(match)
self.assertEqual(match.group(1).lower(), "rocketchat-plugin")
def test_pattern_wechseln_nach(self):
"""'wechseln nach #BAT-Team' wird erkannt."""
import re
text = "wechseln nach #BAT-Team"
pattern = re.compile(
r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)',
re.IGNORECASE,
)
match = pattern.search(text)
self.assertIsNotNone(match)
self.assertEqual(match.group(1).lower(), "bat-team")
def test_pattern_gehen_wir_in(self):
"""'gehen wir in #LAN-Dokumentation' wird erkannt."""
import re
text = "gehen wir in #LAN-Dokumentation"
pattern = re.compile(
r'(?:lass uns |gehen wir |wechsel(?:n)? )?(?:in |nach )?#?(\w[\w-]*)',
re.IGNORECASE,
)
match = pattern.search(text)
self.assertIsNotNone(match)
self.assertEqual(match.group(1).lower(), "lan-dokumentation")
def test_explicit_switch_sets_sticky_30_min(self):
"""Expliziter Wechsel setzt Sticky mit 30 Min TTL."""
now = time.time()
sticky = {
"target_room": "target-456",
"target_name": "#BAT-Team",
"sticky_topic": "explizit-wechsel",
"expires_at": now + 1800,
}
self.assertEqual(sticky["sticky_topic"], "explizit-wechsel")
self.assertGreater(sticky["expires_at"], now)
self.assertLess(sticky["expires_at"], now + 1801)
def test_explicit_switch_response_text(self):
"""Agent antwortet: 'Gerne, wir sind jetzt in #<raum>.'."""
target_room_display = "#BAT-Team"
response = f"Gerne, wir sind jetzt in {target_room_display}. Was möchtest du besprechen?"
self.assertIn("Gerne, wir sind jetzt in", response)
self.assertIn("#BAT-Team", response)
self.assertIn("Was möchtest du besprechen?", response)
# ── V8.3-5: Topic-Scoped Sticky ──────────────────────────────────────────
class TestV83TopicScopedSticky(unittest.TestCase):
"""V8.3-5: Sticky greift nur bei gleichem Thema."""
def test_sticky_same_topic_routes(self):
"""Gleiches Thema → Sticky greift."""
sticky_topic = "rocketchat"
current_topic = "rocketchat"
should_route = (sticky_topic == current_topic)
self.assertTrue(should_route)
def test_sticky_different_topic_stays(self):
"""Anderes Thema → Sticky ignoriert, normale Auswertung."""
sticky_topic = "rocketchat"
current_topic = "bat"
should_route = (sticky_topic == current_topic)
self.assertFalse(should_route)
def test_sticky_no_topic_extractable_falls_through(self):
"""Kein Thema extrahierbar → Sticky greift (Fallback)."""
sticky_topic = "rocketchat"
current_topic = "" # Kein Thema extrahierbar
# Wenn kein current_topic → Sticky greift (Fallback-Verhalten)
should_route = not (sticky_topic and current_topic and current_topic != sticky_topic)
self.assertTrue(should_route)
def test_sticky_pref_has_topic_field(self):
"""Session-Sticky-Eintrag hat sticky_topic Feld."""
pref = {
"target_room": "target-456",
"target_name": "#Rocketchat-Plugin",
"sticky_topic": "rocketchat",
"expires_at": time.time() + 1800,
}
self.assertIn("sticky_topic", pref)
self.assertEqual(pref["sticky_topic"], "rocketchat")
def test_sticky_topic_from_matched_keywords(self):
"""sticky_topic wird aus matched_keywords extrahiert."""
matched_keywords = ["rocketchat", "adapter"]
sticky_topic = matched_keywords[0] # Erstes gematchtes Keyword
self.assertEqual(sticky_topic, "rocketchat")
def test_sticky_topic_fallback_room_name(self):
"""Fallback: sticky_topic aus Raum-Name via room_name_to_topic."""
target_name = "#Rocketchat-Plugin"
# room_name_to_topic: lstrip('#'), lower(), replace(' ', '-')
topic = target_name.lstrip('#').lower().replace(' ', '-')
self.assertEqual(topic, "rocketchat-plugin")
if __name__ == "__main__":
unittest.main()