feat(P2): Themenring Phase A — In-Memory Ringmatrix für menschenähnliche Kommunikation
Herzstück der Multi-Room-Kommunikation: Andreas arbeitet gleichzeitig an mehreren Themen in verschiedenen Räumen. Der Themenring speichert pro Raum eine deque von TopicEntry-NamedTuples und erlaubt lock-free Reads via Copy-on-Write-Snapshot. Änderungen: - NEU: plugin/archivar/topic_ring.py — TopicRing Klasse mit Single-Reader- Multi-Writer Pattern, TTL-basierter GC, periodischem Prune-Sweep - NEU: plugin/archivar/tests/test_topic_ring.py — 39 Tests (CRUD, TTL, GC per-room/global, Thread-Safety, Cross-Contamination, send()-Integration) - config.py: TOPIC_RING_MAX_PER_ROOM=5, GLOBAL_MAX=200, TTLs, PRUNE_INTERVAL - adapter.py: T1 Ring-Befüllung in _process_incoming() NACH Archivar- Klassifikation; Prio 1 TopicRing-Lookup in send() und send_clarify() VOR _room_context-Fallback Prioritäten-Kette in send(): Prio 0: _CURRENT_ORIGIN_ROOM (ContextVar) — UNVERÄNDERT Prio 1: TopicRing.get_active_topic_for_chat() — NEU Prio 1.5: _room_context (Stream-Retry Fallback) — BESTEHT Prio 2: _THEMATIC_TARGET_ROOM — UNVERÄNDERT Prio 3: _user_rooms[-1] — UNVERÄNDERT Prio 4: _find_fallback_room_for_user — UNVERÄNDERT Tests: 1383 passed + 39 new = 1422 total (4 pre-existing failures)
This commit is contained in:
+128
-56
@@ -34,6 +34,11 @@ class RocketChatRateLimitError(Exception):
|
||||
"""HTTP 429 Too Many Requests from Rocket.Chat REST API."""
|
||||
pass
|
||||
|
||||
# ── Themenring Phase A: In-Memory Ringmatrix ──────────────────────────────
|
||||
# Import des Modul-Singletons — wird in _process_incoming() befüllt und
|
||||
# in send() als Prio 1 gelesen.
|
||||
from archivar.topic_ring import topic_ring, TopicEntry, extract_topic_from_message
|
||||
|
||||
# ── Room context (global dict statt ContextVar — ContextVars sind asyncio-task-lokal,
|
||||
# aber der Agent läuft in einem separaten Task und sieht sie nicht) ──
|
||||
# P1: Cross-Contamination-Fix — Task-Token + TTL-Sweep
|
||||
@@ -3159,6 +3164,46 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.info("ROUTING BYPASS: reason=exception_fallback, origin_room=%s", room_id)
|
||||
logger.debug("[rocketchat] Archivar classification skipped: %s", e)
|
||||
|
||||
# ── Themenring Phase A: T1 — Ring-Befüllung NACH Archivar-Klassifikation ──
|
||||
# Filter: nur wenn nicht smalltalk und topic > 8 Zeichen.
|
||||
# Topic wird aus Archivar-Klassifikation extrahiert (Andreas F-A).
|
||||
if decision and decision.category and decision.category != "smalltalk":
|
||||
import datetime as _dt # lokaler Import — verhindert UnboundLocalError
|
||||
# Topic aus Archivar-Entscheidung extrahieren
|
||||
target_name = getattr(decision, 'move_request_target_name', '')
|
||||
target_room = getattr(decision, 'target_room', '')
|
||||
archivar_topic = ""
|
||||
if target_name:
|
||||
archivar_topic = target_name.lstrip('#')
|
||||
elif target_room:
|
||||
archivar_topic = f"Archivar: {decision.category}"
|
||||
# Fallback: Topic aus Nachrichtentext extrahieren
|
||||
if not archivar_topic or len(archivar_topic) <= 8:
|
||||
archivar_topic = extract_topic_from_message(routing_text)
|
||||
# TTL: persistent bei hoher Konfidenz (butler/stay/alarm), sonst session
|
||||
ttl = "session"
|
||||
if decision.confidence >= 0.9:
|
||||
ttl = "persistent"
|
||||
elif decision.category == "ambiguous":
|
||||
ttl = "ephemeral"
|
||||
if archivar_topic and len(archivar_topic) > 8:
|
||||
entry = TopicEntry(
|
||||
topic=archivar_topic,
|
||||
room_id=room_id,
|
||||
origin_room=room_id,
|
||||
thematic_target=target_room if target_room and target_room != room_id else "",
|
||||
timestamp=_dt.datetime.now(_dt.timezone.utc).isoformat(),
|
||||
ttl=ttl,
|
||||
user_id=f"user:{username}",
|
||||
source="archivar",
|
||||
)
|
||||
topic_ring.add(entry)
|
||||
logger.debug(
|
||||
"[rocketchat] Themenring T1: Added topic='%s' room=%s ttl=%s",
|
||||
archivar_topic[:40], room_id[:8], ttl,
|
||||
)
|
||||
# ── Ende Themenring T1 ──────────────────────────────────────────────
|
||||
|
||||
# ── User-Flow C: Nachricht kopieren, Antwort IMMER hier ────────
|
||||
# V7-1: Wenn move_request_sent=True, KEIN Agent-Dispatch.
|
||||
# Der Agent wird erst nach Button-Bestätigung (✅Ja) dispatched,
|
||||
@@ -6492,39 +6537,56 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
real_room_id = origin
|
||||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
||||
# ist _CURRENT_ORIGIN_ROOM leer. _room_context (global dict) überlebt.
|
||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||
fallback_origin = _get_room_context_origin(chat_id)
|
||||
if fallback_origin:
|
||||
real_room_id = fallback_origin
|
||||
routing_counter.increment('contextvar_reset_fallback')
|
||||
logger.info("[rocketchat] send via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||
# ── Themenring Phase A: Prio 1 — Aktives Thema für diesen Chat ──
|
||||
# Der Themenring speichert, in welchem Raum ein Thema aktiv ist.
|
||||
# Wenn der Agent zu einem Thema antwortet, das im Ring registriert
|
||||
# ist, wird die Antwort in den registrierten Raum gesendet.
|
||||
# Dies ist das Herzstück der menschenähnlichen Kommunikation:
|
||||
# Andreas arbeitet gleichzeitig an mehreren Themen in verschiedenen
|
||||
# Räumen — der Themenring stellt sicher, dass Antworten im richtigen
|
||||
# Raum landen.
|
||||
topic_ring_origin = topic_ring.get_active_topic_for_chat(chat_id)
|
||||
if topic_ring_origin:
|
||||
real_room_id = topic_ring_origin
|
||||
routing_counter.increment('topic_ring_prio1')
|
||||
logger.info(
|
||||
"[rocketchat] send via TopicRing Prio 1: %s → %s (active topic)",
|
||||
chat_id, real_room_id[:8],
|
||||
)
|
||||
else:
|
||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
||||
# ist _CURRENT_ORIGIN_ROOM leer. _room_context (global dict) überlebt.
|
||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||
fallback_origin = _get_room_context_origin(chat_id)
|
||||
if fallback_origin:
|
||||
real_room_id = fallback_origin
|
||||
routing_counter.increment('contextvar_reset_fallback')
|
||||
logger.info("[rocketchat] send via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Priority 2: proaktive Nachricht — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||
if fallback_room:
|
||||
real_room_id = fallback_room
|
||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||
# Priority 2: proaktive Nachricht — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||
if fallback_room:
|
||||
real_room_id = fallback_room
|
||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||
else:
|
||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||
|
||||
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
|
||||
# This allows the agent to request buttons by embedding markup in its
|
||||
@@ -6865,37 +6927,47 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
real_room_id = origin
|
||||
logger.debug("[rocketchat] send_clarify via ContextVar: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||
fallback_origin = _get_room_context_origin(chat_id)
|
||||
if fallback_origin:
|
||||
real_room_id = fallback_origin
|
||||
routing_counter.increment('contextvar_reset_fallback')
|
||||
logger.info("[rocketchat] send_clarify via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||
# ── Themenring Phase A: Prio 1 — Aktives Thema für diesen Chat ──
|
||||
topic_ring_origin = topic_ring.get_active_topic_for_chat(chat_id)
|
||||
if topic_ring_origin:
|
||||
real_room_id = topic_ring_origin
|
||||
routing_counter.increment('topic_ring_prio1')
|
||||
logger.info(
|
||||
"[rocketchat] send_clarify via TopicRing Prio 1: %s → %s (active topic)",
|
||||
chat_id, real_room_id[:8],
|
||||
)
|
||||
else:
|
||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||
fallback_origin = _get_room_context_origin(chat_id)
|
||||
if fallback_origin:
|
||||
real_room_id = fallback_origin
|
||||
routing_counter.increment('contextvar_reset_fallback')
|
||||
logger.info("[rocketchat] send_clarify via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Priority 2: proactive message — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send_clarify via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||
if thematic_target:
|
||||
real_room_id = thematic_target
|
||||
logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||
if fallback_room:
|
||||
real_room_id = fallback_room
|
||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||
# Priority 2: proactive message — use most recent room for this user
|
||||
rooms = self._user_rooms.get(chat_id, [])
|
||||
if rooms:
|
||||
real_room_id = rooms[-1] # last room user was active in
|
||||
logger.debug("[rocketchat] send_clarify via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||
else:
|
||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||
# Fallback: try to find any room with recent activity involving this user
|
||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||
if fallback_room:
|
||||
real_room_id = fallback_room
|
||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||
else:
|
||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||
|
||||
# Render full option text in the message body so users
|
||||
# can read long choices that would be truncated in buttons.
|
||||
|
||||
Reference in New Issue
Block a user