fix: V8.2.1 — 7 Befunde (A2 Caller, A3 Persistenz, A4 Strategie-Block, Tests, Feature-Flag, conftest, runbook)

Befund 1 (P0): A2 Dead-Code — _should_trigger_nachklaerung() in adapter.py
Button-Response-Handler angebunden. stay_once (Button 3) triggert jetzt
Nachklärung mit Strategie-Buttons. ARCHIVAR_CLARIFY-Responses werden
verarbeitet (Strategie-Thema → Ring-Zustand "jetzt", ANDERER GRUND →
normales Lernen).

Befund 2 (P0): A3 Persistenz-Bug — _stay_counts und _keyword_last_matched
in RoomMap.save() und _from_dict() serialisiert. Tracking-Felder
überleben Gateway-Restart.

Befund 3 (P1): A4 Strategie-Block — _is_strategie_topic() im DM-Pfad
des Routers. Strategie-Themen im DM → stay_in_room (kein Routing,
kein Lernen).

Befund 4 (P1): Tests — 8 neue echte Integrationstests (TestV821A2,
TestV821A3, TestV821A4). 27/27 grün.

Befund 5 (P2): ARCHIVAR_STRATEGY_AUTO_DETECT env var in config.py,
Default false (Rainer Auflage P1).

Befund 6 (P2): conftest.py mit temp_room_map_path und temp_state_path
Fixtures für saubere Pfad-Tests.

