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:
@@ -0,0 +1,125 @@
|
||||
# Archivar Deployment-Runbook für .45 Bare-VM
|
||||
|
||||
## Voraussetzungen
|
||||
|
||||
- Ubuntu/Debian .45 Bare-VM
|
||||
- Python 3.10+
|
||||
- Rocket.Chat Server (selbst gehostet)
|
||||
- Ollama (lokal oder remote)
|
||||
|
||||
## 1. System-Abhängigkeiten
|
||||
|
||||
```bash
|
||||
sudo apt update
|
||||
sudo apt install -y python3 python3-pip python3-venv git curl
|
||||
```
|
||||
|
||||
## 2. Repository klonen
|
||||
|
||||
```bash
|
||||
cd /opt
|
||||
git clone https://github.com/your-org/Hermes_rocket.chat_Plugin.git
|
||||
cd Hermes_rocket.chat_Plugin
|
||||
```
|
||||
|
||||
## 3. Python-Umgebung
|
||||
|
||||
```bash
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
## 4. room-map.json Pfad-Korrektur
|
||||
|
||||
**KRITISCH:** Auf .45 Bare-VM liegt das Hermes-Datenverzeichnis unter
|
||||
`/var/lib/hermes-agent/data/`, NICHT unter `~/.hermes/hermes-agent/data/`.
|
||||
|
||||
```bash
|
||||
# Korrekten Pfad setzen
|
||||
export ARCHIVAR_ROOM_MAP_PATH="/var/lib/hermes-agent/data/room-map.json"
|
||||
export ARCHIVAR_STATE_PATH="/var/lib/hermes-agent/data/archivar_state.json"
|
||||
|
||||
# Verzeichnis anlegen falls nicht vorhanden
|
||||
mkdir -p /var/lib/hermes-agent/data/
|
||||
```
|
||||
|
||||
## 5. room-map.json erstellen
|
||||
|
||||
```bash
|
||||
cp room-map.schema.json /var/lib/hermes-agent/data/room-map.json
|
||||
# Bearbeite die Datei mit deinen Raum-IDs:
|
||||
nano /var/lib/hermes-agent/data/room-map.json
|
||||
```
|
||||
|
||||
## 6. Environment-Variablen
|
||||
|
||||
```bash
|
||||
# In /etc/hermes-agent/hermes.env oder systemd EnvironmentFile:
|
||||
|
||||
ROCKETCHAT_URL=https://chat.example.com
|
||||
ROCKETCHAT_USER=archivar-bot
|
||||
ROCKETCHAT_PASSWORD=your-password
|
||||
ROCKETCHAT_TOKEN=your-resume-token
|
||||
|
||||
ARCHIVAR_ROOM_MAP_PATH=/var/lib/hermes-agent/data/room-map.json
|
||||
ARCHIVAR_STATE_PATH=/var/lib/hermes-agent/data/archivar_state.json
|
||||
ARCHIVAR_EMBEDDING_BASE_URL=http://localhost:11434
|
||||
ARCHIVAR_LLM_BASE_URL=http://localhost:11434
|
||||
ARCHIVAR_ENABLE_LLM=true
|
||||
|
||||
# V8.2.1: Feature-Flags
|
||||
ARCHIVAR_STRATEGY_AUTO_DETECT=false # Default AUS (Rainer Auflage P1)
|
||||
|
||||
MULTIROOM_AGENT=true
|
||||
```
|
||||
|
||||
## 7. Ollama sicherstellen
|
||||
|
||||
```bash
|
||||
# Ollama installieren falls nicht vorhanden
|
||||
curl -fsSL https://ollama.com/install.sh | sh
|
||||
|
||||
# Modelle pullen
|
||||
ollama pull nomic-embed-text
|
||||
ollama pull qwen2.5:7b
|
||||
```
|
||||
|
||||
## 8. Gateway-Start
|
||||
|
||||
```bash
|
||||
cd /opt/Hermes_rocket.chat_Plugin
|
||||
source venv/bin/activate
|
||||
python3 -m gateway --platform rocketchat
|
||||
```
|
||||
|
||||
## 9. Verifikation
|
||||
|
||||
```bash
|
||||
# Kompilierung prüfen
|
||||
python3 -m py_compile plugin/adapter.py plugin/archivar/*.py
|
||||
|
||||
# Tests ausführen
|
||||
cd plugin && python3 -m pytest archivar/tests/ -q
|
||||
|
||||
# Gateway-Logs prüfen
|
||||
tail -f /var/log/hermes-agent/gateway.log | grep -E "Archivar|ROUTING|FAISS"
|
||||
```
|
||||
|
||||
## 10. Troubleshooting
|
||||
|
||||
### room-map.json nicht gefunden
|
||||
→ Prüfe `ARCHIVAR_ROOM_MAP_PATH` und ob die Datei existiert.
|
||||
→ Auf .45 Bare-VM: `/var/lib/hermes-agent/data/room-map.json`
|
||||
|
||||
### Ollama nicht erreichbar
|
||||
→ `curl http://localhost:11434/api/tags`
|
||||
→ Falls remote: `ARCHIVAR_EMBEDDING_BASE_URL` und `ARCHIVAR_LLM_BASE_URL` anpassen
|
||||
|
||||
### Gateway startet nicht
|
||||
→ `python3 -m py_compile plugin/adapter.py` — muss ohne Fehler durchlaufen
|
||||
→ Prüfe ob alle Env-Vars gesetzt sind
|
||||
|
||||
### Strategie-Modus funktioniert nicht
|
||||
→ `ARCHIVAR_STRATEGY_AUTO_DETECT=false` ist Default (manuelle Nachklärung)
|
||||
→ Auto-Detection erst aktivieren wenn manuelle Nachklärung stabil läuft
|
||||
+61
-3
@@ -1218,8 +1218,9 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
msg_obj.get("actions") and
|
||||
msg_obj.get("params", {}).get("triggerSender") and
|
||||
msg_obj.get("params", {}).get("payload"))
|
||||
or (text and "::" in text and not text.startswith("CLARIFY:") and text.split("::", 1)[0].strip() != "")
|
||||
or (text and "::" in text and not text.startswith("CLARIFY:") and not text.startswith("ARCHIVAR_CLARIFY:") and text.split("::", 1)[0].strip() != "")
|
||||
or (text and text.startswith("CLARIFY:"))
|
||||
or (text and text.startswith("ARCHIVAR_CLARIFY:"))
|
||||
)
|
||||
|
||||
# Check for CLARIFY button responses
|
||||
@@ -1315,6 +1316,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
# ── CLARIFY Response Handling ───────────────────────────────────
|
||||
# Handle CLARIFY button responses: CLARIFY:<clarify_id>:<choice> or CLARIFY:<clarify_id>:other
|
||||
# V8.2.1 A2: Handle ARCHIVAR_CLARIFY (Nachklärung) responses
|
||||
is_archivar_clarify = text.startswith("ARCHIVAR_CLARIFY:") if text else False
|
||||
if is_clarify_response and text.startswith("CLARIFY:"):
|
||||
routing_counter.increment('clarify_answer_bypass')
|
||||
logger.info("ROUTING BYPASS: reason=clarify_answer_bypass, origin_room=%s", room_id)
|
||||
@@ -1376,6 +1379,48 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] Error processing CLARIFY response: %s", e)
|
||||
|
||||
# ── V8.2.1 A2: ARCHIVAR_CLARIFY (Nachklärung) Response Handling ──
|
||||
if is_archivar_clarify:
|
||||
routing_counter.increment('archivar_clarify_bypass')
|
||||
logger.info("ROUTING BYPASS: reason=archivar_clarify_bypass, origin_room=%s", room_id)
|
||||
try:
|
||||
# Format: ARCHIVAR_CLARIFY:<choice>
|
||||
parts = text.split(":", 2)
|
||||
if len(parts) >= 2:
|
||||
choice = parts[1].strip()
|
||||
strategie_topics = {"absprache", "planung", "strategie", "entscheidung"}
|
||||
if choice in strategie_topics:
|
||||
# Strategie-Thema → Ring-Zustand 'jetzt' (30 Min), KEIN Lernen
|
||||
if _MULTIROOM() and self.archivar is not None:
|
||||
self.archivar._state.set_ring_state(room_id, "jetzt", ttl_minutes=30)
|
||||
logger.info(
|
||||
"[rocketchat] V8.2.1 A2: Strategie-Modus aktiviert — "
|
||||
"topic=%s, room=%s, ring=jetzt (30 Min)",
|
||||
choice, room_id[:8],
|
||||
)
|
||||
await self._post_message_with_retry(
|
||||
room_id,
|
||||
f"🎯 Verstanden — '{choice}' ist ein Strategie-Thema. "
|
||||
"Ich bleibe hier und lerne nichts dazu."
|
||||
)
|
||||
elif choice == "anderer_grund":
|
||||
# ANDERER GRUND → normales Lernen
|
||||
if _MULTIROOM() and self.archivar is not None:
|
||||
logger.info(
|
||||
"[rocketchat] V8.2.1 A2: ANDERER GRUND — "
|
||||
"normales Lernen in room %s",
|
||||
room_id[:8],
|
||||
)
|
||||
await self._post_message_with_retry(
|
||||
room_id,
|
||||
"👍 Alles klar — ich lerne daraus fürs nächste Mal."
|
||||
)
|
||||
else:
|
||||
logger.warning("[rocketchat] Unknown ARCHIVAR_CLARIFY choice: %s", choice)
|
||||
return # Nachricht verarbeitet — keine weitere Verarbeitung
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] Error processing ARCHIVAR_CLARIFY response: %s", e)
|
||||
|
||||
# Auto-Onboarding: Wenn onboarding_active, fange alle relevanten Antworten ab
|
||||
if _MULTIROOM() and self.archivar is not None and self.archivar._stats.get("onboarding_active", False):
|
||||
stripped = text.strip()
|
||||
@@ -1487,10 +1532,23 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
await self._post_message_with_retry(room_id, "🔒 Verstanden — dieser Raum wird nicht mehr automatisch geroutet. (Gilt dauerhaft)")
|
||||
feedback_type = "never"
|
||||
else:
|
||||
# 3️⃣ Hier bleiben → Antwort im Ursprungsraum (nur diesmal, kein Sticky)
|
||||
# Bug 4 fix: Track stay count — nach 3× stay in 10 Min → auto-promote zu never_route
|
||||
# 3️⃣ Nur diesmal → Antwort im Ursprungsraum (nur diesmal, kein Sticky)
|
||||
# V8.2.1 A2: Nach stay_once → Nachklärung mit Strategie-Buttons
|
||||
await self._post_message_with_retry(room_id, "👍 Bleiben hier — ich kümmere mich drum.")
|
||||
feedback_type = "stay"
|
||||
# V8.2.1 A2: Nachklärung bei stay_once — Strategie-Buttons senden
|
||||
if _MULTIROOM() and self.archivar is not None:
|
||||
if self.archivar._should_trigger_nachklaerung("stay_once"):
|
||||
nachklaerung_buttons = self.archivar._get_nachklaerung_buttons()
|
||||
await self._send_archivar_buttons(
|
||||
room_id,
|
||||
nachklaerung_buttons["text"],
|
||||
{"actions": nachklaerung_buttons["actions"]},
|
||||
)
|
||||
logger.info(
|
||||
"[rocketchat] V8.2.1 A2: Nachklärung gesendet — "
|
||||
"Strategie-Buttons in room %s", room_id[:8],
|
||||
)
|
||||
# Stay-Counter: Wenn der User 3× in 10 Min "Hier bleiben" klickt,
|
||||
# wird der Raum automatisch auf "never_route" gesetzt.
|
||||
# P1-3: stay_tracker ist jetzt persistent in ArchivarState
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user