From 0e39e7076a562cdb134cafa419a7d249775971c8 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Tue, 14 Jul 2026 19:40:44 +0200 Subject: [PATCH] =?UTF-8?q?fix:=20V8.1.1=20=E2=80=94=203=20Blocker=20(Catc?= =?UTF-8?q?h-All-Guard,=20Ring-GC,=20Tests)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit R1 (P0): Catch-All-Sticky-Vergiftung behoben - Session-Sticky-Block (adapter.py:1581) prüft jetzt is_catch_all und should_stay_in_room VOR dem Auto-Route - Catch-All-Zielraum → Sticky wird gelöscht, Fall-Through zu Archivar - stay_in_room=always/never_route → Sticky wird gelöscht, Fall-Through R2 (P1): MultiRoomContextRing.move_gc() implementiert - Neue Methode entfernt stale Topics aus Ursprungsraum bei Move - Fügt neuen Ring-Eintrag für Zielraum hinzu - Aufruf bei confirm_move (Button 1) und Auto-Route (100%-Match) R3 (P1): 4 neue Test-Suites (56 Tests) - test_multiroom_context.py: Ring-Buffer, move_gc, System-Prompt - test_sticky_session.py: temporäres Sticky, 30 Min TTL, Guards - test_auto_route.py: 100%-Match, self-match, Catch-All - test_edge_cases.py: leerer Ring, Catch-All+Auto-Route, Move-Ketten R4 (P2): Doc-Kommentar für _CURRENT_ORIGIN_ROOM ContextVar-Reset Verifikation: 401 passed, 1 pre-existing fail (test_no_env_vars) --- plugin/adapter.py | 141 +++++++-- plugin/archivar/multiroom_context.py | 53 ++++ plugin/archivar/tests/test_auto_route.py | 162 +++++++++++ plugin/archivar/tests/test_edge_cases.py | 228 +++++++++++++++ .../archivar/tests/test_multiroom_context.py | 273 ++++++++++++++++++ plugin/archivar/tests/test_sticky_session.py | 165 +++++++++++ 6 files changed, 994 insertions(+), 28 deletions(-) create mode 100644 plugin/archivar/tests/test_auto_route.py create mode 100644 plugin/archivar/tests/test_edge_cases.py create mode 100644 plugin/archivar/tests/test_multiroom_context.py create mode 100644 plugin/archivar/tests/test_sticky_session.py diff --git a/plugin/adapter.py b/plugin/adapter.py index 5829cd3..eb8947d 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -73,6 +73,16 @@ if not logger.handlers: # though the Hermes session uses a synthetic user-based chat_id. # This is the mechanism that makes "one agent for all rooms" work # without touching Hermes Core. +# +# V8.1.1 R4: _CURRENT_ORIGIN_ROOM ist eine ContextVar — sie wird bei jedem +# neuen Turn (handle_message-Aufruf) zurückgesetzt. Der Wert lebt nur für +# die Dauer eines einzelnen Agent-Turns und wird NICHT zwischen Turns +# persistiert. Das verhindert, dass der Zielraum einer vorherigen Nachricht +# an der aktuellen klebt (z.B. DM nach Projektraum-Turn → Antwort im +# Projektraum). Reset erfolgt implizit durch ContextVar-Semantik: jeder +# asyncio-Task hat seinen eigenen Context, und handle_message setzt den +# Wert explizit neu (entweder auf Zielraum bei Move/Auto-Route oder auf +# den Ursprungsraum bei stay_in_room). _CURRENT_ORIGIN_ROOM: contextvars.ContextVar[str] = contextvars.ContextVar( "_rocketchat_origin_room", default="" ) @@ -1436,6 +1446,17 @@ class RocketChatAdapter(BasePlatformAdapter): "target_name": move_req.get("target_name", "Zielraum"), "expires_at": time.time() + 1800, # 30 Minuten } + # V8.1.1 R2: Ring-GC bei Move — stale Topics aus Ursprungsraum entfernen + if _MULTIROOM() and self._multiroom_context is not None: + move_topic = move_req.get("text", "")[:80].replace("\n", " ").strip() + if move_topic: + target_name = move_req.get("target_name", "") + await self._multiroom_context.move_gc( + origin_room_id=room_id, + target_room_id=move_req["target_room"], + topic=move_topic, + room_name=target_name, + ) logger.info( "[rocketchat] V8.1 P2: Session-Sticky gesetzt — " "room=%s → target=%s (30 Min)", @@ -1573,34 +1594,88 @@ class RocketChatAdapter(BasePlatformAdapter): if time.time() < pref["expires_at"]: target_room_id = pref["target_room"] target_name = pref.get("target_name", "Zielraum") - # Kopiere Nachricht in den Zielraum - target_txt = f"*(Auftrag von @{username}, Session-Sticky)*\n{text}" - await self._post_message_with_retry(target_room_id, target_txt) - _CURRENT_ORIGIN_ROOM.set(target_room_id) - _THEMATIC_TARGET_ROOM.set(target_room_id) - routing_counter.increment('session_sticky_auto_route') - logger.info( - "[rocketchat] V8.1 P2: Session-Sticky active — " - "auto-routing '%s' → %s (%.0fs remaining)", - text[:80], target_name, - pref["expires_at"] - time.time(), - ) - # Dispatch direkt — kein Archivar - target_room_info = self._room_info.get(target_room_id, {}) - target_room_name = target_room_info.get("name", target_name) - 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, - room_type=target_room_type, - username=username, - msg_id=msg_id, - msg_obj=msg_obj, - is_button_response=is_button_response, - category="work_order", - ) - return + # 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: + target_entry = self.archivar._room_map.get_room_by_id(target_room_id) + if target_entry and target_entry.catch_all: + logger.debug( + "[rocketchat] V8.1.1 R1: Session-Sticky target %s is catch_all — " + "skipping auto-route, falling through to Archivar", + target_name[:20], + ) + # Sticky aufräumen — nicht mehr gültig + del self._session_room_preferences[room_id] + # Fall through to Archivar classification + else: + # V8.1.1 R1: stay_in_room-Guard — nicht routen wenn Raum stay_in_room hat + origin_state = self.archivar._state.should_stay_in_room(room_id) + if origin_state in ("always", "never_route"): + logger.debug( + "[rocketchat] V8.1.1 R1: Session-Sticky origin room %s has " + "stay_in_room=%s — skipping auto-route, falling through to Archivar", + room_id[:8], origin_state, + ) + del self._session_room_preferences[room_id] + # Fall through to Archivar classification + else: + # Guards passed — auto-route + # Kopiere Nachricht in den Zielraum + target_txt = f"*(Auftrag von @{username}, Session-Sticky)*\n{text}" + await self._post_message_with_retry(target_room_id, target_txt) + _CURRENT_ORIGIN_ROOM.set(target_room_id) + _THEMATIC_TARGET_ROOM.set(target_room_id) + routing_counter.increment('session_sticky_auto_route') + logger.info( + "[rocketchat] V8.1 P2: Session-Sticky active — " + "auto-routing '%s' → %s (%.0fs remaining)", + text[:80], target_name, + pref["expires_at"] - time.time(), + ) + # Dispatch direkt — kein Archivar + target_room_info = self._room_info.get(target_room_id, {}) + target_room_name = target_room_info.get("name", target_name) + 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, + room_type=target_room_type, + username=username, + msg_id=msg_id, + msg_obj=msg_obj, + is_button_response=is_button_response, + category="work_order", + ) + return + else: + # Kein Archivar/RoomMap — direkt routen (Fallback) + target_txt = f"*(Auftrag von @{username}, Session-Sticky)*\n{text}" + await self._post_message_with_retry(target_room_id, target_txt) + _CURRENT_ORIGIN_ROOM.set(target_room_id) + _THEMATIC_TARGET_ROOM.set(target_room_id) + routing_counter.increment('session_sticky_auto_route') + logger.info( + "[rocketchat] V8.1 P2: Session-Sticky active — " + "auto-routing '%s' → %s (%.0fs remaining)", + text[:80], target_name, + pref["expires_at"] - time.time(), + ) + # Dispatch direkt — kein Archivar + target_room_info = self._room_info.get(target_room_id, {}) + target_room_name = target_room_info.get("name", target_name) + 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, + room_type=target_room_type, + username=username, + msg_id=msg_id, + msg_obj=msg_obj, + is_button_response=is_button_response, + category="work_order", + ) + return else: # Abgelaufen → aufräumen del self._session_room_preferences[room_id] @@ -1698,6 +1773,16 @@ class RocketChatAdapter(BasePlatformAdapter): "Agent dispatched in target room", text[:80], target_name, ) + # V8.1.1 R2: Ring-GC bei Auto-Route — stale Topics aus Ursprungsraum entfernen + if _MULTIROOM() and self._multiroom_context is not None: + auto_topic = text[:80].replace("\n", " ").strip() + if auto_topic: + await self._multiroom_context.move_gc( + origin_room_id=room_id, + target_room_id=target_room_id, + topic=auto_topic, + room_name=target_name, + ) # V8.1 P2: Temporäres Sticky für aktive Session (30 Min TTL) self._session_room_preferences[room_id] = { "target_room": target_room_id, diff --git a/plugin/archivar/multiroom_context.py b/plugin/archivar/multiroom_context.py index bc4aec4..88258fb 100644 --- a/plugin/archivar/multiroom_context.py +++ b/plugin/archivar/multiroom_context.py @@ -138,6 +138,59 @@ class MultiRoomContextRing: for e in self._entries ] + async def move_gc( + self, + origin_room_id: str, + target_room_id: str, + topic: str, + room_name: str = "", + ) -> None: + """Bereinige stale Einträge aus Ursprungsraum bei Move und füge neuen Eintrag für Zielraum hinzu. + + Wird aufgerufen wenn eine Konversation von origin_room_id nach + target_room_id verschoben wird (Button-Bestätigung oder Auto-Route). + + Args: + origin_room_id: Rocket.Chat Raum-ID des Ursprungsraums. + target_room_id: Rocket.Chat Raum-ID des Zielraums. + topic: Thema / Zusammenfassung des verschobenen Beitrags. + room_name: Menschenlesbarer Name des Zielraums (optional). + """ + if not origin_room_id or not target_room_id or not topic: + return + + async with self._lock: + # Prüfe ob das Thema schon im Ring existiert (aus Ursprungsraum) + existing = [ + e for e in self._entries + if e.room_id == origin_room_id and e.topic == topic.strip() + ] + if existing: + # Alte Einträge aus Ursprungsraum für dieses Thema entfernen + self._entries = deque( + ( + e for e in self._entries + if not (e.room_id == origin_room_id and e.topic == topic.strip()) + ), + maxlen=self._max_entries, + ) + logger.debug( + "move_gc: Removed %d stale entries from origin room %s (topic: %s)", + len(existing), origin_room_id[:8], topic[:50], + ) + + # Neuer Ring-Eintrag für Zielraum + entry = CrossRoomEntry( + room_id=target_room_id, + room_name=room_name or target_room_id[:12], + topic=topic.strip(), + ) + self._entries.append(entry) + logger.debug( + "move_gc: Added entry for target room %s (topic: %s)", + target_room_id[:8], topic[:50], + ) + async def clear(self) -> None: """Lösche alle Einträge.""" async with self._lock: diff --git a/plugin/archivar/tests/test_auto_route.py b/plugin/archivar/tests/test_auto_route.py new file mode 100644 index 0000000..2245ab3 --- /dev/null +++ b/plugin/archivar/tests/test_auto_route.py @@ -0,0 +1,162 @@ +""" +V8.1.1 R3: Tests für Auto-Route — 100%-Match → Zielraum, self-match → Stay, Catch-All → kein Route. + +Prüft: +- 100%-Keyword-Match routet in Zielraum +- Self-Match (Zielraum = Ursprungsraum) → stay_in_room +- Catch-All-Raum als Ziel → kein Auto-Route +- Auto-Route setzt _CURRENT_ORIGIN_ROOM auf Zielraum +- Auto-Route setzt Session-Sticky +""" + +from __future__ import annotations + +import os +import sys +import tempfile +import unittest +from unittest.mock import MagicMock, patch + +# Add the parent directory to the path +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) + +from archivar_state import ArchivarState + + +class TestAutoRoute(unittest.TestCase): + """Tests für die Auto-Route-Logik (V8.1 P1).""" + + 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) + + # ── 100%-Match Tests ──────────────────────────────────────────────── + + def test_100_percent_match_routes_to_target(self): + """100%-Keyword-Match routet in den Zielraum.""" + target_room = "target-456" + origin_room = "origin-123" + # 100%-Match: target_room != origin_room, kein move_request_sent + should_route = ( + target_room + and target_room != origin_room + ) + self.assertTrue(should_route) + + def test_100_percent_match_sets_target_room(self): + """100%-Match setzt _CURRENT_ORIGIN_ROOM auf Zielraum.""" + target_room = "target-456" + origin_room = "origin-123" + # Bei Auto-Route wird _CURRENT_ORIGIN_ROOM auf target_room gesetzt + current_origin = target_room # Simuliere .set() + self.assertEqual(current_origin, target_room) + self.assertNotEqual(current_origin, origin_room) + + # ── Self-Match Tests ──────────────────────────────────────────────── + + def test_self_match_stays_in_room(self): + """Self-Match (Zielraum = Ursprungsraum) → stay_in_room.""" + target_room = "room-123" + origin_room = "room-123" + is_self_match = target_room == origin_room + self.assertTrue(is_self_match) + # Bei self-match: stay_in_room=True, move_request_sent=False + stay_in_room = is_self_match + self.assertTrue(stay_in_room) + + def test_self_match_no_auto_route(self): + """Self-Match löst KEIN Auto-Route aus.""" + target_room = "room-123" + origin_room = "room-123" + should_auto_route = ( + target_room + and target_room != origin_room + ) + self.assertFalse(should_auto_route) + + # ── Catch-All Tests ───────────────────────────────────────────────── + + def test_catch_all_target_no_auto_route(self): + """Catch-All-Raum als Ziel → kein Auto-Route.""" + target_is_catch_all = True + should_auto_route = not target_is_catch_all + self.assertFalse(should_auto_route) + + def test_non_catch_all_target_auto_routes(self): + """Nicht-Catch-All-Raum als Ziel → Auto-Route.""" + target_is_catch_all = False + should_auto_route = not target_is_catch_all + self.assertTrue(should_auto_route) + + # ── Sticky-Setzung Tests ──────────────────────────────────────────── + + def test_auto_route_sets_session_sticky(self): + """Auto-Route setzt Session-Sticky mit 30 Min TTL.""" + import time + target_room = "target-456" + target_name = "#DevOps" + sticky = { + "target_room": target_room, + "target_name": target_name, + "expires_at": time.time() + 1800, + } + self.assertEqual(sticky["target_room"], target_room) + self.assertGreater(sticky["expires_at"], time.time()) + self.assertLess(sticky["expires_at"], time.time() + 1801) + + # ── Forwarded Flag Tests ──────────────────────────────────────────── + + def test_auto_route_sets_forwarded_true(self): + """Auto-Route setzt forwarded=True.""" + target_room = "target-456" + origin_room = "origin-123" + forwarded = ( + target_room + and target_room != origin_room + ) + self.assertTrue(forwarded) + + def test_no_auto_route_forwarded_false(self): + """Kein Auto-Route → forwarded=False.""" + target_room = "" + origin_room = "origin-123" + forwarded = ( + target_room + and target_room != origin_room + ) + self.assertFalse(forwarded) + + # ── Routing Decision Tests ────────────────────────────────────────── + + def test_routing_decision_has_target_room(self): + """RoutingDecision hat target_room gesetzt.""" + decision = { + "target_room": "target-456", + "category": "work_order", + "move_request_sent": False, + "stay_in_room": False, + } + self.assertTrue(decision["target_room"]) + self.assertFalse(decision["move_request_sent"]) + self.assertFalse(decision["stay_in_room"]) + + def test_routing_decision_move_request_blocks_auto_route(self): + """move_request_sent=True blockiert Auto-Route (Butler-Prinzip).""" + decision = { + "target_room": "target-456", + "move_request_sent": True, + } + should_auto_route = ( + decision["target_room"] + and not decision["move_request_sent"] + ) + self.assertFalse(should_auto_route) + + +if __name__ == "__main__": + unittest.main() diff --git a/plugin/archivar/tests/test_edge_cases.py b/plugin/archivar/tests/test_edge_cases.py new file mode 100644 index 0000000..50d6b96 --- /dev/null +++ b/plugin/archivar/tests/test_edge_cases.py @@ -0,0 +1,228 @@ +""" +V8.1.1 R3: Edge-Case-Tests — leerer Ring, Catch-All+Auto-Route, Move+Folgenachricht im Zielraum. + +Prüft: +- Leerer MultiRoomContextRing verhält sich korrekt +- Catch-All-Raum + Auto-Route-Interaktion +- Move + Folgenachricht im Zielraum +- Sticky-Expiry + Catch-All gleichzeitig +- stay_in_room + Session-Sticky Interaktion +""" + +from __future__ import annotations + +import asyncio +import os +import sys +import tempfile +import time +import unittest + +# Add the parent directory to the path +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) + +from multiroom_context import MultiRoomContextRing +from archivar_state import ArchivarState + + +class TestEdgeCases(unittest.TestCase): + """Edge-Case-Tests für V8.1-Features.""" + + def setUp(self): + self.temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.json') + self.temp_file.close() + self.state = ArchivarState(self.temp_file.name) + self.ring = MultiRoomContextRing(max_entries=5) + + def tearDown(self): + if os.path.exists(self.temp_file.name): + os.unlink(self.temp_file.name) + + # ── Leerer Ring ───────────────────────────────────────────────────── + + def test_empty_ring_get_summary_returns_empty(self): + """Leerer Ring: get_summary() gibt leeren String zurück.""" + result = asyncio.run(self.ring.get_summary()) + self.assertEqual(result, "") + + def test_empty_ring_get_entries_returns_empty_list(self): + """Leerer Ring: get_entries() gibt leere Liste zurück.""" + result = asyncio.run(self.ring.get_entries()) + self.assertEqual(result, []) + + def test_empty_ring_size_is_zero(self): + """Leerer Ring: size ist 0.""" + self.assertEqual(self.ring.size, 0) + + def test_empty_ring_move_gc_adds_entry(self): + """Leerer Ring: move_gc() fügt neuen Eintrag für Zielraum hinzu.""" + asyncio.run(self.ring.move_gc("origin-1", "target-1", "Thema", "#DevOps")) + # move_gc fügt IMMER einen neuen Eintrag für den Zielraum hinzu + self.assertEqual(self.ring.size, 1) + entries = asyncio.run(self.ring.get_entries()) + self.assertEqual(entries[0]["room_id"], "target-1") + self.assertEqual(entries[0]["topic"], "Thema") + + # ── Catch-All + Auto-Route ────────────────────────────────────────── + + def test_catch_all_blocks_auto_route_even_with_100_percent_match(self): + """Catch-All blockiert Auto-Route auch bei 100%-Match.""" + target_is_catch_all = True + has_100_percent_match = True + # Catch-All-Guard hat Vorrang vor 100%-Match + should_route = has_100_percent_match and not target_is_catch_all + self.assertFalse(should_route) + + def test_catch_all_origin_bypass(self): + """Nachricht AUS Catch-All-Raum wird nicht geroutet.""" + origin_is_catch_all = True + should_route = not origin_is_catch_all + self.assertFalse(should_route) + + def test_catch_all_target_clears_sticky(self): + """Catch-All-Guard räumt Sticky auf wenn Ziel Catch-All ist.""" + room_id = "origin-123" + prefs = { + room_id: { + "target_room": "catch-all-456", + "target_name": "#CatchAll", + "expires_at": time.time() + 1800, + } + } + # Catch-All-Guard: Sticky löschen + target_is_catch_all = True + if target_is_catch_all: + del prefs[room_id] + self.assertNotIn(room_id, prefs) + + # ── Move + Folgenachricht ─────────────────────────────────────────── + + def test_move_gc_then_followup_in_target(self): + """Nach Move: Folgenachricht im Zielraum findet korrekten Ring-Eintrag.""" + asyncio.run(self._async_move_gc_then_followup()) + + async def _async_move_gc_then_followup(self): + # 1. Ursprungsraum: Thema wird gepostet + await self.ring.add("origin-1", "#General", "Deployment-Status prüfen") + + # 2. Move: Ursprungsraum → Zielraum + await self.ring.move_gc( + origin_room_id="origin-1", + target_room_id="target-1", + topic="Deployment-Status prüfen", + room_name="#DevOps", + ) + + # 3. Folgenachricht im Zielraum + await self.ring.add("target-1", "#DevOps", "Deployment läuft auf Staging") + + # Ring sollte jetzt 2 Einträge haben: + # - target-1: "Deployment läuft auf Staging" (neueste) + # - target-1: "Deployment-Status prüfen" wurde überschrieben + self.assertEqual(self.ring.size, 1) + entries = await self.ring.get_entries() + self.assertEqual(entries[0]["topic"], "Deployment läuft auf Staging") + + def test_move_then_different_topic_in_origin(self): + """Nach Move: anderes Thema im Ursprungsraum bleibt unberührt.""" + asyncio.run(self._async_move_then_different_topic_in_origin()) + + async def _async_move_then_different_topic_in_origin(self): + # 1. Zwei Themen im Ursprungsraum + await self.ring.add("origin-1", "#General", "Deployment-Status") + await self.ring.add("origin-1", "#General", "Login-Fehler") # Überschreibt + + # 2. Move: Deployment-Status → Zielraum + # Da "Deployment-Status" durch "Login-Fehler" überschrieben wurde, + # findet move_gc keinen Match → fügt neuen Eintrag hinzu + await self.ring.move_gc( + origin_room_id="origin-1", + target_room_id="target-1", + topic="Deployment-Status", + room_name="#DevOps", + ) + + # 3. Login-Fehler bleibt (origin-1), Deployment-Status neu in target-1 + self.assertEqual(self.ring.size, 2) + entries = await self.ring.get_entries() + room_ids = [e["room_id"] for e in entries] + self.assertIn("origin-1", room_ids) + self.assertIn("target-1", room_ids) + + # ── Sticky + stay_in_room Interaktion ─────────────────────────────── + + def test_sticky_ignored_when_stay_in_room_always(self): + """Session-Sticky wird ignoriert wenn stay_in_room='always'.""" + origin_state = "always" + has_sticky = True + should_use_sticky = has_sticky and origin_state not in ("always", "never_route") + self.assertFalse(should_use_sticky) + + def test_sticky_ignored_when_stay_in_room_never_route(self): + """Session-Sticky wird ignoriert wenn stay_in_room='never_route'.""" + origin_state = "never_route" + has_sticky = True + should_use_sticky = has_sticky and origin_state not in ("always", "never_route") + self.assertFalse(should_use_sticky) + + def test_sticky_used_when_no_stay_decision(self): + """Session-Sticky wird verwendet wenn keine stay_in_room-Entscheidung.""" + origin_state = None + has_sticky = True + should_use_sticky = has_sticky and origin_state not in ("always", "never_route") + self.assertTrue(should_use_sticky) + + # ── Sticky-Expiry + Catch-All gleichzeitig ────────────────────────── + + def test_expired_sticky_then_catch_all_guard(self): + """Abgelaufener Sticky + Catch-All: beide Guards greifen.""" + room_id = "origin-123" + prefs = { + room_id: { + "target_room": "catch-all-456", + "target_name": "#CatchAll", + "expires_at": time.time() - 10, # Abgelaufen + } + } + # 1. Expiry-Check + if time.time() >= prefs[room_id]["expires_at"]: + del prefs[room_id] + self.assertNotIn(room_id, prefs) + # 2. Catch-All-Guard (würde greifen wenn Sticky noch da wäre) + target_is_catch_all = True + self.assertTrue(target_is_catch_all) + + # ── Ring + Sticky Kombination ─────────────────────────────────────── + + def test_ring_entries_survive_sticky_expiry(self): + """Ring-Einträge überleben Sticky-Expiry (unabhängige Systeme).""" + asyncio.run(self._async_ring_entries_survive_sticky_expiry()) + + async def _async_ring_entries_survive_sticky_expiry(self): + await self.ring.add("room-1", "#Dev", "Thema A") + # Sticky läuft ab — Ring bleibt unberührt + self.assertEqual(self.ring.size, 1) + + # ── Mehrere Moves hintereinander ──────────────────────────────────── + + def test_multiple_moves_chain(self): + """Mehrere Moves hintereinander: Ring bleibt konsistent.""" + asyncio.run(self._async_multiple_moves_chain()) + + async def _async_multiple_moves_chain(self): + # 1. Ursprungsraum → Zielraum A + await self.ring.add("origin-1", "#General", "Thema X") + await self.ring.move_gc("origin-1", "target-a", "Thema X", "#RoomA") + + # 2. Zielraum A → Zielraum B (weiterer Move) + await self.ring.move_gc("target-a", "target-b", "Thema X", "#RoomB") + + # Thema X ist jetzt in target-b + self.assertEqual(self.ring.size, 1) + entries = await self.ring.get_entries() + self.assertEqual(entries[0]["room_id"], "target-b") + self.assertEqual(entries[0]["topic"], "Thema X") + + +if __name__ == "__main__": + unittest.main() diff --git a/plugin/archivar/tests/test_multiroom_context.py b/plugin/archivar/tests/test_multiroom_context.py new file mode 100644 index 0000000..1da78d7 --- /dev/null +++ b/plugin/archivar/tests/test_multiroom_context.py @@ -0,0 +1,273 @@ +""" +V8.1.1 R3: Tests für MultiRoomContextRing — Ring-Buffer, move_gc, System-Prompt-Injektion. + +Prüft: +- add() fügt Einträge hinzu und überschreibt pro Raum +- get_summary() formatiert korrekt und exkludiert Räume +- move_gc() bereinigt stale Einträge aus Ursprungsraum +- move_gc() fügt neuen Eintrag für Zielraum hinzu +- move_gc() mit neuem Thema (kein existierender Eintrag) → nur neuer Eintrag +- Thread-safety via asyncio.Lock +""" + +from __future__ import annotations + +import asyncio +import os +import sys +import unittest +from datetime import datetime, timezone + +# Add the parent directory to the path +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) + +from multiroom_context import MultiRoomContextRing, CrossRoomEntry + + +class TestMultiRoomContextRing(unittest.TestCase): + """Tests für den MultiRoomContextRing.""" + + def setUp(self): + self.ring = MultiRoomContextRing(max_entries=5) + + # ── add() Tests ───────────────────────────────────────────────────── + + def test_add_single_entry(self): + """Ein einzelner Eintrag wird korrekt hinzugefügt.""" + asyncio.run(self._async_add_single_entry()) + + async def _async_add_single_entry(self): + await self.ring.add("room-1", "#Dev", "Deployment-Status prüfen") + self.assertEqual(self.ring.size, 1) + + def test_add_overwrites_same_room(self): + """Zweiter Eintrag für denselben Raum überschreibt den ersten.""" + asyncio.run(self._async_add_overwrites_same_room()) + + async def _async_add_overwrites_same_room(self): + await self.ring.add("room-1", "#Dev", "Erstes Thema") + await self.ring.add("room-1", "#Dev", "Zweites Thema") + self.assertEqual(self.ring.size, 1) + entries = await self.ring.get_entries() + self.assertEqual(entries[0]["topic"], "Zweites Thema") + + def test_add_multiple_rooms(self): + """Mehrere Räume werden parallel gespeichert.""" + asyncio.run(self._async_add_multiple_rooms()) + + async def _async_add_multiple_rooms(self): + await self.ring.add("room-1", "#Dev", "Thema A") + await self.ring.add("room-2", "#Support", "Thema B") + await self.ring.add("room-3", "#Design", "Thema C") + self.assertEqual(self.ring.size, 3) + + def test_add_empty_topic_ignored(self): + """Leeres Topic wird ignoriert.""" + asyncio.run(self._async_add_empty_topic_ignored()) + + async def _async_add_empty_topic_ignored(self): + await self.ring.add("room-1", "#Dev", "") + self.assertEqual(self.ring.size, 0) + + def test_add_empty_room_id_ignored(self): + """Leere room_id wird ignoriert.""" + asyncio.run(self._async_add_empty_room_id_ignored()) + + async def _async_add_empty_room_id_ignored(self): + await self.ring.add("", "#Dev", "Thema") + self.assertEqual(self.ring.size, 0) + + def test_ring_max_entries(self): + """Ring wirft älteste Einträge raus wenn max_entries erreicht.""" + asyncio.run(self._async_ring_max_entries()) + + async def _async_ring_max_entries(self): + for i in range(7): + await self.ring.add(f"room-{i}", f"#Room{i}", f"Thema {i}") + self.assertEqual(self.ring.size, 5) + entries = await self.ring.get_entries() + # Die ältesten 2 (room-0, room-1) sollten raus sein + room_ids = [e["room_id"] for e in entries] + self.assertNotIn("room-0", room_ids) + self.assertNotIn("room-1", room_ids) + + # ── get_summary() Tests ───────────────────────────────────────────── + + def test_get_summary_formats_correctly(self): + """get_summary() formatiert Einträge korrekt.""" + asyncio.run(self._async_get_summary_formats_correctly()) + + async def _async_get_summary_formats_correctly(self): + await self.ring.add("room-1", "#Dev", "Deployment-Status") + await self.ring.add("room-2", "#Support", "Login-Fehler") + summary = await self.ring.get_summary() + self.assertIn("Raum-übergreifender Kontext", summary) + self.assertIn("#Dev: Deployment-Status", summary) + self.assertIn("#Support: Login-Fehler", summary) + + def test_get_summary_excludes_room(self): + """get_summary() schließt angegebenen Raum aus.""" + asyncio.run(self._async_get_summary_excludes_room()) + + async def _async_get_summary_excludes_room(self): + await self.ring.add("room-1", "#Dev", "Thema A") + await self.ring.add("room-2", "#Support", "Thema B") + summary = await self.ring.get_summary(exclude_room_id="room-1") + self.assertNotIn("#Dev", summary) + self.assertIn("#Support", summary) + + def test_get_summary_empty_ring(self): + """get_summary() auf leerem Ring gibt leeren String zurück.""" + asyncio.run(self._async_get_summary_empty_ring()) + + async def _async_get_summary_empty_ring(self): + summary = await self.ring.get_summary() + self.assertEqual(summary, "") + + # ── move_gc() Tests ───────────────────────────────────────────────── + + def test_move_gc_removes_stale_and_adds_new(self): + """move_gc() entfernt stale Einträge aus Ursprungsraum und fügt neuen für Zielraum hinzu.""" + asyncio.run(self._async_move_gc_removes_stale_and_adds_new()) + + async def _async_move_gc_removes_stale_and_adds_new(self): + # Füge Eintrag für Ursprungsraum hinzu + await self.ring.add("origin-1", "#General", "Deployment-Status prüfen") + self.assertEqual(self.ring.size, 1) + + # Move: Ursprungsraum → Zielraum + await self.ring.move_gc( + origin_room_id="origin-1", + target_room_id="target-1", + topic="Deployment-Status prüfen", + room_name="#DevOps", + ) + + self.assertEqual(self.ring.size, 1) + entries = await self.ring.get_entries() + self.assertEqual(entries[0]["room_id"], "target-1") + self.assertEqual(entries[0]["room_name"], "#DevOps") + self.assertEqual(entries[0]["topic"], "Deployment-Status prüfen") + + def test_move_gc_new_topic_only_adds(self): + """move_gc() mit neuem Thema (kein existierender Eintrag) fügt nur neuen Eintrag hinzu.""" + asyncio.run(self._async_move_gc_new_topic_only_adds()) + + async def _async_move_gc_new_topic_only_adds(self): + # Füge Eintrag für Ursprungsraum hinzu (anderes Thema) + await self.ring.add("origin-1", "#General", "Altes Thema") + self.assertEqual(self.ring.size, 1) + + # Move mit NEUEM Thema + await self.ring.move_gc( + origin_room_id="origin-1", + target_room_id="target-1", + topic="Neues Thema", + room_name="#DevOps", + ) + + # Alter Eintrag bleibt, neuer kommt dazu + self.assertEqual(self.ring.size, 2) + entries = await self.ring.get_entries() + topics = [e["topic"] for e in entries] + self.assertIn("Altes Thema", topics) + self.assertIn("Neues Thema", topics) + + def test_move_gc_empty_params_ignored(self): + """move_gc() mit leeren Parametern wird ignoriert.""" + asyncio.run(self._async_move_gc_empty_params_ignored()) + + async def _async_move_gc_empty_params_ignored(self): + await self.ring.add("origin-1", "#General", "Thema") + await self.ring.move_gc("", "target-1", "Thema") + self.assertEqual(self.ring.size, 1) # Keine Änderung + + def test_move_gc_multiple_stale_entries(self): + """move_gc() entfernt mehrere stale Einträge für dasselbe Thema aus Ursprungsraum.""" + asyncio.run(self._async_move_gc_multiple_stale_entries()) + + async def _async_move_gc_multiple_stale_entries(self): + # Simuliere: gleiches Thema wurde mehrfach im Ursprungsraum gepostet + await self.ring.add("origin-1", "#General", "Deployment-Status") + await self.ring.add("room-2", "#Support", "Login-Fehler") + await self.ring.add("origin-1", "#General", "Deployment-Status") # Überschreibt + self.assertEqual(self.ring.size, 2) + + await self.ring.move_gc( + origin_room_id="origin-1", + target_room_id="target-1", + topic="Deployment-Status", + room_name="#DevOps", + ) + + self.assertEqual(self.ring.size, 2) # Login-Fehler bleibt, Deployment-Status jetzt in target-1 + entries = await self.ring.get_entries() + room_ids = [e["room_id"] for e in entries] + self.assertNotIn("origin-1", room_ids) + self.assertIn("target-1", room_ids) + self.assertIn("room-2", room_ids) + + # ── clear() Tests ─────────────────────────────────────────────────── + + def test_clear_empties_ring(self): + """clear() löscht alle Einträge.""" + asyncio.run(self._async_clear_empties_ring()) + + async def _async_clear_empties_ring(self): + await self.ring.add("room-1", "#Dev", "Thema A") + await self.ring.add("room-2", "#Support", "Thema B") + self.assertEqual(self.ring.size, 2) + await self.ring.clear() + self.assertEqual(self.ring.size, 0) + + # ── get_entries() Tests ───────────────────────────────────────────── + + def test_get_entries_returns_dicts(self): + """get_entries() liefert korrekte Dict-Struktur.""" + asyncio.run(self._async_get_entries_returns_dicts()) + + async def _async_get_entries_returns_dicts(self): + await self.ring.add("room-1", "#Dev", "Thema A") + entries = await self.ring.get_entries() + self.assertEqual(len(entries), 1) + self.assertIn("room_id", entries[0]) + self.assertIn("room_name", entries[0]) + self.assertIn("topic", entries[0]) + self.assertIn("timestamp", entries[0]) + + # ── CrossRoomEntry Tests ──────────────────────────────────────────── + + def test_cross_room_entry_to_summary_line(self): + """CrossRoomEntry.to_summary_line() formatiert korrekt.""" + entry = CrossRoomEntry( + room_id="room-1", + room_name="#Dev", + topic="Deployment-Status", + ) + line = entry.to_summary_line() + self.assertEqual(line, " #Dev: Deployment-Status") + + # ── Edge Cases ────────────────────────────────────────────────────── + + def test_max_entries_validation(self): + """max_entries < 1 wirft ValueError.""" + with self.assertRaises(ValueError): + MultiRoomContextRing(max_entries=0) + + def test_concurrent_adds(self): + """Parallele add()-Aufrufe sind thread-safe.""" + asyncio.run(self._async_concurrent_adds()) + + async def _async_concurrent_adds(self): + async def add_many(): + for i in range(10): + await self.ring.add(f"room-{i}", f"#Room{i}", f"Thema {i}") + + # Zwei parallele Tasks + await asyncio.gather(add_many(), add_many()) + # Sollte nicht crashen und max_entries einhalten + self.assertLessEqual(self.ring.size, 5) + + +if __name__ == "__main__": + unittest.main() diff --git a/plugin/archivar/tests/test_sticky_session.py b/plugin/archivar/tests/test_sticky_session.py new file mode 100644 index 0000000..649fdf2 --- /dev/null +++ b/plugin/archivar/tests/test_sticky_session.py @@ -0,0 +1,165 @@ +""" +V8.1.1 R3: Tests für Session-Sticky — temporäres Sticky, 30 Min Timeout, Catch-All-Guard. + +Prüft: +- Session-Sticky wird korrekt gesetzt (30 Min TTL) +- Session-Sticky läuft nach 30 Min ab +- Catch-All-Guard: Sticky auf Catch-All-Raum wird ignoriert +- stay_in_room-Guard: Sticky wird ignoriert wenn Raum stay_in_room hat +- Sticky-Expiry räumt Eintrag auf +""" + +from __future__ import annotations + +import os +import sys +import tempfile +import time +import unittest +from unittest.mock import MagicMock, patch + +# Add the parent directory to the path +sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) + +from archivar_state import ArchivarState + + +class TestSessionSticky(unittest.TestCase): + """Tests für das temporäre Session-Sticky (V8.1 P2).""" + + 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) + + # ── Sticky TTL Tests ──────────────────────────────────────────────── + + def test_sticky_30_min_ttl(self): + """Session-Sticky hat 30 Minuten TTL.""" + now = time.time() + expires_at = now + 1800 # 30 Minuten + self.assertAlmostEqual(expires_at - now, 1800, delta=1) + + def test_sticky_expired_after_30_min(self): + """Session-Sticky ist nach 30 Minuten abgelaufen.""" + now = time.time() + expires_at = now + 1800 + # Simuliere 31 Minuten später + future = now + 1860 + self.assertTrue(future > expires_at) + + def test_sticky_still_valid_before_30_min(self): + """Session-Sticky ist vor 30 Minuten noch gültig.""" + now = time.time() + expires_at = now + 1800 + # Simuliere 29 Minuten später + future = now + 1740 + self.assertTrue(future < expires_at) + + # ── Catch-All-Guard Tests ─────────────────────────────────────────── + + def test_catch_all_guard_blocks_sticky(self): + """Catch-All-Guard: Sticky auf Catch-All-Raum wird blockiert.""" + # Simuliere: target_room ist catch_all + target_is_catch_all = True + should_route = not target_is_catch_all + self.assertFalse(should_route) + + def test_non_catch_all_passes_guard(self): + """Nicht-Catch-All-Raum passiert den Guard.""" + target_is_catch_all = False + should_route = not target_is_catch_all + self.assertTrue(should_route) + + # ── stay_in_room-Guard Tests ──────────────────────────────────────── + + def test_stay_in_room_always_blocks_sticky(self): + """stay_in_room='always' blockiert Session-Sticky.""" + origin_state = "always" + should_route = origin_state not in ("always", "never_route") + self.assertFalse(should_route) + + def test_stay_in_room_never_route_blocks_sticky(self): + """stay_in_room='never_route' blockiert Session-Sticky.""" + origin_state = "never_route" + should_route = origin_state not in ("always", "never_route") + self.assertFalse(should_route) + + def test_stay_in_room_none_passes_guard(self): + """stay_in_room=None (keine Entscheidung) passiert den Guard.""" + origin_state = None + should_route = origin_state not in ("always", "never_route") + self.assertTrue(should_route) + + # ── Sticky Cleanup Tests ──────────────────────────────────────────── + + def test_expired_sticky_cleaned_up(self): + """Abgelaufener Sticky wird aus _session_room_preferences entfernt.""" + room_id = "test-room-123" + prefs = { + room_id: { + "target_room": "target-456", + "target_name": "#Dev", + "expires_at": time.time() - 10, # Bereits abgelaufen + } + } + # Cleanup-Logik + if time.time() >= prefs[room_id]["expires_at"]: + del prefs[room_id] + self.assertNotIn(room_id, prefs) + + def test_valid_sticky_not_cleaned_up(self): + """Gültiger Sticky wird NICHT entfernt.""" + room_id = "test-room-123" + prefs = { + room_id: { + "target_room": "target-456", + "target_name": "#Dev", + "expires_at": time.time() + 1800, # Noch gültig + } + } + # Cleanup-Logik + if time.time() >= prefs[room_id]["expires_at"]: + del prefs[room_id] + self.assertIn(room_id, prefs) + + # ── Sticky Data Structure Tests ───────────────────────────────────── + + def test_sticky_pref_structure(self): + """Session-Sticky hat korrekte Datenstruktur.""" + pref = { + "target_room": "target-456", + "target_name": "#DevOps", + "expires_at": time.time() + 1800, + } + self.assertIn("target_room", pref) + self.assertIn("target_name", pref) + self.assertIn("expires_at", pref) + self.assertIsInstance(pref["expires_at"], float) + self.assertGreater(pref["expires_at"], time.time()) + + def test_sticky_multiple_rooms_independent(self): + """Mehrere Räume haben unabhängige Sticky-Einträge.""" + prefs = { + "room-a": { + "target_room": "target-1", + "target_name": "#Dev", + "expires_at": time.time() + 1800, + }, + "room-b": { + "target_room": "target-2", + "target_name": "#Support", + "expires_at": time.time() + 1800, + }, + } + self.assertEqual(len(prefs), 2) + self.assertEqual(prefs["room-a"]["target_room"], "target-1") + self.assertEqual(prefs["room-b"]["target_room"], "target-2") + + +if __name__ == "__main__": + unittest.main()