feat: V8.4 — Red Flag: Agent als 6. Entscheidungsträger (Pre-Dispatch-Hook, Ring-Feedback, Feature-Flag)
This commit is contained in:
@@ -0,0 +1,599 @@
|
||||
"""
|
||||
V8.4: Red Flag — Agent als 6. Entscheidungsträger.
|
||||
|
||||
Pre-Dispatch-Hook zwischen Archivar-STAY und Agent-Dispatch:
|
||||
- Wenn Archivar Stufe 5 (Default-STAY) bei >1 available Raum → UNCERTAIN → Red Flag
|
||||
- Archivar schickt strukturierten Prompt an Agent: 'Router unsicher. Räume: ... Welcher Raum? Antworte: ROOM: <raumname>'
|
||||
- Agent entscheidet VOR der Antwort: WO antworten
|
||||
- Agent antwortet mit ROOM: <raumname> → Route + Ring-Feedback
|
||||
- Agent antwortet nicht innerhalb Timeout → STAY (Fallback)
|
||||
- Ring wird mit Agent-Entscheidung trainiert (source='red_flag')
|
||||
|
||||
Tests:
|
||||
1. Red Flag Trigger: STAY bei >1 Raum → is_red_flag=True
|
||||
2. Red Flag NICHT bei 1 Raum → is_red_flag=False
|
||||
3. Feature-Flag AUS → kein Red Flag
|
||||
4. Red-Flag-Prompt korrekt strukturiert
|
||||
5. ROOM:-Parsing: gültige Antwort → Route
|
||||
6. ROOM:-Parsing: keine ROOM: → STAY Fallback
|
||||
7. Telemetrie: red_flag_triggered + red_flag_fallback_stay
|
||||
8. Sticky-Bypass-Reihenfolge: vor Feature-Flag
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import List, Optional
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
# Ensure the archivar package is importable
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
from plugin.archivar.router import BidirectionalRouter, RoutingDecision
|
||||
from plugin.archivar.room_map import RoomMap, RoomEntry
|
||||
from plugin.archivar.classifier import IntentClassifier, EmbeddingClient
|
||||
from plugin.archivar.archivar_state import ArchivarState
|
||||
from plugin.archivar.routing_telemetry import RoutingTelemetry, routing_telemetry
|
||||
from plugin.archivar.routing_counter import routing_counter
|
||||
|
||||
|
||||
# ── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class MockEmbeddingClient(EmbeddingClient):
|
||||
"""Mock embedding client that returns fixed vectors."""
|
||||
|
||||
def get_embedding(self, text: str) -> Optional[List[float]]:
|
||||
return [0.1] * 768
|
||||
|
||||
|
||||
def _make_multi_room_map() -> RoomMap:
|
||||
"""Build a RoomMap with 3 non-catch-all rooms + 1 catch-all."""
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
map_path = Path(tmp.name) / "room-map.json"
|
||||
|
||||
test_data = {
|
||||
"version": 5,
|
||||
"rooms": {
|
||||
"room_rc_plugin": {
|
||||
"name": "#RC-Plugin",
|
||||
"theme": "Rocket.Chat Plugin Entwicklung",
|
||||
"description": "Entwicklung des Hermes Rocket.Chat Plugins",
|
||||
"keywords_100": ["plugin", "rocketchat"],
|
||||
"keywords_context": ["adapter", "gateway"],
|
||||
"catch_all": False,
|
||||
},
|
||||
"room_lan_doku": {
|
||||
"name": "#LAN-Doku",
|
||||
"theme": "LAN Dokumentation",
|
||||
"description": "Dokumentation des LAN-Netzwerks",
|
||||
"keywords_100": ["dokumentation", "doku"],
|
||||
"keywords_context": ["netzwerk", "lan"],
|
||||
"catch_all": False,
|
||||
},
|
||||
"room_bat_team": {
|
||||
"name": "#BAT-Team",
|
||||
"theme": "BAT Team Koordination",
|
||||
"description": "Koordination des BAT-Teams",
|
||||
"keywords_100": ["bat", "team"],
|
||||
"keywords_context": ["support", "hilfe"],
|
||||
"catch_all": False,
|
||||
},
|
||||
"room_catchall": {
|
||||
"name": "#CatchAll",
|
||||
"theme": "Catch-all room",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"butler_mode": "cognitive",
|
||||
"fact_store_path": str(Path(tmp.name) / "docs"),
|
||||
}
|
||||
with open(map_path, "w") as f:
|
||||
json.dump(test_data, f)
|
||||
|
||||
room_map = RoomMap.load(path=map_path)
|
||||
# Keep tmp alive by attaching it
|
||||
room_map._tmpdir = tmp
|
||||
return room_map
|
||||
|
||||
|
||||
def _make_single_room_map() -> RoomMap:
|
||||
"""Build a RoomMap with only 1 non-catch-all room + 1 catch-all."""
|
||||
tmp = tempfile.TemporaryDirectory()
|
||||
map_path = Path(tmp.name) / "room-map.json"
|
||||
|
||||
test_data = {
|
||||
"version": 5,
|
||||
"rooms": {
|
||||
"room_rc_plugin": {
|
||||
"name": "#RC-Plugin",
|
||||
"theme": "Rocket.Chat Plugin Entwicklung",
|
||||
"description": "Entwicklung des Hermes Rocket.Chat Plugins",
|
||||
"keywords_100": ["plugin", "rocketchat"],
|
||||
"keywords_context": ["adapter", "gateway"],
|
||||
"catch_all": False,
|
||||
},
|
||||
"room_catchall": {
|
||||
"name": "#CatchAll",
|
||||
"theme": "Catch-all room",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
},
|
||||
"excluded_rooms": [],
|
||||
"butler_mode": "cognitive",
|
||||
"fact_store_path": str(Path(tmp.name) / "docs"),
|
||||
}
|
||||
with open(map_path, "w") as f:
|
||||
json.dump(test_data, f)
|
||||
|
||||
room_map = RoomMap.load(path=map_path)
|
||||
room_map._tmpdir = tmp
|
||||
return room_map
|
||||
|
||||
|
||||
def _make_router(room_map: RoomMap, mock_llm_fn=None) -> BidirectionalRouter:
|
||||
"""Build a BidirectionalRouter with mock classifier and state."""
|
||||
mock_client = MockEmbeddingClient()
|
||||
classifier = IntentClassifier(embedding_client=mock_client)
|
||||
state = ArchivarState()
|
||||
|
||||
router = BidirectionalRouter(room_map, classifier, state)
|
||||
|
||||
if mock_llm_fn is not None:
|
||||
classifier._llm_raw = mock_llm_fn
|
||||
|
||||
return router
|
||||
|
||||
|
||||
# ── Red Flag Trigger Tests ─────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestRedFlagTrigger:
|
||||
"""Red Flag wird nur bei STAY + >1 verfügbarem Raum ausgelöst."""
|
||||
|
||||
def test_red_flag_triggers_on_stay_with_multi_rooms(self):
|
||||
"""STAY bei >1 Nicht-Catch-All-Raum → is_red_flag=True, red_flag_rooms gefüllt."""
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_stay(prompt: str) -> str:
|
||||
return "STAY"
|
||||
|
||||
router = _make_router(room_map, mock_llm_stay)
|
||||
|
||||
# Route a message that won't match any keywords
|
||||
decision = asyncio.run(router.route(
|
||||
"Was hältst du von der neuen Architektur?",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
# Should trigger Red Flag: STAY + >1 available rooms
|
||||
assert decision.is_red_flag is True, (
|
||||
f"Expected is_red_flag=True, got {decision.is_red_flag}"
|
||||
)
|
||||
assert len(decision.red_flag_rooms) >= 2, (
|
||||
f"Expected >=2 red_flag_rooms, got {len(decision.red_flag_rooms)}"
|
||||
)
|
||||
# red_flag_rooms should contain room names (not IDs)
|
||||
assert any("LAN-Doku" in r for r in decision.red_flag_rooms), (
|
||||
f"Expected 'LAN-Doku' in red_flag_rooms: {decision.red_flag_rooms}"
|
||||
)
|
||||
assert any("BAT-Team" in r for r in decision.red_flag_rooms), (
|
||||
f"Expected 'BAT-Team' in red_flag_rooms: {decision.red_flag_rooms}"
|
||||
)
|
||||
|
||||
def test_red_flag_not_triggered_with_single_room(self):
|
||||
"""Nur 1 Nicht-Catch-All-Raum → kein Red Flag, normales STAY."""
|
||||
room_map = _make_single_room_map()
|
||||
|
||||
async def mock_llm_stay(prompt: str) -> str:
|
||||
return "STAY"
|
||||
|
||||
router = _make_router(room_map, mock_llm_stay)
|
||||
|
||||
decision = asyncio.run(router.route(
|
||||
"Was hältst du von der neuen Architektur?",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
# Should NOT trigger Red Flag: only 1 available room
|
||||
assert decision.is_red_flag is False, (
|
||||
f"Expected is_red_flag=False with single room, got {decision.is_red_flag}"
|
||||
)
|
||||
assert decision.stay_in_room is True
|
||||
|
||||
def test_red_flag_not_triggered_when_llm_routes(self):
|
||||
"""LLM routet → kein Red Flag (nur bei STAY)."""
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_route(prompt: str) -> str:
|
||||
return "room_lan_doku"
|
||||
|
||||
router = _make_router(room_map, mock_llm_route)
|
||||
|
||||
decision = asyncio.run(router.route(
|
||||
"Dokumentiere das neue Feature",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
# Should NOT trigger Red Flag: LLM found a room
|
||||
assert decision.is_red_flag is False, (
|
||||
f"Expected is_red_flag=False when LLM routes, got {decision.is_red_flag}"
|
||||
)
|
||||
|
||||
def test_red_flag_not_triggered_when_keyword_matches(self):
|
||||
"""100%-Keyword-Match → kein Red Flag (überspringt LLM-STAY)."""
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_stay(prompt: str) -> str:
|
||||
return "STAY"
|
||||
|
||||
router = _make_router(room_map, mock_llm_stay)
|
||||
|
||||
# "dokumentation" is a 100% keyword for #LAN-Doku
|
||||
decision = asyncio.run(router.route(
|
||||
"Bitte dokumentiere das neue Feature",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
# Should NOT trigger Red Flag: keyword match bypasses LLM
|
||||
assert decision.is_red_flag is False, (
|
||||
f"Expected is_red_flag=False on keyword match, got {decision.is_red_flag}"
|
||||
)
|
||||
# Should have routed to LAN-Doku
|
||||
assert decision.target_room == "room_lan_doku", (
|
||||
f"Expected target_room=room_lan_doku, got {decision.target_room}"
|
||||
)
|
||||
|
||||
|
||||
# ── Feature-Flag Tests ─────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestRedFlagFeatureFlag:
|
||||
"""ARCHIVAR_RED_FLAG env var steuert Red-Flag-Verhalten."""
|
||||
|
||||
def test_feature_flag_default_on(self):
|
||||
"""Default (env nicht gesetzt) → Red Flag aktiv."""
|
||||
# Ensure env is not set
|
||||
if "ARCHIVAR_RED_FLAG" in os.environ:
|
||||
del os.environ["ARCHIVAR_RED_FLAG"]
|
||||
|
||||
from plugin.archivar.config import ARCHIVAR_RED_FLAG
|
||||
# Re-import to pick up env change
|
||||
import importlib
|
||||
import plugin.archivar.config as cfg
|
||||
importlib.reload(cfg)
|
||||
assert cfg.ARCHIVAR_RED_FLAG is True, (
|
||||
f"Expected ARCHIVAR_RED_FLAG=True by default, got {cfg.ARCHIVAR_RED_FLAG}"
|
||||
)
|
||||
|
||||
def test_feature_flag_off(self, monkeypatch):
|
||||
"""ARCHIVAR_RED_FLAG=false → Red Flag deaktiviert."""
|
||||
monkeypatch.setenv("ARCHIVAR_RED_FLAG", "false")
|
||||
|
||||
import importlib
|
||||
import plugin.archivar.config as cfg
|
||||
importlib.reload(cfg)
|
||||
assert cfg.ARCHIVAR_RED_FLAG is False
|
||||
|
||||
def test_feature_flag_off_disables_red_flag_in_router(self, monkeypatch):
|
||||
"""Feature-Flag AUS → is_red_flag immer False, auch bei >1 Raum."""
|
||||
# Set the flag directly on the router module (import-time constant)
|
||||
import plugin.archivar.router as router_mod
|
||||
monkeypatch.setattr(router_mod, "ARCHIVAR_RED_FLAG", False)
|
||||
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_stay(prompt: str) -> str:
|
||||
return "STAY"
|
||||
|
||||
router = _make_router(room_map, mock_llm_stay)
|
||||
|
||||
decision = asyncio.run(router.route(
|
||||
"Was hältst du von der neuen Architektur?",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
assert decision.is_red_flag is False, (
|
||||
"Red Flag should be disabled when feature flag is off"
|
||||
)
|
||||
|
||||
|
||||
# ── Red Flag Prompt Tests ──────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestRedFlagPrompt:
|
||||
"""Der Red-Flag-Prompt ist korrekt strukturiert."""
|
||||
|
||||
def test_prompt_contains_room_list(self):
|
||||
"""Prompt enthält alle verfügbaren Räume (außer Catch-All + Origin)."""
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_stay(prompt: str) -> str:
|
||||
return "STAY"
|
||||
|
||||
router = _make_router(room_map, mock_llm_stay)
|
||||
|
||||
decision = asyncio.run(router.route(
|
||||
"Generische Frage ohne klares Thema",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
assert decision.is_red_flag is True
|
||||
prompt = decision.red_flag_prompt
|
||||
assert prompt is not None
|
||||
assert "Router unsicher" in prompt, f"Prompt missing 'Router unsicher': {prompt}"
|
||||
assert "ROOM:" in prompt, f"Prompt missing 'ROOM:': {prompt}"
|
||||
# Should NOT include origin room in the list
|
||||
assert "RC-Plugin" not in prompt or "Ursprungsraum" in prompt, (
|
||||
f"Origin room should not be listed as option: {prompt}"
|
||||
)
|
||||
# Should include other rooms
|
||||
assert "LAN-Doku" in prompt, f"Prompt missing LAN-Doku: {prompt}"
|
||||
assert "BAT-Team" in prompt, f"Prompt missing BAT-Team: {prompt}"
|
||||
|
||||
def test_prompt_excludes_catch_all(self):
|
||||
"""Prompt enthält NICHT den Catch-All-Raum."""
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_stay(prompt: str) -> str:
|
||||
return "STAY"
|
||||
|
||||
router = _make_router(room_map, mock_llm_stay)
|
||||
|
||||
decision = asyncio.run(router.route(
|
||||
"Generische Frage",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
assert decision.is_red_flag is True
|
||||
prompt = decision.red_flag_prompt
|
||||
assert "CatchAll" not in prompt, (
|
||||
f"Catch-All should not be in prompt: {prompt}"
|
||||
)
|
||||
|
||||
|
||||
# ── ROOM: Parsing Tests ────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestRoomParsing:
|
||||
"""ROOM: <raumname> wird korrekt aus Agent-Antwort extrahiert."""
|
||||
|
||||
def test_parse_room_exact_match(self):
|
||||
"""ROOM: #LAN-Doku → erkannt und aufgelöst."""
|
||||
from plugin.archivar.router import _parse_red_flag_response
|
||||
|
||||
room_map = _make_multi_room_map()
|
||||
result = _parse_red_flag_response("ROOM: #LAN-Doku", room_map)
|
||||
assert result == "room_lan_doku", f"Expected room_lan_doku, got {result}"
|
||||
|
||||
def test_parse_room_without_hash(self):
|
||||
"""ROOM: LAN-Doku → erkannt (ohne #)."""
|
||||
from plugin.archivar.router import _parse_red_flag_response
|
||||
|
||||
room_map = _make_multi_room_map()
|
||||
result = _parse_red_flag_response("ROOM: LAN-Doku", room_map)
|
||||
assert result == "room_lan_doku", f"Expected room_lan_doku, got {result}"
|
||||
|
||||
def test_parse_room_case_insensitive(self):
|
||||
"""ROOM: lan-doku → erkannt (case-insensitive)."""
|
||||
from plugin.archivar.router import _parse_red_flag_response
|
||||
|
||||
room_map = _make_multi_room_map()
|
||||
result = _parse_red_flag_response("ROOM: lan-doku", room_map)
|
||||
assert result == "room_lan_doku", f"Expected room_lan_doku, got {result}"
|
||||
|
||||
def test_parse_room_with_text_after(self):
|
||||
"""ROOM: #LAN-Doku\n\nHier ist die Antwort... → nur ROOM: wird extrahiert."""
|
||||
from plugin.archivar.router import _parse_red_flag_response
|
||||
|
||||
room_map = _make_multi_room_map()
|
||||
result = _parse_red_flag_response(
|
||||
"ROOM: #LAN-Doku\n\nHier ist die eigentliche Antwort auf deine Frage.",
|
||||
room_map,
|
||||
)
|
||||
assert result == "room_lan_doku", f"Expected room_lan_doku, got {result}"
|
||||
|
||||
def test_parse_room_not_found(self):
|
||||
"""ROOM: UnbekannterRaum → None (Fallback STAY)."""
|
||||
from plugin.archivar.router import _parse_red_flag_response
|
||||
|
||||
room_map = _make_multi_room_map()
|
||||
result = _parse_red_flag_response("ROOM: UnbekannterRaum", room_map)
|
||||
assert result is None, f"Expected None for unknown room, got {result}"
|
||||
|
||||
def test_parse_no_room_prefix(self):
|
||||
"""Kein ROOM: im Text → None (Fallback STAY)."""
|
||||
from plugin.archivar.router import _parse_red_flag_response
|
||||
|
||||
room_map = _make_multi_room_map()
|
||||
result = _parse_red_flag_response(
|
||||
"Hier ist die Antwort auf deine Frage, aber ohne ROOM: Prefix.",
|
||||
room_map,
|
||||
)
|
||||
assert result is None, f"Expected None without ROOM:, got {result}"
|
||||
|
||||
def test_parse_room_empty_response(self):
|
||||
"""Leere Antwort → None."""
|
||||
from plugin.archivar.router import _parse_red_flag_response
|
||||
|
||||
room_map = _make_multi_room_map()
|
||||
result = _parse_red_flag_response("", room_map)
|
||||
assert result is None
|
||||
|
||||
def test_parse_room_with_whitespace(self):
|
||||
"""ROOM: #BAT-Team → erkannt (Whitespace-tolerant)."""
|
||||
from plugin.archivar.router import _parse_red_flag_response
|
||||
|
||||
room_map = _make_multi_room_map()
|
||||
result = _parse_red_flag_response("ROOM: #BAT-Team ", room_map)
|
||||
assert result == "room_bat_team", f"Expected room_bat_team, got {result}"
|
||||
|
||||
def test_strip_room_prefix(self):
|
||||
"""_strip_red_flag_prefix entfernt ROOM: Zeile aus Antwort."""
|
||||
from plugin.archivar.router import _strip_red_flag_prefix
|
||||
|
||||
text = "ROOM: #LAN-Doku\n\nHier ist die eigentliche Antwort."
|
||||
result = _strip_red_flag_prefix(text)
|
||||
assert result == "Hier ist die eigentliche Antwort.", (
|
||||
f"Expected stripped text, got: {result}"
|
||||
)
|
||||
|
||||
def test_strip_room_prefix_no_room(self):
|
||||
"""_strip_red_flag_prefix: kein ROOM: → Text unverändert."""
|
||||
from plugin.archivar.router import _strip_red_flag_prefix
|
||||
|
||||
text = "Hier ist eine normale Antwort."
|
||||
result = _strip_red_flag_prefix(text)
|
||||
assert result == text
|
||||
|
||||
|
||||
# ── Telemetrie Tests ───────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestRedFlagTelemetry:
|
||||
"""Telemetrie-Counter für Red Flag."""
|
||||
|
||||
def test_red_flag_triggered_counter(self):
|
||||
"""red_flag_triggered wird bei Red-Flag-Trigger inkrementiert."""
|
||||
routing_counter.reset()
|
||||
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_stay(prompt: str) -> str:
|
||||
return "STAY"
|
||||
|
||||
router = _make_router(room_map, mock_llm_stay)
|
||||
|
||||
asyncio.run(router.route(
|
||||
"Generische Frage",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
counts = routing_counter.get_counts()
|
||||
assert counts.get("red_flag_triggered", 0) >= 1, (
|
||||
f"Expected red_flag_triggered >= 1, got {counts}"
|
||||
)
|
||||
|
||||
def test_red_flag_fallback_stay_counter(self):
|
||||
"""red_flag_fallback_stay wird bei Fallback (kein ROOM:) inkrementiert."""
|
||||
routing_counter.reset()
|
||||
|
||||
# This is tested via _parse_red_flag_response returning None
|
||||
from plugin.archivar.router import _parse_red_flag_response
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
# Simulate: Agent didn't respond with ROOM:
|
||||
result = _parse_red_flag_response("Keine ROOM: Antwort", room_map)
|
||||
assert result is None
|
||||
|
||||
# In production, the adapter would increment red_flag_fallback_stay
|
||||
routing_counter.increment("red_flag_fallback_stay")
|
||||
counts = routing_counter.get_counts()
|
||||
assert counts.get("red_flag_fallback_stay", 0) == 1
|
||||
|
||||
|
||||
# ── Sticky-Bypass-Reihenfolge Tests ────────────────────────────────────────
|
||||
|
||||
|
||||
class TestStickyBypassOrder:
|
||||
"""Sticky-Bypass wird VOR Feature-Flag geprüft (Rainer's Review)."""
|
||||
|
||||
def test_sticky_bypass_before_red_flag(self):
|
||||
"""Wenn Sticky aktiv → kein Red Flag, auch bei >1 Raum."""
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_stay(prompt: str) -> str:
|
||||
return "STAY"
|
||||
|
||||
router = _make_router(room_map, mock_llm_stay)
|
||||
|
||||
# Set a never_route (sticky) for the origin room.
|
||||
# Topic must match _room_name_to_topic("#LAN-Doku") = "lan-doku"
|
||||
router._state.set_never_route("room_rc_plugin", "lan-doku")
|
||||
|
||||
# Message that would match LAN-Doku via context keyword "lan"
|
||||
# but sticky should block before Red Flag triggers
|
||||
decision = asyncio.run(router.route(
|
||||
"Noch eine Frage zum Netzwerk-Setup im LAN",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
# Sticky should block routing entirely — no Red Flag needed
|
||||
assert decision.stay_in_room is True, (
|
||||
f"Expected stay_in_room=True, got {decision.stay_in_room}"
|
||||
)
|
||||
assert decision.is_red_flag is False, (
|
||||
"Sticky should prevent Red Flag from triggering"
|
||||
)
|
||||
|
||||
|
||||
# ── RoutingDecision Fields ─────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestRoutingDecisionFields:
|
||||
"""RoutingDecision hat die neuen Red-Flag-Felder."""
|
||||
|
||||
def test_red_flag_fields_exist(self):
|
||||
"""is_red_flag, red_flag_rooms, red_flag_prompt sind definiert."""
|
||||
decision = RoutingDecision(
|
||||
category="direct_question",
|
||||
target_room="",
|
||||
confidence=0.0,
|
||||
)
|
||||
assert hasattr(decision, "is_red_flag")
|
||||
assert hasattr(decision, "red_flag_rooms")
|
||||
assert hasattr(decision, "red_flag_prompt")
|
||||
assert decision.is_red_flag is False
|
||||
assert decision.red_flag_rooms == []
|
||||
assert decision.red_flag_prompt == ""
|
||||
|
||||
|
||||
# ── Integration: Red Flag → Adapter Flow ──────────────────────────────────
|
||||
|
||||
|
||||
class TestRedFlagAdapterIntegration:
|
||||
"""Red-Flag-Decision wird korrekt an Adapter durchgereicht."""
|
||||
|
||||
def test_classify_and_route_returns_red_flag(self):
|
||||
"""classify_and_route() gibt Red-Flag-Decision zurück."""
|
||||
from plugin.archivar.adapter_integration import ArchivarMessageHandler
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_stay(prompt: str) -> str:
|
||||
return "STAY"
|
||||
|
||||
# Build handler with mocked dependencies
|
||||
with patch(
|
||||
"plugin.archivar.adapter_integration.ArchivarMessageHandler._load_room_map",
|
||||
return_value=room_map,
|
||||
):
|
||||
handler = ArchivarMessageHandler()
|
||||
handler._initialized = True
|
||||
# Replace router with our test router
|
||||
router = _make_router(room_map, mock_llm_stay)
|
||||
handler._router = router
|
||||
handler._room_map = room_map
|
||||
|
||||
decision = asyncio.run(handler.classify_and_route(
|
||||
"Generische Frage ohne klares Thema",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
assert decision.is_red_flag is True
|
||||
assert len(decision.red_flag_rooms) >= 2
|
||||
assert decision.red_flag_prompt is not None
|
||||
assert "Router unsicher" in decision.red_flag_prompt
|
||||
Reference in New Issue
Block a user