From 00aecfaa7bb3f29583811048f86ce543fca3d413 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Wed, 2 Sep 2026 15:36:05 +0200 Subject: [PATCH] feat(archivar): Telemetrie um STAY/UNSICHER/TIMEOUT-Unterscheidung erweitern MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auftrag t_5e4863c6 — Routing-Telemetrie differenziert jetzt: - llm_stay_sicher — LLM sagte STAY (sicher), kein Red Flag, kein Cloud-Call - llm_unsicher — LLM sagte UNSICHER, Red Flag (Cloud-Call) - llm_timeout — LLM timeoutete (separat von llm_unavailable) - cloud_call_stay — Cloud-Agent endete mit STAY (Cloud-Call ohne Routing-Effekt) - cloud_call_route — Cloud-Agent entschied ROUTE (Cloud-Call mit Wirkung) - no_llm_needed — Nachricht vor Stufe 4 entschieden (FAISS/Keyword/Smalltalk) Abwärtskompatibel: llm_stay und llm_unavailable bleiben unverändert. ::status zeigt die neuen Zähler in einer Routing-Telemetrie-Sektion. 10 neue Tests (test_telemetry_stay_unsicher_timeout.py). --- plugin/adapter.py | 13 + plugin/archivar/inline_commands.py | 27 ++ plugin/archivar/router.py | 11 +- plugin/archivar/routing_telemetry.py | 2 +- .../test_telemetry_stay_unsicher_timeout.py | 304 ++++++++++++++++++ 5 files changed, 355 insertions(+), 2 deletions(-) create mode 100644 plugin/archivar/tests/test_telemetry_stay_unsicher_timeout.py diff --git a/plugin/adapter.py b/plugin/adapter.py index 8d8fbfa..7feea2a 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -5459,6 +5459,14 @@ class RocketChatAdapter(BasePlatformAdapter): current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online' pulse_active = self._presence_engine.is_pulse_active() + # Routing-Telemetrie (STAY/UNSICHER/TIMEOUT, Auftrag t_5e4863c6) + routing_counts = None + try: + from archivar.routing_counter import routing_counter + routing_counts = routing_counter.get_counts() + except Exception: + routing_counts = None + return build_status_text( room_count=room_count, archivar_active=archivar_active, @@ -5469,6 +5477,7 @@ class RocketChatAdapter(BasePlatformAdapter): current_status=current_status, pulse_active=pulse_active, plugin_version=PLUGIN_VERSION, + routing_counts=routing_counts, ) async def _cmd_reset(self, room_id: str, args: str) -> str: @@ -8957,6 +8966,7 @@ class RocketChatAdapter(BasePlatformAdapter): "(Agent-Antwort verworfen für Routing)", RED_FLAG_TIMEOUT, ) + routing_counter.increment('cloud_call_stay') # Antwort bleibt im Ursprungsraum (kein ROOM:-Parsing). else: _RED_FLAG_SET_TIME.set(0.0) @@ -8974,6 +8984,7 @@ class RocketChatAdapter(BasePlatformAdapter): target_room_id[:8], origin_room[:8] if origin_room else "?", ) routing_counter.increment('red_flag_agent_routed') + routing_counter.increment('cloud_call_route') # Route: Antwort geht in den Zielraum _CURRENT_ORIGIN_ROOM.set(target_room_id) _THEMATIC_TARGET_ROOM.set(target_room_id) @@ -9008,6 +9019,7 @@ class RocketChatAdapter(BasePlatformAdapter): "STAY-Fallback (Ursprungsraum)" ) routing_counter.increment('red_flag_fallback_stay') + routing_counter.increment('cloud_call_stay') # ── Stufe 5: Butler-Rückfrage vorbereiten ────────────── # Bei Red Flag (Unsicherheit) fragt der Archivar den User, # ob das Routing gemerkt werden soll. Die Rückfrage wird @@ -9080,6 +9092,7 @@ class RocketChatAdapter(BasePlatformAdapter): "[rocketchat] V8.4 Red Flag: Response-Interception failed: %s", e ) routing_counter.increment('red_flag_fallback_stay') + routing_counter.increment('cloud_call_stay') # ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ────────── # Hermes Core sendet Meldungen mit /approve, /deny etc. diff --git a/plugin/archivar/inline_commands.py b/plugin/archivar/inline_commands.py index f7d7e10..0c24713 100644 --- a/plugin/archivar/inline_commands.py +++ b/plugin/archivar/inline_commands.py @@ -520,6 +520,7 @@ def build_status_text( current_status: str = "online", pulse_active: bool = False, plugin_version: str = "", + routing_counts: Optional[Dict[str, int]] = None, ) -> str: """Baut die Status-Seite mit aktuellen Plugin-Informationen. @@ -533,6 +534,9 @@ def build_status_text( current_status: Aktueller Presence-Status ('online', 'away', 'busy'). pulse_active: Ob der PulseController gerade pulsiert. plugin_version: Plugin-Version (z.B. "9.2 (1d31d2c)"). + routing_counts: Routing-Counter-Dict (aus routing_counter.get_counts()). + Wenn gesetzt, wird eine STAY/UNSICHER/TIMEOUT-Telemetrie-Sektion + angezeigt (Auftrag t_5e4863c6). Returns: Formatierte Status-Seite. @@ -579,6 +583,29 @@ def build_status_text( lines.append("") lines.append(room_map_summary) + # ── Routing-Telemetrie (STAY/UNSICHER/TIMEOUT, Auftrag t_5e4863c6) ── + if routing_counts: + lines.append("") + lines.append("**Routing-Telemetrie (seit Gateway-Start):**") + lines.append( + f"- **LLM STAY (sicher):** {routing_counts.get('llm_stay_sicher', 0)}" + ) + lines.append( + f"- **LLM UNSICHER:** {routing_counts.get('llm_unsicher', 0)}" + ) + lines.append( + f"- **LLM Timeout:** {routing_counts.get('llm_timeout', 0)}" + ) + lines.append( + f"- **Cloud-Call → STAY:** {routing_counts.get('cloud_call_stay', 0)}" + ) + lines.append( + f"- **Cloud-Call → ROUTE:** {routing_counts.get('cloud_call_route', 0)}" + ) + lines.append( + f"- **Ohne LLM entschieden:** {routing_counts.get('no_llm_needed', 0)}" + ) + lines.append("") lines.append("💡 `::hilfe` für alle Befehle | `::status` für Aktualisierung") diff --git a/plugin/archivar/router.py b/plugin/archivar/router.py index d9c876b..376f002 100644 --- a/plugin/archivar/router.py +++ b/plugin/archivar/router.py @@ -1101,6 +1101,7 @@ class BidirectionalRouter: text[:80], matched_room.name, ) routing_counter.increment('keyword_100_auto_route') + routing_counter.increment('no_llm_needed') routing_telemetry.record( stage='keyword_100', score=1.0, decision='route', target=matched_room.room_id, origin=origin_room_id, @@ -1125,6 +1126,7 @@ class BidirectionalRouter: text[:80], matched_room.name, ) routing_counter.increment('keyword_context_butler') + routing_counter.increment('no_llm_needed') routing_telemetry.record( stage='context_keyword', score=0.95, decision='butler', target=matched_room.room_id, origin=origin_room_id, @@ -1212,6 +1214,7 @@ class BidirectionalRouter: booster_applied, ) routing_counter.increment('faiss_auto_route') + routing_counter.increment('no_llm_needed') routing_telemetry.record( stage='faiss', score=top_score, decision='route', target=top_room_id, origin=origin_room_id, @@ -1243,6 +1246,7 @@ class BidirectionalRouter: FAISS_AUTO_ROUTE, ) routing_counter.increment('faiss_butler') + routing_counter.increment('no_llm_needed') routing_telemetry.record( stage='faiss', score=top_score, decision='butler', target=top_room_id, origin=origin_room_id, @@ -1267,6 +1271,7 @@ class BidirectionalRouter: ) if is_smalltalk: + routing_counter.increment('no_llm_needed') return RoutingDecision( category="smalltalk", target_room="", @@ -1319,6 +1324,7 @@ class BidirectionalRouter: "100%% Keyword-Match (4.5): '%s' → %s — Auto-Route (kein Butler)", text[:80], matched_room.name, ) + routing_counter.increment('no_llm_needed') return RoutingDecision( category="work_order", target_room=matched_room.room_id, @@ -1336,6 +1342,7 @@ class BidirectionalRouter: "Kontext-Keyword-Match (4.5): '%s' → %s — Butler fragt", text[:80], matched_room.name, ) + routing_counter.increment('no_llm_needed') return RoutingDecision( category="work_order", target_room=matched_room.room_id, @@ -1438,7 +1445,7 @@ class BidirectionalRouter: ) routing_counter.increment('llm_unsicher') routing_telemetry.record( - stage='llm', score=0.0, decision='stay', + stage='llm', score=0.0, decision='unsicher', target='', origin=origin_room_id, duration_ms=routing_telemetry.elapsed_ms(), ) @@ -1470,6 +1477,7 @@ class BidirectionalRouter: "LLM-Raum-Router: STAY für '%.80s...' → stay_in_room", text[:80] ) routing_counter.increment('llm_stay') + routing_counter.increment('llm_stay_sicher') routing_telemetry.record( stage='llm', score=0.0, decision='stay', target='', origin=origin_room_id, @@ -1696,6 +1704,7 @@ class BidirectionalRouter: LLM_ROOM_LOOKUP_TIMEOUT, text, ) routing_counter.increment('llm_room_lookup_timeout') + routing_counter.increment('llm_timeout') routing_counter.record_attempt(success=False) return None, False, True, "unavailable", "" except Exception as e: diff --git a/plugin/archivar/routing_telemetry.py b/plugin/archivar/routing_telemetry.py index a538d55..919bcbb 100644 --- a/plugin/archivar/routing_telemetry.py +++ b/plugin/archivar/routing_telemetry.py @@ -87,7 +87,7 @@ class RoutingTelemetry: Args: stage: 'keyword_100' | 'context_keyword' | 'faiss' | 'llm' | 'default' score: FAISS-Score, LLM-Confidence, 1.0 bei 100%-Match, 0.0 bei Default - decision: 'route' | 'stay' | 'butler' | 'timeout' + decision: 'route' | 'stay' | 'butler' | 'timeout' | 'unsicher' target: Zielraum-ID (oder '' bei stay) origin: Ursprungsraum-ID duration_ms: Dauer der Stufe in Millisekunden diff --git a/plugin/archivar/tests/test_telemetry_stay_unsicher_timeout.py b/plugin/archivar/tests/test_telemetry_stay_unsicher_timeout.py new file mode 100644 index 0000000..28ef77e --- /dev/null +++ b/plugin/archivar/tests/test_telemetry_stay_unsicher_timeout.py @@ -0,0 +1,304 @@ +""" +Telemetrie-Erweiterung: STAY/UNSICHER/TIMEOUT-Unterscheidung (Auftrag t_5e4863c6). + +Die bisherige Telemetrie zählte nur llm_stay, llm_unavailable, red_flag_triggered. +Diese Erweiterung unterscheidet: + +1. llm_stay_sicher — LLM sagte STAY (sicher), kein Red Flag, kein Cloud-Call +2. llm_unsicher — LLM sagte UNSICHER, Red Flag (Cloud-Call) +3. llm_timeout — LLM timeoutete (separater Zähler, nicht mit llm_unavailable vermischt) +4. cloud_call_stay — Cloud-Agent endete mit STAY (Cloud-Call ohne Routing-Effekt) +5. cloud_call_route — Cloud-Agent entschied ROUTE (Cloud-Call mit Wirkung) +6. no_llm_needed — Nachricht wurde vor Stufe 4 entschieden (FAISS/Keyword/Smalltalk) + +Abwärtskompatibilität: llm_stay und llm_unavailable bleiben unverändert. +""" + +from __future__ import annotations + +import asyncio +import json +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 +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 + + +class MockEmbeddingClient(EmbeddingClient): + def get_embedding(self, text: str) -> Optional[list]: + return [0.1] * 768 + + +def _make_room_map(non_catchall: int) -> RoomMap: + """Baut eine RoomMap mit N Nicht-Catch-All-Räumen + 1 Catch-All.""" + tmp = tempfile.TemporaryDirectory() + map_path = Path(tmp.name) / "room-map.json" + + rooms = {} + for i in range(non_catchall): + rooms[f"room_{i}"] = { + "name": f"#Raum{i}", + "theme": f"Thema {i}", + "description": f"Beschreibung {i}", + "keywords_100": [f"kw{i}"], + "keywords_context": [], + "catch_all": False, + } + rooms["room_catchall"] = { + "name": "#CatchAll", + "theme": "Catch-all room", + "keywords_100": [], + "keywords_context": [], + "catch_all": True, + } + + test_data = { + "version": 5, + "rooms": rooms, + "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 + + +# ── Zähler 1: llm_stay_sicher ──────────────────────────────────────────────── + + +class TestLlmStaySicher: + """STAY (sicher) inkrementiert llm_stay_sicher, NICHT red_flag_triggered.""" + + def test_stay_increments_llm_stay_sicher(self): + routing_counter.reset() + room_map = _make_room_map(non_catchall=5) + + 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_0")) + + counts = routing_counter.get_counts() + assert counts.get("llm_stay_sicher", 0) >= 1, ( + f"Expected llm_stay_sicher >= 1, got {counts}" + ) + # Abwärtskompatibilität: llm_stay bleibt ebenfalls inkrementiert. + assert counts.get("llm_stay", 0) >= 1 + # Kein Red Flag → kein Cloud-Call. + assert counts.get("red_flag_triggered", 0) == 0 + + +# ── Zähler 2: llm_unsicher ─────────────────────────────────────────────────── + + +class TestLlmUnsicher: + """UNSICHER inkrementiert llm_unsicher + red_flag_triggered.""" + + def test_unsicher_increments_llm_unsicher(self): + routing_counter.reset() + room_map = _make_room_map(non_catchall=2) + + async def mock_llm_unsicher(prompt: str) -> str: + return "UNSICHER" + + router = _make_router(room_map, mock_llm_unsicher) + asyncio.run(router.route("Mehrdeutige Nachricht", origin_room_id="room_0")) + + counts = routing_counter.get_counts() + assert counts.get("llm_unsicher", 0) >= 1, ( + f"Expected llm_unsicher >= 1, got {counts}" + ) + assert counts.get("red_flag_triggered", 0) >= 1 + + +# ── Zähler 3: llm_timeout ──────────────────────────────────────────────────── + + +class TestLlmTimeout: + """Timeout inkrementiert llm_timeout (separat von llm_unavailable).""" + + def test_timeout_increments_llm_timeout(self): + """Echter asyncio.TimeoutError → llm_timeout + llm_unavailable.""" + routing_counter.reset() + room_map = _make_room_map(non_catchall=5) + + async def mock_llm_timeout(prompt: str) -> str: + raise asyncio.TimeoutError() + + router = _make_router(room_map, mock_llm_timeout) + asyncio.run(router.route("Generische Frage", origin_room_id="room_0")) + + counts = routing_counter.get_counts() + # llm_timeout wird bei echtem Timeout inkrementiert. + assert counts.get("llm_timeout", 0) >= 1, ( + f"Expected llm_timeout >= 1, got {counts}" + ) + # llm_unavailable bleibt der Umbrella-Zähler (Abwärtskompatibilität). + assert counts.get("llm_unavailable", 0) >= 1 + + def test_timeout_counter_distinct_from_unavailable(self): + """llm_timeout ist ein eigener Key, unabhängig von llm_unavailable.""" + routing_counter.reset() + # Direkt: der Zähler ist ein separater Key im Counter-Dict. + routing_counter.increment("llm_timeout") + routing_counter.increment("llm_unavailable") + counts = routing_counter.get_counts() + assert counts["llm_timeout"] == 1 + assert counts["llm_unavailable"] == 1 + + +# ── Zähler 4 + 5: cloud_call_stay / cloud_call_route ──────────────────────── + + +class TestCloudCallCounters: + """Cloud-Call-Ergebnis wird als stay/route unterschieden.""" + + def test_cloud_call_counters_are_distinct_keys(self): + routing_counter.reset() + routing_counter.increment("cloud_call_stay") + routing_counter.increment("cloud_call_route") + counts = routing_counter.get_counts() + assert counts["cloud_call_stay"] == 1 + assert counts["cloud_call_route"] == 1 + + +# ── Zähler 6: no_llm_needed ───────────────────────────────────────────────── + + +class TestNoLlmNeeded: + """Nachricht vor Stufe 4 entschieden → no_llm_needed.""" + + def test_smalltalk_increments_no_llm_needed(self): + """Smalltalk (Embedding-Vorfilter) → no_llm_needed, kein LLM-Call.""" + routing_counter.reset() + room_map = _make_room_map(non_catchall=3) + + # Mock classifier: Smalltalk mit hoher Konfidenz. + from plugin.archivar.classifier import ClassificationResult + + class SmalltalkClassifier(IntentClassifier): + def __init__(self): + super().__init__(embedding_client=MockEmbeddingClient()) + self._initialized = True + + async def classify(self, text): + return ClassificationResult( + category="smalltalk", confidence=0.95, all_scores={} + ) + + 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, SmalltalkClassifier(), state) + + asyncio.run(router.route("Hallo, wie geht's?", origin_room_id="room_0")) + + counts = routing_counter.get_counts() + assert counts.get("no_llm_needed", 0) >= 1, ( + f"Expected no_llm_needed >= 1, got {counts}" + ) + + +# ── Abwärtskompatibilität ──────────────────────────────────────────────────── + + +class TestBackwardCompatibility: + """Bestehende Zähler llm_stay / llm_unavailable bleiben intakt.""" + + def test_llm_stay_still_incremented(self): + routing_counter.reset() + room_map = _make_room_map(non_catchall=5) + + 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_0")) + + counts = routing_counter.get_counts() + assert counts.get("llm_stay", 0) >= 1 + + def test_llm_unavailable_still_incremented(self): + routing_counter.reset() + room_map = _make_room_map(non_catchall=5) + + async def mock_llm_none(prompt: str) -> Optional[str]: + return None + + router = _make_router(room_map, mock_llm_none) + asyncio.run(router.route("Generische Frage", origin_room_id="room_0")) + + counts = routing_counter.get_counts() + assert counts.get("llm_unavailable", 0) >= 1 + + +# ── ::status zeigt die neuen Zähler ────────────────────────────────────────── + + +class TestStatusTextRoutingCounts: + """build_status_text zeigt die STAY/UNSICHER/TIMEOUT-Sektion.""" + + def test_status_shows_all_six_counters(self): + from plugin.archivar.inline_commands import build_status_text + + counts = { + "llm_stay_sicher": 10, + "llm_unsicher": 3, + "llm_timeout": 5, + "cloud_call_stay": 7, + "cloud_call_route": 1, + "no_llm_needed": 20, + } + text = build_status_text( + room_count=3, + archivar_active=True, + butler_mode="cognitive", + routing_counts=counts, + ) + + assert "Routing-Telemetrie" in text + assert "LLM STAY (sicher):** 10" in text + assert "LLM UNSICHER:** 3" in text + assert "LLM Timeout:** 5" in text + assert "Cloud-Call → STAY:** 7" in text + assert "Cloud-Call → ROUTE:** 1" in text + assert "Ohne LLM entschieden:** 20" in text + + def test_status_without_counts_omits_section(self): + from plugin.archivar.inline_commands import build_status_text + + text = build_status_text(room_count=3, archivar_active=True) + assert "Routing-Telemetrie" not in text