fix(archivar): P-108 Sticky-Scope bleibt im Ursprungsraum bei themenarmer Folge-Nachricht
This commit is contained in:
+22
-3
@@ -1377,6 +1377,10 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# 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]] = {}
|
||||
# P-108a: Flag — Sticky wurde in diesem Turn via B2 (kein 100%-Keyword-Match)
|
||||
# bypassed. Verhindert, dass der Archivar-Fallthrough (Setter B) den Sticky
|
||||
# ungeprüft erneuert. Wird pro Turn am Anfang des Archivar-Blocks zurückgesetzt.
|
||||
self._sticky_bypassed_this_turn: bool = False
|
||||
# V7-2: _sticky_rooms removed — thematic never_route replaces spatial bypass.
|
||||
# The router's _check_never_route_topic handles per-topic blocking now.
|
||||
# Clarify state: maps clarify_id → session_key for gateway resolution
|
||||
@@ -3927,6 +3931,10 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# Intentional bypass paths setzen False. Fall-through paths
|
||||
# (Sticky-Bypass, B2-No-Topic, Expliziter-Wechsel-ohne-#) behalten True.
|
||||
_should_classify = True
|
||||
# P-108a: Sticky-Bypass-Flag pro Turn zurücksetzen. Der B2-Block
|
||||
# (kein 100%-Keyword-Match) setzt es, der Archivar-Fallthrough
|
||||
# (Setter B) prüft es, um den Sticky nicht ungeprüft zu erneuern.
|
||||
self._sticky_bypassed_this_turn = False
|
||||
|
||||
try:
|
||||
if _MULTIROOM() and self.archivar is not None:
|
||||
@@ -3999,10 +4007,18 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.info(
|
||||
"[rocketchat] V8.3.4 B2: No topic extracted from message — "
|
||||
"sticky_topic='%s' but no 100%% keyword match → ignoring sticky, "
|
||||
"falling through to Archivar",
|
||||
"staying in origin room (P-108)",
|
||||
sticky_topic,
|
||||
)
|
||||
# Fall through to Archivar classification
|
||||
# P-108: Sticky ignorieren, Nachricht im Ursprungsraum behalten.
|
||||
# KEIN Fall-through zum Archivar — die Nachricht gehört
|
||||
# offensichtlich zum aktuellen Raum. _should_classify=False
|
||||
# verhindert, dass der Archivar erneut routet; die Nachricht
|
||||
# wird normal an den Agent dispatcht.
|
||||
# P-108a: Flag setzen, damit der Archivar-Fallthrough
|
||||
# (Setter B) den Sticky NICHT ungeprüft erneuert.
|
||||
self._sticky_bypassed_this_turn = True
|
||||
_should_classify = False
|
||||
else:
|
||||
# Thema matcht → Sticky greift
|
||||
# V8.1.1 R1: Catch-All-Guard — nicht in Catch-All-Raum auto-routen
|
||||
@@ -4406,7 +4422,10 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# V8.3-5: Temporäres Sticky mit Topic-Scoping (30 Min TTL)
|
||||
# V8.3.2 F1: Nur setzen wenn decision.set_sticky=True
|
||||
# (100%-Keyword-Match). FAISS/LLM-Routing setzt KEINEN Sticky.
|
||||
if getattr(decision, 'set_sticky', False):
|
||||
# P-108a: Wenn der B2-Block oben den Sticky bypassed hat
|
||||
# (kein 100%-Keyword-Match), darf der Archivar-Fallthrough den
|
||||
# Sticky NICHT ungeprüft erneuern.
|
||||
if getattr(decision, 'set_sticky', False) and not self._sticky_bypassed_this_turn:
|
||||
self._session_room_preferences[room_id] = {
|
||||
"target_room": target_room_id,
|
||||
"target_name": target_name,
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
"""
|
||||
P-108: Topic-Scoped Sticky — themenarme Folge-Nachricht bleibt im Ursprungsraum.
|
||||
|
||||
Root Cause (P-108): Nach einem Move-Request-Confirm (BAT-Team) wird eine
|
||||
Folge-Nachricht ohne klares 100%-Keyword durch den Topic-Scoped Sticky in den
|
||||
Sticky-Target-Raum geroutet, statt im Ursprungsraum zu bleiben. Die B2-Logik
|
||||
(kein Topic → Sticky ignorieren) war korrekt implementiert, griff aber erst
|
||||
bei der ZWEITEN Folge-Nachricht — die erste lief durch den Archivar-Fallthrough
|
||||
mit ``target_room=BAT-Team``.
|
||||
|
||||
Fix-Variante A (Rainer, reviewed von Bernd):
|
||||
1. B2-Block (kein 100%-Keyword-Match): Sticky ignorieren, Nachricht im
|
||||
Ursprungsraum behalten. ``_should_classify = False`` — KEIN Fall-through
|
||||
zum Archivar. Die Nachricht wird normal an den Agent dispatcht.
|
||||
2. P-108a: Flag ``_sticky_bypassed_this_turn`` wird im B2-Block gesetzt und
|
||||
vor dem Archivar-Setter B geprüft — der Sticky wird NICHT ungeprüft
|
||||
erneuert.
|
||||
|
||||
Diese Tests verifizieren:
|
||||
1. Sticky + kurze Nachricht ("Ja, bitte") → bleibt im Ursprungsraum, kein
|
||||
Archivar-Routing.
|
||||
2. Sticky + Frage ("Was meinst du?") → bleibt im Ursprungsraum.
|
||||
3. Sticky + klares 100%-Keyword → Sticky greift, Auto-Route (REGRESSION-GUARD).
|
||||
4. Sticky + Nachricht ohne 100%-Match → Sticky ignoriert UND nicht erneuert
|
||||
(P-108a-Schutz).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
# Ensure the plugin package is importable (mirrors test_v8_3_4.py)
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
# Reuse the mock-adapter builder from the existing V8.3.4 integration tests.
|
||||
from test_v8_3_4 import _build_mock_adapter, _make_minimal_room_map_json # noqa: E402
|
||||
|
||||
|
||||
class TestP108StickyScope(unittest.TestCase):
|
||||
"""P-108: Sticky-Scope bleibt im Ursprungsraum bei themenarmer Folge-Nachricht."""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls._tmpdir = tempfile.TemporaryDirectory()
|
||||
cls._room_map_path = _make_minimal_room_map_json(cls._tmpdir.name)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls._tmpdir.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
self.adapter, self.mock_rest = _build_mock_adapter(self._room_map_path)
|
||||
# Mock classify_and_route so we can assert it is NOT called (P-108 core).
|
||||
self.adapter.archivar.classify_and_route = AsyncMock(return_value=None)
|
||||
# Mock handle_message so the normal dispatch path is observable.
|
||||
self.adapter.handle_message = AsyncMock()
|
||||
|
||||
def _set_sticky(self, origin: str, target: str, target_name: str, topic: str):
|
||||
"""Set a topic-scoped sticky preference: origin → target."""
|
||||
self.adapter._session_room_preferences[origin] = {
|
||||
"target_room": target,
|
||||
"target_name": target_name,
|
||||
"sticky_topic": topic,
|
||||
"expires_at": time.time() + 1800,
|
||||
}
|
||||
|
||||
def _msg(self, text: str, room: str) -> dict:
|
||||
return {
|
||||
"_id": "msg_p108",
|
||||
"rid": room,
|
||||
"msg": text,
|
||||
"u": {"username": "testuser"},
|
||||
}
|
||||
|
||||
# ── Test 1: kurze Nachricht ohne Topic → bleibt im Ursprungsraum ──────
|
||||
|
||||
def test_sticky_no_topic_short_message_keeps_in_room(self):
|
||||
"""Sticky + 'Ja, bitte' (1 Wort) → bleibt im Ursprungsraum, kein Archivar-Routing."""
|
||||
self._set_sticky(
|
||||
"room_bat_team", "room_rc_plugin", "#Rocketchat-Plugin", "rocketchat-plugin"
|
||||
)
|
||||
|
||||
asyncio.run(self.adapter._process_incoming(self._msg("Ja, bitte", "room_bat_team")))
|
||||
|
||||
# P-108 Kern: KEIN Archivar-Routing (classify_and_route nicht aufgerufen)
|
||||
self.adapter.archivar.classify_and_route.assert_not_awaited()
|
||||
# Kein Sticky-Auto-Route: _dispatch_agent NICHT mit Zielraum aufgerufen
|
||||
dispatch_rooms = [
|
||||
c.kwargs.get("room_id")
|
||||
for c in self.adapter._dispatch_agent.call_args_list
|
||||
]
|
||||
self.assertNotIn("room_rc_plugin", dispatch_rooms,
|
||||
"Sticky darf bei themenarmer Nachricht NICHT in den Zielraum routen")
|
||||
|
||||
# ── Test 2: Frage ohne Topic → bleibt im Ursprungsraum ────────────────
|
||||
|
||||
def test_sticky_no_topic_question_keeps_in_room(self):
|
||||
"""Sticky + 'Was meinst du?' (Frage, 2 Wörter) → bleibt im Ursprungsraum."""
|
||||
self._set_sticky(
|
||||
"room_bat_team", "room_rc_plugin", "#Rocketchat-Plugin", "rocketchat-plugin"
|
||||
)
|
||||
|
||||
asyncio.run(self.adapter._process_incoming(self._msg("Was meinst du?", "room_bat_team")))
|
||||
|
||||
self.adapter.archivar.classify_and_route.assert_not_awaited()
|
||||
dispatch_rooms = [
|
||||
c.kwargs.get("room_id")
|
||||
for c in self.adapter._dispatch_agent.call_args_list
|
||||
]
|
||||
self.assertNotIn("room_rc_plugin", dispatch_rooms,
|
||||
"Sticky darf bei themenarmer Frage NICHT in den Zielraum routen")
|
||||
|
||||
# ── Test 3: klares 100%-Keyword → Sticky greift (REGRESSION-GUARD) ────
|
||||
|
||||
def test_sticky_with_clear_topic_still_routes(self):
|
||||
"""Sticky + klares 100%-Keyword → Sticky greift, Auto-Route wie bisher."""
|
||||
# Sticky: room_rc_plugin → room_bat_team, topic='bat-team'.
|
||||
# 'BAT-Framework Doku' matcht 'bat' (keywords_100 von #BAT-Team).
|
||||
self._set_sticky(
|
||||
"room_rc_plugin", "room_bat_team", "#BAT-Team", "bat-team"
|
||||
)
|
||||
|
||||
asyncio.run(self.adapter._process_incoming(
|
||||
self._msg("BAT-Framework Doku", "room_rc_plugin")
|
||||
))
|
||||
|
||||
# Sticky greift: _dispatch_agent im Zielraum aufgerufen
|
||||
dispatch_rooms = [
|
||||
c.kwargs.get("room_id")
|
||||
for c in self.adapter._dispatch_agent.call_args_list
|
||||
]
|
||||
self.assertIn("room_bat_team", dispatch_rooms,
|
||||
"Sticky muss bei klarem 100%-Keyword weiterhin in den Zielraum routen")
|
||||
|
||||
# ── Test 4: kein 100%-Match → Sticky ignoriert UND nicht erneuert ─────
|
||||
|
||||
def test_sticky_no_topic_keyword_match_does_not_renew_sticky(self):
|
||||
"""Sticky + 'Pitfall in der neuen Architektur' (kein 100%-Match) →
|
||||
Sticky ignoriert UND nicht erneuert (P-108a-Schutz)."""
|
||||
self._set_sticky(
|
||||
"room_bat_team", "room_rc_plugin", "#Rocketchat-Plugin", "rocketchat-plugin"
|
||||
)
|
||||
# Snapshot des Sticky-Eintrags VOR der Verarbeitung
|
||||
before = dict(self.adapter._session_room_preferences["room_bat_team"])
|
||||
|
||||
asyncio.run(self.adapter._process_incoming(
|
||||
self._msg("Pitfall in der neuen Architektur", "room_bat_team")
|
||||
))
|
||||
|
||||
# Kein Archivar-Routing
|
||||
self.adapter.archivar.classify_and_route.assert_not_awaited()
|
||||
# P-108a: Sticky NICHT erneuert — Eintrag unverändert (gleicher expires_at)
|
||||
after = self.adapter._session_room_preferences.get("room_bat_team")
|
||||
self.assertIsNotNone(after, "Sticky darf nicht gelöscht werden")
|
||||
self.assertEqual(after["expires_at"], before["expires_at"],
|
||||
"Sticky darf bei themenarmer Nachricht NICHT erneuert werden (P-108a)")
|
||||
self.assertEqual(after["sticky_topic"], before["sticky_topic"],
|
||||
"sticky_topic darf sich nicht ändern")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -238,11 +238,12 @@ class TestV843B2FallthroughRedFlag(unittest.TestCase):
|
||||
self.adapter, self.mock_rest = _build_mock_adapter(self._room_map_path)
|
||||
|
||||
def test_b2_no_topic_falls_through_to_classify_and_route(self):
|
||||
"""B2 No-Topic: classify_and_route wird aufgerufen (nicht übergangen).
|
||||
"""B2 No-Topic: classify_and_route wird NICHT aufgerufen (P-108).
|
||||
|
||||
Sticky ist aktiv, aber die Nachricht enthält KEIN 100%-Keyword.
|
||||
Vor V8.4.3: classify_and_route wurde NIE aufgerufen.
|
||||
Nach V8.4.3: classify_and_route wird aufgerufen → Red Flag kann feuern.
|
||||
Vor P-108 (V8.4.3): classify_and_route wurde aufgerufen (Fall-through).
|
||||
Nach P-108: Sticky wird ignoriert, Nachricht bleibt im Ursprungsraum —
|
||||
KEIN Archivar-Routing, die Nachricht wird normal an den Agent dispatcht.
|
||||
"""
|
||||
# Set up sticky session preference: origin room → target room
|
||||
self.adapter._session_room_preferences["room_bat_team"] = {
|
||||
@@ -260,43 +261,29 @@ class TestV843B2FallthroughRedFlag(unittest.TestCase):
|
||||
"u": {"username": "testuser"},
|
||||
}
|
||||
|
||||
# Patch classify_and_route to track calls AND return a Red Flag decision
|
||||
from plugin.archivar.router import RoutingDecision
|
||||
|
||||
red_flag_decision = RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=0.0,
|
||||
stay_in_room=True,
|
||||
is_red_flag=True,
|
||||
red_flag_rooms=["#LAN-Doku", "#BAT-Team"],
|
||||
red_flag_prompt="ROUTER UNSICHER: ...",
|
||||
)
|
||||
|
||||
original_classify = self.adapter.archivar.classify_and_route
|
||||
# Patch classify_and_route to track calls
|
||||
call_count = [0]
|
||||
|
||||
async def tracking_classify(text, origin_room_id="", **kwargs):
|
||||
call_count[0] += 1
|
||||
return red_flag_decision
|
||||
return None
|
||||
|
||||
self.adapter.archivar.classify_and_route = tracking_classify
|
||||
|
||||
asyncio.run(self.adapter._process_incoming(msg_obj))
|
||||
|
||||
# Verify: classify_and_route WAS called
|
||||
self.assertEqual(call_count[0], 1,
|
||||
f"classify_and_route should be called once, got {call_count[0]} calls")
|
||||
# P-108: classify_and_route wird NICHT aufgerufen — Nachricht bleibt
|
||||
# im Ursprungsraum, kein Archivar-Routing.
|
||||
self.assertEqual(call_count[0], 0,
|
||||
f"classify_and_route should NOT be called on B2 no-topic (P-108), got {call_count[0]} calls")
|
||||
|
||||
def test_b2_no_topic_red_flag_decision_reaches_dispatch(self):
|
||||
"""B2 No-Topic: is_red_flag=True erreicht den Pre-Dispatch-Hook.
|
||||
"""B2 No-Topic: Nachricht wird normal dispatcht, OHNE Red-Flag (P-108).
|
||||
|
||||
Der Red-Flag-Prompt wird in den System-Prompt injiziert.
|
||||
Vor V8.4.3: is_red_flag=True wurde NIE erreicht weil
|
||||
classify_and_route nie aufgerufen wurde.
|
||||
Sticky aktiv + Nachricht ohne 100%-Keyword → Sticky ignoriert, kein
|
||||
Archivar-Routing → kein Red-Flag-Prompt. Die Nachricht wird normal an
|
||||
den Agent dispatcht (handle_message aufgerufen).
|
||||
"""
|
||||
from plugin.archivar.router import RoutingDecision
|
||||
|
||||
# Set up sticky session preference
|
||||
self.adapter._session_room_preferences["room_bat_team"] = {
|
||||
"target_room": "room_rc_plugin",
|
||||
@@ -305,21 +292,9 @@ class TestV843B2FallthroughRedFlag(unittest.TestCase):
|
||||
"expires_at": time.time() + 1800,
|
||||
}
|
||||
|
||||
red_flag_decision = RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=0.0,
|
||||
stay_in_room=True,
|
||||
is_red_flag=True,
|
||||
red_flag_rooms=["#LAN-Doku", "#BAT-Team"],
|
||||
red_flag_prompt="ROUTER UNSICHER: Wähle einen Raum.\n\n"
|
||||
"1. #LAN-Doku - LAN Dokumentation\n"
|
||||
"2. #BAT-Team - BAT Team Koordination\n\n"
|
||||
"Antworte mit: ROOM: <raumname>",
|
||||
)
|
||||
|
||||
async def tracking_classify(text, origin_room_id="", **kwargs):
|
||||
return red_flag_decision
|
||||
# Sollte nie aufgerufen werden (P-108)
|
||||
raise AssertionError("classify_and_route must not be called on B2 no-topic")
|
||||
|
||||
self.adapter.archivar.classify_and_route = tracking_classify
|
||||
|
||||
@@ -332,16 +307,16 @@ class TestV843B2FallthroughRedFlag(unittest.TestCase):
|
||||
|
||||
asyncio.run(self.adapter._process_incoming(msg_obj))
|
||||
|
||||
# Verify: handle_message was called (flow completed)
|
||||
# Verify: handle_message was called (flow completed — normal dispatch)
|
||||
self.adapter.handle_message.assert_called_once()
|
||||
|
||||
# Verify: Red Flag prompt was injected into chat_topic (system prompt)
|
||||
# Verify: KEIN Red-Flag-Prompt injiziert (kein Archivar-Routing)
|
||||
call_args = self.adapter.handle_message.call_args[0]
|
||||
event = call_args[0] # MessageEvent
|
||||
source = getattr(event, 'source', None)
|
||||
chat_topic = getattr(source, 'chat_topic', '') if source else ''
|
||||
self.assertIn("ROUTER UNSICHER", chat_topic,
|
||||
f"Red Flag prompt should be in source.chat_topic, got: {chat_topic[:200]}")
|
||||
self.assertNotIn("ROUTER UNSICHER", chat_topic,
|
||||
f"Red Flag prompt should NOT be injected on B2 no-topic (P-108), got: {chat_topic[:200]}")
|
||||
|
||||
def test_b2_no_topic_with_real_router_red_flag(self):
|
||||
"""B2 No-Topic: classify_and_route wird aufgerufen → Red Flag erreichbar.
|
||||
|
||||
Reference in New Issue
Block a user