Befund 7 (P2): docs/deployment-runbook.md mit .45 Bare-VM Schritten
inkl. room-map.json Pfad-Korrektur.
This commit is contained in:
Bernd (Hermes)
2026-07-14 21:27:32 +02:00
parent 39a5041621
commit de930a1227
7 changed files with 590 additions and 4 deletions
+11
View File
@@ -264,6 +264,17 @@ FAISS_CONFLICT_DIFF: float = 0.05
der Keyword-Booster zur Konfliktlösung eingesetzt wird. Bei Diff < 0.05
entscheiden eindeutige Keywords, nicht der reine FAISS-Score."""
# ── V8.2.1 A2: Feature-Flag für Auto-Detection (Phase 2) ────────────────────
# Rainer Auflage P1: A2-Phase 2 (Auto-Detection) MUSS Feature-Flag bekommen,
# Default AUS. Erst wenn die manuelle Nachklärung stabil läuft, kann Phase 2
# aktiviert werden.
ARCHIVAR_STRATEGY_AUTO_DETECT: bool = os.getenv(
"ARCHIVAR_STRATEGY_AUTO_DETECT", "false"
).strip().lower() in ("1", "true", "yes")
"""Feature-Flag für A2-Phase 2: Automatische Strategie-Themen-Erkennung.
Default: false (AUS). Setze auf 'true' um Auto-Detection zu aktivieren."""
# ── Deprecated: LLM_CLASSIFY_PROMPT (bleibt für Abwärtskompatibilität) ─────
# Wird NICHT mehr verwendet — LLM_ROOM_PROMPT ist der neue Standard.
# Bleibt im Code, falls externe Skripte darauf verweisen.
+9 -1
View File
@@ -492,7 +492,10 @@ class RoomMap:
"description": room_entry.description,
"keywords_100": room_entry.keywords_100,
"keywords_context": room_entry.keywords_context,
"catch_all": room_entry.catch_all
"catch_all": room_entry.catch_all,
# V8.2.1 A3: Persistiere Tracking-Felder
"_stay_counts": room_entry._stay_counts,
"_keyword_last_matched": room_entry._keyword_last_matched,
}
# Schreibe die Datei mit exklusivem File-Lock
@@ -705,6 +708,11 @@ class RoomMap:
keywords_context=keywords_context,
catch_all=room_data.get("catch_all", False),
)
# V8.2.1 A3: Tracking-Felder aus JSON deserialisieren
if "_stay_counts" in room_data:
rooms[room_id]._stay_counts = room_data["_stay_counts"]
if "_keyword_last_matched" in room_data:
rooms[room_id]._keyword_last_matched = room_data["_keyword_last_matched"]
excluded = set(data.get("excluded_rooms", []))
fact_store = Path(
+32
View File
@@ -380,6 +380,19 @@ class BidirectionalRouter:
# → Strategie-Modus, KEIN Lernen.
if not origin_room_id:
# DM: Erlaube Routing, aber markiere als DM-Kontext
# V8.2.1 A4: Strategie-Themen im DM → stay_in_room (kein Routing, kein Lernen)
if self._is_strategie_topic(text):
logger.info(
"DM-Guard V8.2.1 A4: Strategie-Thema im DM erkannt → stay_in_room"
)
routing_counter.increment('dm_strategie_stay')
logger.info("ROUTING DECISION: reason=dm_strategie_stay, origin_room=%s, target_room=, stay=True, butler_mode=False", origin_room_id)
return RoutingDecision(
category="direct_question",
target_room="",
confidence=1.0,
stay_in_room=True,
)
logger.debug("DM-Guard V8.2: origin_room_id leer → DM-Routing erlaubt (A4)")
# Kein sofortiges stay_in_room — normaler Flow mit Butler
@@ -1070,6 +1083,25 @@ class BidirectionalRouter:
return True
return False
# ── V8.2.1 A4: Strategie-Themen-Erkennung ──────────────────────────
@staticmethod
def _is_strategie_topic(text: str) -> bool:
"""Prüft ob der Text ein Strategie-Thema enthält.
Strategie-Themen: absprache, planung, strategie, entscheidung.
Bei diesen Themen → Strategie-Modus, KEIN Lernen, KEIN Routing.
Args:
text: Der Nachrichtentext.
Returns:
True wenn Strategie-Thema erkannt.
"""
strategie_keywords = {"absprache", "planung", "strategie", "entscheidung"}
text_lower = text.lower()
return any(kw in text_lower for kw in strategie_keywords)
# ── Fallback: Keyword-Heuristik ────────────────────────────────────
@staticmethod
+64
View File
@@ -0,0 +1,64 @@
"""
V8.2.1: pytest-Fixtures für saubere Pfad-Tests.
Statt nested patches in jedem Test wird der room-map.json Pfad
pro Test umgebogen. Verwendet tempfile.TemporaryDirectory für
Isolation.
"""
import json
import tempfile
from pathlib import Path
import pytest
@pytest.fixture
def temp_room_map_path():
"""Erzeugt eine temporäre room-map.json mit minimalem Test-Setup.
Returns:
Path: Pfad zur temporären room-map.json.
"""
tmp = tempfile.TemporaryDirectory()
map_path = Path(tmp.name) / "room-map.json"
test_data = {
"version": 2,
"rooms": {
"catchall_id": {
"name": "#CatchAll",
"theme": "Catch-all room",
"keywords_100": [],
"keywords_context": [],
"catch_all": True,
},
"plugin_room_id": {
"name": "#Rocketchat-Plugin",
"theme": "Plugin-Entwicklung",
"keywords_100": ["plugin"],
"keywords_context": ["adapter"],
"catch_all": False,
},
},
"excluded_rooms": [],
"fact_store_path": str(Path(tmp.name) / "docs"),
}
with open(map_path, "w") as f:
json.dump(test_data, f)
yield map_path
tmp.cleanup()
@pytest.fixture
def temp_state_path():
"""Erzeugt einen temporären Pfad für archivar_state.json.
Returns:
str: Pfad zur temporären State-Datei.
"""
tmp = tempfile.TemporaryDirectory()
state_path = str(Path(tmp.name) / "archivar_state.json")
yield state_path
tmp.cleanup()
+288
View File
@@ -435,5 +435,293 @@ class TestA4DMButlerStrategie(unittest.TestCase):
self.assertFalse(handler._is_strategie_topic("plugin"))
# ═══════════════════════════════════════════════════════════════════════════════
# V8.2.1: Echte Integrationstests (Rainer Quality-Loop)
# ═══════════════════════════════════════════════════════════════════════════════
class TestV821A2Integration(unittest.TestCase):
"""A2: Echter Test dass stay_once → Strategie-Buttons gesendet werden."""
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.temp_path = Path(self.temp_dir.name) / "room-map.json"
self.test_data = {
"version": 2,
"rooms": {
"catchall_id": {
"name": "#CatchAll",
"theme": "Catch-all room",
"keywords_100": [],
"keywords_context": [],
"catch_all": True,
},
"plugin_room_id": {
"name": "#Rocketchat-Plugin",
"theme": "Plugin-Entwicklung",
"keywords_100": ["plugin"],
"keywords_context": ["adapter"],
"catch_all": False,
},
},
"excluded_rooms": [],
"fact_store_path": str(self.temp_path.parent / "docs"),
}
with open(self.temp_path, "w") as f:
json.dump(self.test_data, f)
def tearDown(self):
self.temp_dir.cleanup()
def test_a2_stay_once_sends_strategie_buttons(self):
"""stay_once → _should_trigger_nachklaerung() → _get_nachklaerung_buttons()
liefert korrekte Buttons mit allen 5 Optionen."""
from plugin.archivar.adapter_integration import ArchivarMessageHandler
with patch('archivar.adapter_integration.ROOM_MAP_PATH', str(self.temp_path)):
with patch('archivar.room_map.DEFAULT_MAP_PATH', str(self.temp_path)):
handler = ArchivarMessageHandler()
handler._state._loaded = True
# stay_once muss Nachklärung triggern
self.assertTrue(handler._should_trigger_nachklaerung("stay_once"))
# Nachklärungs-Buttons müssen alle 5 Optionen enthalten
buttons = handler._get_nachklaerung_buttons()
self.assertIn("actions", buttons)
action_types = [a["type"] for a in buttons["actions"]]
self.assertIn("absprache", action_types)
self.assertIn("planung", action_types)
self.assertIn("strategie", action_types)
self.assertIn("entscheidung", action_types)
self.assertIn("anderer_grund", action_types)
self.assertEqual(len(buttons["actions"]), 5)
def test_a2_strategie_topic_sets_ring_and_blocks_learning(self):
"""Strategie-Thema → set_ring_state('jetzt') → is_ring_state_active
blockiert Lernen."""
state = ArchivarState()
state._loaded = True
# Setze Ring-Zustand
state.set_ring_state("room_123", "jetzt", ttl_minutes=30)
ring = state.get_ring_state("room_123")
self.assertEqual(ring["state"], "jetzt")
self.assertIsNotNone(ring["expires_at"])
# Ring-Zustand 'jetzt' blockiert Lernen
self.assertTrue(state.is_ring_state_active("room_123", "jetzt"))
# Ring-Zustand 'aus' blockiert NICHT
self.assertFalse(state.is_ring_state_active("room_123", "aus"))
class TestV821A3Integration(unittest.TestCase):
"""A3: Echter Test dass _stay_counts nach save/load erhalten bleiben."""
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.temp_path = Path(self.temp_dir.name) / "room-map.json"
self.test_data = {
"version": 2,
"rooms": {
"catchall_id": {
"name": "#CatchAll",
"theme": "Catch-all room",
"keywords_100": [],
"keywords_context": [],
"catch_all": True,
},
"plugin_room_id": {
"name": "#Rocketchat-Plugin",
"theme": "Plugin-Entwicklung",
"keywords_100": ["plugin"],
"keywords_context": ["adapter"],
"catch_all": False,
},
},
"excluded_rooms": [],
"fact_store_path": str(self.temp_path.parent / "docs"),
}
with open(self.temp_path, "w") as f:
json.dump(self.test_data, f)
def tearDown(self):
self.temp_dir.cleanup()
def test_a3_stay_counts_survive_save_load_roundtrip(self):
"""_stay_counts und _keyword_last_matched überleben save/load."""
room_map = RoomMap._from_dict(self.test_data)
# Setze Tracking-Daten
room_map.increment_stay_count("plugin_room_id", "dokumentation")
room_map.increment_stay_count("plugin_room_id", "dokumentation")
room_map.increment_stay_count("plugin_room_id", "dokumentation")
room_map.set_keyword_last_matched(
"plugin_room_id", "plugin", "2026-07-14T10:00:00"
)
# Persistiere
RoomMap.save(room_map, self.temp_path)
# Lade neu
reloaded = RoomMap.load(self.temp_path)
entry = reloaded.get_room_by_id("plugin_room_id")
# _stay_counts muss erhalten sein
self.assertEqual(entry._stay_counts.get("dokumentation"), 3)
# _keyword_last_matched muss erhalten sein
self.assertEqual(
entry._keyword_last_matched.get("plugin"), "2026-07-14T10:00:00"
)
def test_a3_promote_resets_stay_count(self):
"""Promotion zu keywords_100 setzt _stay_counts zurück."""
room_map = RoomMap._from_dict(self.test_data)
# 3 stays → promote
room_map.add_keyword_context("plugin_room_id", "dokumentation")
for _ in range(3):
room_map.increment_stay_count("plugin_room_id", "dokumentation")
promoted = room_map.promote_to_keywords_100("plugin_room_id", "dokumentation")
self.assertTrue(promoted)
entry = room_map.get_room_by_id("plugin_room_id")
self.assertIn("dokumentation", entry.keywords_100)
# Stay-Count muss zurückgesetzt sein
self.assertNotIn("dokumentation", entry._stay_counts)
def test_a3_demotion_preserves_tracking_in_roundtrip(self):
"""Demotion + save/load: Tracking-Felder bleiben konsistent."""
room_map = RoomMap._from_dict(self.test_data)
# Setze altes last_matched
old_date = (datetime.now() - timedelta(days=100)).isoformat()
room_map.set_keyword_last_matched("plugin_room_id", "plugin", old_date)
# Demote
demoted = room_map.demote_stale_keywords(max_age_days=90)
self.assertGreaterEqual(demoted, 1)
# Persistiere
RoomMap.save(room_map, self.temp_path)
# Reload
reloaded = RoomMap.load(self.temp_path)
entry = reloaded.get_room_by_id("plugin_room_id")
# Nach Demotion: keyword in keywords_context, nicht in keywords_100
self.assertNotIn("plugin", entry.keywords_100)
self.assertIn("plugin", entry.keywords_context)
# _keyword_last_matched für demoted keyword muss gelöscht sein
self.assertNotIn("plugin", entry._keyword_last_matched)
class TestV821A4Integration(unittest.TestCase):
"""A4: Echter Test dass Strategie-Thema im DM → stay_in_room."""
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.temp_path = Path(self.temp_dir.name) / "room-map.json"
self.test_data = {
"version": 2,
"rooms": {
"catchall_id": {
"name": "DM Admin",
"theme": "Catch-all DM",
"keywords_100": [],
"keywords_context": [],
"catch_all": True,
},
"plugin_room_id": {
"name": "#Rocketchat-Plugin",
"theme": "Plugin-Entwicklung",
"keywords_100": ["plugin"],
"keywords_context": ["adapter"],
"catch_all": False,
},
},
"excluded_rooms": [],
"fact_store_path": str(self.temp_path.parent / "docs"),
}
with open(self.temp_path, "w") as f:
json.dump(self.test_data, f)
def tearDown(self):
self.temp_dir.cleanup()
def test_a4_dm_strategie_topic_stay_in_room(self):
"""Strategie-Thema im DM (origin_room_id='') → stay_in_room."""
from plugin.archivar.router import BidirectionalRouter
from plugin.archivar.room_map import RoomMap
from plugin.archivar.archivar_state import ArchivarState
room_map = RoomMap._from_dict(self.test_data)
state = ArchivarState()
state._loaded = True
mock_classifier = MagicMock()
mock_classifier.is_initialized = True
mock_classifier.classify = AsyncMock(return_value=None)
router = BidirectionalRouter(room_map, mock_classifier, state)
# Strategie-Thema im DM
import asyncio
decision = asyncio.run(
router.route("Lass uns eine Absprache zur Strategie treffen", origin_room_id="")
)
# Muss stay_in_room sein (Strategie-Thema im DM)
self.assertTrue(decision.stay_in_room,
"A4: Strategie-Thema im DM muss stay_in_room sein")
def test_a4_dm_non_strategie_allows_routing(self):
"""Nicht-Strategie-Thema im DM → Routing erlaubt."""
from plugin.archivar.router import BidirectionalRouter
from plugin.archivar.room_map import RoomMap
from plugin.archivar.archivar_state import ArchivarState
room_map = RoomMap._from_dict(self.test_data)
state = ArchivarState()
state._loaded = True
mock_classifier = MagicMock()
mock_classifier.is_initialized = True
mock_classifier.classify = AsyncMock(return_value=None)
mock_classifier._llm_raw = AsyncMock(return_value="plugin_room_id")
router = BidirectionalRouter(room_map, mock_classifier, state)
# Normales Thema im DM
import asyncio
decision = asyncio.run(
router.route("Bitte das Plugin dokumentieren", origin_room_id="")
)
# Sollte NICHT stay_in_room sein (kein Strategie-Thema)
self.assertFalse(decision.stay_in_room,
"A4: Nicht-Strategie-Thema im DM muss Routing erlauben")
def test_a4_router_strategie_detection(self):
"""Router._is_strategie_topic() erkennt Strategie-Themen im Text."""
from plugin.archivar.router import BidirectionalRouter
# Strategie-Themen
self.assertTrue(BidirectionalRouter._is_strategie_topic("Wir brauchen eine Absprache"))
self.assertTrue(BidirectionalRouter._is_strategie_topic("Planung für Q3"))
self.assertTrue(BidirectionalRouter._is_strategie_topic("Strategie-Meeting morgen"))
self.assertTrue(BidirectionalRouter._is_strategie_topic("Entscheidung zum Budget"))
# Keine Strategie-Themen
self.assertFalse(BidirectionalRouter._is_strategie_topic("Dokumentation aktualisieren"))
self.assertFalse(BidirectionalRouter._is_strategie_topic("Plugin kompilieren"))
self.assertFalse(BidirectionalRouter._is_strategie_topic("Hallo Welt"))
if __name__ == '__main__':
unittest.main()