feat(archivar): Stufe 4 Red Flag Detection + Bernd Activation
Routing-Pipeline Stufe 4: Wenn der LLM-Router unsicher ist (STAY bei
>1 Raum), verloren ist (Timeout/None) ODER ein neues Thema erkennt
(unbekannter Raum-Name), setzt der Archivar eine Red Flag und aktiviert
den Hauptagenten als Entscheidungsträger (STAY/ROUTE).
Änderungen:
- router.py: _llm_room_lookup liefert 5-Tupel (room, stay, failed,
reason, suggestion). reason ∈ {route, stay, unavailable, new_topic}.
Neues 'new_topic'-Signal: LLM nannte einen Raum der nicht in der
Raum-Map steht → Red Flag mit red_flag_suggestion.
- router.py: asyncio.wait_for(LLM_ROOM_LOOKUP_TIMEOUT) um den LLM-Call
(Rainer-Niagara-Befund #3: war ohne wait_for → Event-Loop-Blockade).
- router.py: RoutingDecision + red_flag_reason / red_flag_suggestion;
_build_red_flag_decision(reason, suggestion) injiziert den Grund als
Hinweis in den Red-Flag-Prompt.
- config.py: LLM_ROOM_LOOKUP_TIMEOUT (Default 15s, env-schaltbar).
- adapter.py: RED_FLAG_TIMEOUT tatsächlich anwenden (Rainer-Niagara
Befund #4: war toter Code) via _RED_FLAG_SET_TIME ContextVar;
Timeout → STAY-Fallback (red_flag_timeout_fallback).
- multiroom_context.py: CrossRoomEntry.source-Feld ('manual'/'move'/
'red_flag'); add(source=...) → Ring-Feedback mit Quellen-Tag für
Stufe-5-Lern-Semantik (Rainer FIX P2).
- adapter.py: Ring-Feedback source='red_flag'; Stufe-4-Feedback-Log
(reason + suggestion) für spätere Lern-Semantik (nur loggen, nicht
lernend — Andreas-Entscheidung offen).
Pitfalls adressiert: P-084 (neues Thema, kein toter Code mehr),
P-102 (Clarify-Responses greifen weiterhin NICHT — unverändert vor
classify_and_route).
Tests: test_stufe4_red_flag.py (13 Tests: new_topic, reason je Trigger,
Ring-source, Config-Timeout). 1643 Tests gesamt grün, keine Regression
in Stufe 1-3.
This commit is contained in:
@@ -0,0 +1,345 @@
|
||||
"""
|
||||
Stufe 4: Red Flag Detection + Bernd Activation (Routing-Pipeline).
|
||||
|
||||
Tests für die Stufe-4-Implementierung:
|
||||
1. Neues Thema (LLM nennt unbekannten Raum) → is_red_flag=True, reason='new_topic'
|
||||
2. LLM unsicher (STAY bei >1 Raum) → reason='llm_stay'
|
||||
3. LLM unavailable (None/Timeout) → reason='llm_unavailable'
|
||||
4. red_flag_suggestion trägt den unbekannten Raum-Namen bei new_topic
|
||||
5. Red-Flag-Prompt enthält den Grund-Hinweis
|
||||
6. MultiRoomContextRing.add() speichert source='red_flag'
|
||||
7. CrossRoomEntry default source='manual' (Abwärtskompatibilität)
|
||||
8. RED_FLAG_TIMEOUT + LLM_ROOM_LOOKUP_TIMEOUT sind konfigurierbar
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
from plugin.archivar.router import BidirectionalRouter, RoutingDecision
|
||||
from plugin.archivar.room_map import RoomMap
|
||||
from plugin.archivar.classifier import IntentClassifier, EmbeddingClient
|
||||
from plugin.archivar.archivar_state import ArchivarState
|
||||
from plugin.archivar.routing_counter import routing_counter
|
||||
|
||||
|
||||
# ── Helpers (Spiegel von test_v8_4.py) ─────────────────────────────────────
|
||||
|
||||
|
||||
class MockEmbeddingClient(EmbeddingClient):
|
||||
def get_embedding(self, text: str) -> Optional[list]:
|
||||
return [0.1] * 768
|
||||
|
||||
|
||||
def _make_multi_room_map() -> RoomMap:
|
||||
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)
|
||||
room_map._tmpdir = tmp
|
||||
return room_map
|
||||
|
||||
|
||||
def _make_router(room_map: RoomMap, mock_llm_fn=None) -> BidirectionalRouter:
|
||||
mock_client = MockEmbeddingClient()
|
||||
classifier = IntentClassifier(embedding_client=mock_client)
|
||||
state = ArchivarState(state_file_path="/tmp/archivar_test_state.json")
|
||||
import os as _os
|
||||
try:
|
||||
_os.remove("/tmp/archivar_test_state.json")
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
router = BidirectionalRouter(room_map, classifier, state)
|
||||
if mock_llm_fn is not None:
|
||||
classifier._llm_raw = mock_llm_fn
|
||||
return router
|
||||
|
||||
|
||||
# ── Stufe 4: Neues Thema ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestNewTopicRedFlag:
|
||||
"""LLM nennt einen Raum, der NICHT in der Raum-Map steht → neues Thema."""
|
||||
|
||||
def test_new_topic_triggers_red_flag(self):
|
||||
"""Unbekannter Raum-Name → is_red_flag=True, reason='new_topic'."""
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_unknown(prompt: str) -> str:
|
||||
return "#Reiseplanung" # Nicht in der Raum-Map
|
||||
|
||||
router = _make_router(room_map, mock_llm_unknown)
|
||||
|
||||
decision = asyncio.run(router.route(
|
||||
"Ich plane eine Chile-Reise und brauche einen Reiseplan",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
assert decision.is_red_flag is True, (
|
||||
f"Expected is_red_flag=True on new topic, got {decision.is_red_flag}"
|
||||
)
|
||||
assert decision.red_flag_reason == "new_topic", (
|
||||
f"Expected reason='new_topic', got {decision.red_flag_reason!r}"
|
||||
)
|
||||
assert decision.red_flag_suggestion == "#Reiseplanung", (
|
||||
f"Expected suggestion='#Reiseplanung', got {decision.red_flag_suggestion!r}"
|
||||
)
|
||||
|
||||
def test_new_topic_prompt_contains_hint(self):
|
||||
"""Red-Flag-Prompt enthält den Hinweis auf ein neues Thema."""
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_unknown(prompt: str) -> str:
|
||||
return "Reiseplanung"
|
||||
|
||||
router = _make_router(room_map, mock_llm_unknown)
|
||||
|
||||
decision = asyncio.run(router.route(
|
||||
"Ich brauche einen Reiseplan für Chile",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
assert decision.is_red_flag is True
|
||||
assert "neues Thema" in decision.red_flag_prompt, (
|
||||
f"Prompt should mention 'neues Thema': {decision.red_flag_prompt}"
|
||||
)
|
||||
assert "Reiseplanung" in decision.red_flag_prompt, (
|
||||
f"Prompt should contain suggestion: {decision.red_flag_prompt}"
|
||||
)
|
||||
|
||||
def test_new_topic_counter_increments(self):
|
||||
"""Counter 'llm_new_topic' wird bei unbekanntem Raum inkrementiert."""
|
||||
routing_counter.reset()
|
||||
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_unknown(prompt: str) -> str:
|
||||
return "UnbekannterThemenraum"
|
||||
|
||||
router = _make_router(room_map, mock_llm_unknown)
|
||||
|
||||
asyncio.run(router.route(
|
||||
"Ein Thema das nirgendwo reinpasst",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
counts = routing_counter.get_counts()
|
||||
assert counts.get("llm_new_topic", 0) >= 1, (
|
||||
f"Expected llm_new_topic >= 1, got {counts}"
|
||||
)
|
||||
assert counts.get("red_flag_triggered", 0) >= 1, (
|
||||
f"Expected red_flag_triggered >= 1, got {counts}"
|
||||
)
|
||||
|
||||
def test_unknown_plain_text_also_new_topic(self):
|
||||
"""Auch Freitext (kein #, keine bekannte ID) → neues Thema."""
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_unknown(prompt: str) -> str:
|
||||
return "Das gehört eigentlich in einen neuen Raum"
|
||||
|
||||
router = _make_router(room_map, mock_llm_unknown)
|
||||
|
||||
decision = asyncio.run(router.route(
|
||||
"Generische Nachricht",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
assert decision.is_red_flag is True
|
||||
assert decision.red_flag_reason == "new_topic"
|
||||
|
||||
|
||||
# ── Stufe 4: Red-Flag-Grund je Trigger-Typ ─────────────────────────────────
|
||||
|
||||
|
||||
class TestRedFlagReason:
|
||||
"""red_flag_reason unterscheidet die drei Trigger-Typen."""
|
||||
|
||||
def test_llm_stay_reason(self):
|
||||
"""LLM sagt STAY bei >1 Raum → reason='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)
|
||||
|
||||
decision = asyncio.run(router.route(
|
||||
"Generische Frage ohne klares Thema",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
assert decision.is_red_flag is True
|
||||
assert decision.red_flag_reason == "llm_stay", (
|
||||
f"Expected reason='llm_stay', got {decision.red_flag_reason!r}"
|
||||
)
|
||||
assert decision.red_flag_suggestion == ""
|
||||
|
||||
def test_llm_unavailable_reason(self):
|
||||
"""LLM liefert None → reason='llm_unavailable'."""
|
||||
room_map = _make_multi_room_map()
|
||||
|
||||
async def mock_llm_none(prompt: str) -> Optional[str]:
|
||||
return None
|
||||
|
||||
router = _make_router(room_map, mock_llm_none)
|
||||
|
||||
decision = asyncio.run(router.route(
|
||||
"Generische Frage",
|
||||
origin_room_id="room_rc_plugin",
|
||||
))
|
||||
|
||||
assert decision.is_red_flag is True
|
||||
assert decision.red_flag_reason == "llm_unavailable", (
|
||||
f"Expected reason='llm_unavailable', got {decision.red_flag_reason!r}"
|
||||
)
|
||||
|
||||
def test_stay_reason_prompt_contains_hint(self):
|
||||
"""llm_stay-Prompt enthält den Unsicherheits-Hinweis."""
|
||||
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
|
||||
assert "unsicher" in decision.red_flag_prompt, (
|
||||
f"Prompt should mention 'unsicher': {decision.red_flag_prompt}"
|
||||
)
|
||||
|
||||
|
||||
# ── Stufe 4: Ring-Feedback source-Tag ──────────────────────────────────────
|
||||
|
||||
|
||||
class TestRingSourceTag:
|
||||
"""MultiRoomContextRing speichert source='red_flag' für Stufe-5-Lernen."""
|
||||
|
||||
def test_add_stores_red_flag_source(self):
|
||||
from plugin.archivar.multiroom_context import MultiRoomContextRing
|
||||
|
||||
ring = MultiRoomContextRing(max_entries=10)
|
||||
|
||||
async def _run():
|
||||
await ring.add(
|
||||
"room_bat_team", "#BAT-Team",
|
||||
"Red Flag: Agent-Entscheidung → #BAT-Team",
|
||||
source="red_flag",
|
||||
)
|
||||
entries = await ring.get_entries()
|
||||
return entries
|
||||
|
||||
entries = asyncio.run(_run())
|
||||
assert len(entries) == 1
|
||||
assert entries[0]["source"] == "red_flag", (
|
||||
f"Expected source='red_flag', got {entries[0]['source']!r}"
|
||||
)
|
||||
|
||||
def test_add_default_source_manual(self):
|
||||
"""Ohne source-Argument → 'manual' (Abwärtskompatibilität)."""
|
||||
from plugin.archivar.multiroom_context import MultiRoomContextRing
|
||||
|
||||
ring = MultiRoomContextRing(max_entries=10)
|
||||
|
||||
async def _run():
|
||||
await ring.add("room-1", "#Dev", "Deployment-Status prüfen")
|
||||
entries = await ring.get_entries()
|
||||
return entries
|
||||
|
||||
entries = asyncio.run(_run())
|
||||
assert entries[0]["source"] == "manual", (
|
||||
f"Expected default source='manual', got {entries[0]['source']!r}"
|
||||
)
|
||||
|
||||
|
||||
# ── Stufe 4: Konfigurations-Konstanten ─────────────────────────────────────
|
||||
|
||||
|
||||
class TestStufe4Config:
|
||||
"""RED_FLAG_TIMEOUT und LLM_ROOM_LOOKUP_TIMEOUT sind konfigurierbar."""
|
||||
|
||||
def test_red_flag_timeout_default(self):
|
||||
from plugin.archivar import config
|
||||
assert config.RED_FLAG_TIMEOUT == 30.0
|
||||
|
||||
def test_red_flag_timeout_env(self, monkeypatch):
|
||||
monkeypatch.setenv("ARCHIVAR_RED_FLAG_TIMEOUT", "15.0")
|
||||
import importlib
|
||||
from plugin.archivar import config
|
||||
importlib.reload(config)
|
||||
try:
|
||||
assert config.RED_FLAG_TIMEOUT == 15.0
|
||||
finally:
|
||||
# Restore default — verhindert Cross-Test-Kontamination.
|
||||
monkeypatch.delenv("ARCHIVAR_RED_FLAG_TIMEOUT", raising=False)
|
||||
importlib.reload(config)
|
||||
|
||||
def test_llm_room_lookup_timeout_default(self):
|
||||
from plugin.archivar import config
|
||||
assert config.LLM_ROOM_LOOKUP_TIMEOUT == 15.0
|
||||
|
||||
def test_llm_room_lookup_timeout_env(self, monkeypatch):
|
||||
monkeypatch.setenv("ARCHIVAR_LLM_ROOM_LOOKUP_TIMEOUT", "5.0")
|
||||
import importlib
|
||||
from plugin.archivar import config
|
||||
importlib.reload(config)
|
||||
try:
|
||||
assert config.LLM_ROOM_LOOKUP_TIMEOUT == 5.0
|
||||
finally:
|
||||
monkeypatch.delenv("ARCHIVAR_LLM_ROOM_LOOKUP_TIMEOUT", raising=False)
|
||||
importlib.reload(config)
|
||||
Reference in New Issue
Block a user