feat: V8.5 — FAKT-Speicherort-Dialog beim Onboarding (4 Optionen, Pfad-Validierung, strategy-aware doc_store)

This commit is contained in:
Bernd (Hermes)
2026-07-18 23:30:13 +02:00
parent 463e29d594
commit f10973810a
7 changed files with 1089 additions and 43 deletions
@@ -0,0 +1,628 @@
"""
Tests für FAKT-Speicherort-Dialog beim Onboarding (Thema 3).
Prüft:
- room_map.py: fact_store_strategy, fact_store_created_at Felder + Migration
- onboarding.py: Pfad-Validierung, 4-Optionen-Dialog
- doc_store.py: set_base_dir()
- adapter_integration.py: strategy-aware Instanziierung
"""
from __future__ import annotations
import asyncio
import json
import os
import sys
import tempfile
from datetime import datetime
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from plugin.archivar.room_map import (
RoomMap,
RoomEntry,
RoomMapValidationError,
)
# ═══════════════════════════════════════════════════════════════════════════════
# Helpers
# ═══════════════════════════════════════════════════════════════════════════════
def _make_map_json(
rooms: list[dict] | None = None,
excluded: list[str] | None = None,
fact_store_path: str = "/tmp/test_docs",
fact_store_strategy: str | None = None,
fact_store_created_at: str | None = None,
) -> str:
"""Create a minimal valid room-map.json as a string."""
data: dict = {
"version": 1,
"rooms": {},
"excluded_rooms": excluded or [],
"fact_store_path": fact_store_path,
}
if fact_store_strategy is not None:
data["fact_store_strategy"] = fact_store_strategy
if fact_store_created_at is not None:
data["fact_store_created_at"] = fact_store_created_at
for room in (rooms or []):
room_data = {
"name": room["name"],
"theme": room.get("theme", ""),
"catch_all": room.get("catch_all", False),
}
if "keywords_100" in room or "keywords_context" in room:
room_data["keywords_100"] = room.get("keywords_100", [])
room_data["keywords_context"] = room.get("keywords_context", [])
else:
room_data["keywords"] = room.get("keywords", [])
data["rooms"][room["room_id"]] = room_data
return json.dumps(data)
def _tmp_map(content: str) -> Path:
tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False, encoding="utf-8")
tmp.write(content)
tmp.close()
return Path(tmp.name)
# ═══════════════════════════════════════════════════════════════════════════════
# RoomMap: fact_store_strategy + fact_store_created_at
# ═══════════════════════════════════════════════════════════════════════════════
class TestFactStoreFields:
"""RoomMap: fact_store_strategy und fact_store_created_at."""
def test_load_with_strategy_auto(self):
"""Map mit fact_store_strategy='auto' laden."""
json_str = _make_map_json(
rooms=[
{"room_id": "r1", "name": "#Dev", "theme": "dev", "keywords": []},
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
fact_store_strategy="auto",
fact_store_created_at="2026-07-18T12:00:00",
)
path = _tmp_map(json_str)
try:
rm = RoomMap.load(path)
assert rm.fact_store_strategy == "auto"
assert rm.fact_store_created_at == "2026-07-18T12:00:00"
finally:
path.unlink(missing_ok=True)
def test_load_with_strategy_manual(self):
"""Map mit fact_store_strategy='manual' laden."""
json_str = _make_map_json(
rooms=[
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
fact_store_strategy="manual",
)
path = _tmp_map(json_str)
try:
rm = RoomMap.load(path)
assert rm.fact_store_strategy == "manual"
finally:
path.unlink(missing_ok=True)
def test_load_with_strategy_none(self):
"""Map mit fact_store_strategy='none' laden."""
json_str = _make_map_json(
rooms=[
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
fact_store_strategy="none",
)
path = _tmp_map(json_str)
try:
rm = RoomMap.load(path)
assert rm.fact_store_strategy == "none"
finally:
path.unlink(missing_ok=True)
def test_migration_no_strategy_defaults_to_manual(self):
"""Bestehende Installation ohne strategy → 'manual' (Migration)."""
json_str = _make_map_json(
rooms=[
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
# KEIN fact_store_strategy gesetzt
)
path = _tmp_map(json_str)
try:
rm = RoomMap.load(path)
assert rm.fact_store_strategy == "manual", (
"Migration: Bestehende Installationen ohne strategy → 'manual'"
)
finally:
path.unlink(missing_ok=True)
def test_migration_no_created_at_defaults_to_none(self):
"""Bestehende Installation ohne created_at → None."""
json_str = _make_map_json(
rooms=[
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
)
path = _tmp_map(json_str)
try:
rm = RoomMap.load(path)
assert rm.fact_store_created_at is None
finally:
path.unlink(missing_ok=True)
def test_save_persists_strategy_and_created_at(self):
"""RoomMap.save() persistiert fact_store_strategy und fact_store_created_at."""
json_str = _make_map_json(
rooms=[
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
fact_store_strategy="auto",
fact_store_created_at="2026-07-18T12:00:00",
)
path = _tmp_map(json_str)
try:
rm = RoomMap.load(path)
# Ändere die Felder
rm.set_fact_store_strategy("manual")
rm.set_fact_store_created_at("2026-07-18T13:00:00")
# Speichere
RoomMap.save(rm, path)
# Lade neu und prüfe
rm2 = RoomMap.load(path)
assert rm2.fact_store_strategy == "manual"
assert rm2.fact_store_created_at == "2026-07-18T13:00:00"
finally:
path.unlink(missing_ok=True)
def test_set_fact_store_strategy_invalid_raises(self):
"""Ungültige strategy → ValueError."""
json_str = _make_map_json(
rooms=[
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
)
path = _tmp_map(json_str)
try:
rm = RoomMap.load(path)
with pytest.raises(ValueError, match="Invalid fact_store_strategy"):
rm.set_fact_store_strategy("invalid")
finally:
path.unlink(missing_ok=True)
def test_reload_preserves_strategy_fields(self):
"""reload() aktualisiert fact_store_strategy und fact_store_created_at."""
json_str = _make_map_json(
rooms=[
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
fact_store_strategy="auto",
fact_store_created_at="2026-07-18T12:00:00",
)
path = _tmp_map(json_str)
try:
rm = RoomMap.load(path)
# Ändere die Datei auf Disk
modified = json.loads(json_str)
modified["fact_store_strategy"] = "none"
modified["fact_store_created_at"] = "2026-07-18T14:00:00"
with open(path, "w") as f:
json.dump(modified, f)
rm.reload(path)
assert rm.fact_store_strategy == "none"
assert rm.fact_store_created_at == "2026-07-18T14:00:00"
finally:
path.unlink(missing_ok=True)
# ═══════════════════════════════════════════════════════════════════════════════
# Pfad-Validierung (onboarding.py)
# ═══════════════════════════════════════════════════════════════════════════════
class TestFactStorePathValidation:
"""Pfad-Validierung für den FAKT-Speicherort-Dialog."""
def test_validate_absolute_path_ok(self):
"""Absoluter Pfad ist gültig."""
from plugin.archivar.onboarding import validate_fact_store_path
result = validate_fact_store_path("/tmp/test_fakt_store")
assert result["valid"] is True
assert result["error"] is None
def test_validate_relative_path_fails(self):
"""Relativer Pfad wird abgelehnt."""
from plugin.archivar.onboarding import validate_fact_store_path
result = validate_fact_store_path("relative/path")
assert result["valid"] is False
assert "absolut" in result["error"].lower()
def test_validate_path_traversal_fails(self):
"""Path-Traversal mit '..' wird abgelehnt."""
from plugin.archivar.onboarding import validate_fact_store_path
result = validate_fact_store_path("/home/../etc/passwd")
assert result["valid"] is False
assert ".." in result["error"].lower() or "traversal" in result["error"].lower()
def test_validate_system_dir_blocked(self):
"""System-Verzeichnisse werden blockiert."""
from plugin.archivar.onboarding import validate_fact_store_path
for blocked in ["/etc/config", "/var/data", "/usr/local", "/boot/efi", "/sys/class", "/proc/cpuinfo"]:
result = validate_fact_store_path(blocked)
assert result["valid"] is False, f"Should block {blocked}"
assert "system" in result["error"].lower() or "blockiert" in result["error"].lower()
def test_validate_home_relative_normalized(self):
"""HOME-relativer Pfad wird normalisiert."""
from plugin.archivar.onboarding import validate_fact_store_path
result = validate_fact_store_path("~/.hermes/wissenssammlung")
assert result["valid"] is True
assert result["normalized_path"] is not None
assert result["normalized_path"].startswith("/")
assert "~" not in result["normalized_path"]
def test_validate_empty_path_fails(self):
"""Leerer Pfad wird abgelehnt."""
from plugin.archivar.onboarding import validate_fact_store_path
result = validate_fact_store_path("")
assert result["valid"] is False
def test_validate_path_with_spaces_ok(self):
"""Pfad mit Leerzeichen ist gültig (wird escaped)."""
from plugin.archivar.onboarding import validate_fact_store_path
result = validate_fact_store_path("/tmp/my fact store")
assert result["valid"] is True
# ═══════════════════════════════════════════════════════════════════════════════
# doc_store.py: set_base_dir()
# ═══════════════════════════════════════════════════════════════════════════════
class TestDocStoreSetBaseDir:
"""DocumentationStore.set_base_dir() Methode."""
def test_set_base_dir_changes_path(self):
"""set_base_dir() ändert das Basisverzeichnis."""
from plugin.archivar.doc_store import DocumentationStore
store = DocumentationStore(base_dir=Path("/tmp/old_docs"))
assert str(store.base_dir) == "/tmp/old_docs"
store.set_base_dir(Path("/tmp/new_docs"))
assert str(store.base_dir) == "/tmp/new_docs"
def test_set_base_dir_creates_directory(self):
"""set_base_dir() erstellt das Verzeichnis nicht (nur store() tut das)."""
from plugin.archivar.doc_store import DocumentationStore
with tempfile.TemporaryDirectory() as tmpdir:
new_dir = Path(tmpdir) / "subdir" / "docs"
store = DocumentationStore(base_dir=Path(tmpdir))
store.set_base_dir(new_dir)
# set_base_dir soll NUR den Pfad setzen, NICHT mkdir
assert str(store.base_dir) == str(new_dir)
# Verzeichnis existiert noch nicht (wird erst bei store() erstellt)
assert not new_dir.exists()
def test_store_uses_new_base_dir_after_set(self):
"""Nach set_base_dir() schreibt store() ins neue Verzeichnis."""
from plugin.archivar.doc_store import DocumentationStore
with tempfile.TemporaryDirectory() as tmpdir:
new_dir = Path(tmpdir) / "fakt_store"
store = DocumentationStore(base_dir=Path(tmpdir))
store.set_base_dir(new_dir)
path = store.store(
text="Test message",
category="FAKT",
confidence=0.95,
reason="test",
)
assert new_dir.name in path
assert Path(path).exists()
assert Path(path).parent.name == "fakt"
# ═══════════════════════════════════════════════════════════════════════════════
# adapter_integration.py: strategy-aware Instanziierung
# ═══════════════════════════════════════════════════════════════════════════════
class TestStrategyAwareDocStore:
"""ArchivarMessageHandler: strategy-aware DocumentationStore."""
def test_strategy_none_no_doc_store(self):
"""Bei strategy='none' wird kein DocumentationStore instanziiert."""
from plugin.archivar.adapter_integration import ArchivarMessageHandler
from unittest.mock import patch, MagicMock
# Erstelle eine RoomMap mit strategy='none'
json_str = _make_map_json(
rooms=[
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
fact_store_strategy="none",
)
path = _tmp_map(json_str)
try:
with patch('plugin.archivar.adapter_integration.ROOM_MAP_PATH', str(path)):
with patch('plugin.archivar.room_map.DEFAULT_MAP_PATH', str(path)):
handler = ArchivarMessageHandler()
# Bei strategy='none' sollte _doc_store None sein
assert handler._doc_store is None, (
"Bei strategy='none' soll kein DocumentationStore erstellt werden"
)
finally:
path.unlink(missing_ok=True)
def test_strategy_auto_creates_doc_store(self):
"""Bei strategy='auto' wird DocumentationStore erstellt."""
from plugin.archivar.adapter_integration import ArchivarMessageHandler
from unittest.mock import patch
json_str = _make_map_json(
rooms=[
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
fact_store_strategy="auto",
)
path = _tmp_map(json_str)
try:
with patch('plugin.archivar.adapter_integration.ROOM_MAP_PATH', str(path)):
with patch('plugin.archivar.room_map.DEFAULT_MAP_PATH', str(path)):
handler = ArchivarMessageHandler()
assert handler._doc_store is not None, (
"Bei strategy='auto' soll DocumentationStore erstellt werden"
)
finally:
path.unlink(missing_ok=True)
def test_strategy_manual_creates_doc_store(self):
"""Bei strategy='manual' wird DocumentationStore erstellt."""
from plugin.archivar.adapter_integration import ArchivarMessageHandler
from unittest.mock import patch
json_str = _make_map_json(
rooms=[
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
fact_store_strategy="manual",
)
path = _tmp_map(json_str)
try:
with patch('plugin.archivar.adapter_integration.ROOM_MAP_PATH', str(path)):
with patch('plugin.archivar.room_map.DEFAULT_MAP_PATH', str(path)):
handler = ArchivarMessageHandler()
assert handler._doc_store is not None, (
"Bei strategy='manual' soll DocumentationStore erstellt werden"
)
finally:
path.unlink(missing_ok=True)
def test_strategy_auto_mkdir_if_missing(self):
"""Bei strategy='auto' wird mkdir -p ausgeführt falls Pfad nicht existiert."""
from plugin.archivar.adapter_integration import ArchivarMessageHandler
from unittest.mock import patch
with tempfile.TemporaryDirectory() as tmpdir:
nonexistent = Path(tmpdir) / "nonexistent" / "fakt"
json_str = _make_map_json(
rooms=[
{"room_id": "admin", "name": "DM Admin", "theme": "admin", "keywords": [], "catch_all": True},
],
fact_store_path=str(nonexistent),
fact_store_strategy="auto",
)
path = _tmp_map(json_str)
try:
with patch('plugin.archivar.adapter_integration.ROOM_MAP_PATH', str(path)):
with patch('plugin.archivar.room_map.DEFAULT_MAP_PATH', str(path)):
handler = ArchivarMessageHandler()
# Bei strategy='auto' soll das Verzeichnis erstellt worden sein
assert nonexistent.exists(), (
"Bei strategy='auto' soll mkdir -p ausgeführt werden"
)
finally:
path.unlink(missing_ok=True)
# ═══════════════════════════════════════════════════════════════════════════════
# Adapter-Level: FAKT-Speicherort-Buttons im is_onboarding-Check (P0-Fix)
# ═══════════════════════════════════════════════════════════════════════════════
class TestFaktStoreOnboardingAdapter:
"""Adapter-Level: FAKT-Speicherort-Buttons werden als Onboarding erkannt.
P0-Bug: Der is_onboarding-Check in _process_incoming (Zeile 1516-1527)
hatte keine Bedingung für die fakt_store-Phase. FAKT-Buttons (FAKT::1️⃣ etc.)
fielen durch und wurden nicht als Onboarding-Antwort verarbeitet.
Fix: Zeile 1522 — ``or (is_operator_room and self._onboarding_state.get("phase") == "fakt_store")``
"""
@pytest.fixture
def adapter(self, tmp_path):
"""Build a mock RocketChatAdapter with fakt_store onboarding state."""
import asyncio
import threading
from unittest.mock import AsyncMock, MagicMock
os.environ["MULTIROOM_AGENT"] = "true"
os.environ["ARCHIVAR_STATE_PATH"] = str(tmp_path / "archivar_state.json")
os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com"
os.environ["ROCKETCHAT_USER"] = "testbot"
os.environ["ROCKETCHAT_PASSWORD"] = "testpass"
# Create a minimal room-map.json
map_path = tmp_path / "room-map.json"
map_data = {
"version": 1,
"rooms": {
"admin": {
"name": "DM Admin",
"theme": "admin",
"keywords": [],
"catch_all": True,
},
},
"excluded_rooms": [],
"fact_store_path": str(tmp_path / "docs"),
}
map_path.write_text(json.dumps(map_data))
os.environ["ARCHIVAR_ROOM_MAP_PATH"] = str(map_path)
from plugin.adapter import RocketChatAdapter, RocketChatREST
from archivar.conversation_history import ConversationHistory
from archivar.multiroom_context import MultiRoomContextRing
from archivar.adapter_integration import ArchivarMessageHandler
from archivar.room_map import RoomMap
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
adapter.config = MagicMock()
adapter.config.extra = {}
adapter.platform = "rocketchat"
adapter.base_url = os.getenv("ROCKETCHAT_BASE_URL", "")
adapter.user = os.getenv("ROCKETCHAT_USER", "")
adapter.password = os.getenv("ROCKETCHAT_PASSWORD", "")
adapter.rest = RocketChatREST(adapter.base_url)
adapter.ddp = None
adapter._auth_token = None
adapter._user_id = None
adapter._rooms = []
adapter._subscribed_rooms = set()
adapter._listen_task = None
adapter._status_timer = None
adapter._last_activity = 0.0
adapter._shutdown_event = threading.Event()
adapter._room_info = {}
adapter._pending_clarifies = {}
adapter._user_rooms = {}
adapter._rooms_with_pending_questions = set()
adapter._excluded_room_ids = set()
adapter._last_server_activity = 0.0
adapter._health_check_timer = None
adapter._last_ddp_ping_ok = False
adapter._running = False
adapter._conversation_history = ConversationHistory(max_size=10)
adapter._multiroom_context = MultiRoomContextRing(max_entries=10)
adapter.archivar = ArchivarMessageHandler(
send_callback=lambda *a, **kw: None,
button_send_callback=lambda *a, **kw: None,
conversation_history=adapter._conversation_history,
)
adapter.archivar._room_map = RoomMap.load(Path(str(map_path)))
adapter._pending_move_requests = {}
adapter._session_room_preferences = {}
adapter._recent_auto_routes = {}
adapter._explicit_switch_sticky = {}
adapter._clarify_state = {}
adapter._onboarding_state = {}
adapter._room_map_summary = ""
mock_rest = MagicMock(spec=RocketChatREST)
mock_rest.auth_token = "fake-token"
mock_rest.user_id = "fake-user-id"
mock_rest.post_message = MagicMock(return_value="msg_12345")
mock_rest.get_rooms = MagicMock(return_value=[
{"id": "dm_room", "name": "DM Admin", "type": "d"},
])
adapter.rest = mock_rest
# Mock _process_onboarding_response to track calls
adapter._process_onboarding_response = AsyncMock()
adapter._post_message_with_retry = AsyncMock(return_value=True)
# Set onboarding_active in archivar stats
adapter.archivar._stats["onboarding_active"] = True
return adapter
def test_fakt_button_standard_recognized_as_onboarding(self, adapter):
"""FAKT::1️⃣ Standard im Operator-Room → is_onboarding=True → _process_onboarding_response aufgerufen."""
adapter._onboarding_state = {
"phase": "fakt_store",
"operator_room_id": "dm_room",
}
msg_obj = {
"msg": "FAKT::1️⃣ Standard",
"rid": "dm_room",
"u": {"username": "bernd"},
"_id": "msg_001",
}
asyncio.run(adapter._process_incoming(msg_obj))
adapter._process_onboarding_response.assert_called_once()
call_args = adapter._process_onboarding_response.call_args
assert call_args[0][0] == "FAKT::1️⃣ Standard"
assert call_args[0][1] == "dm_room"
def test_fakt_button_new_path_recognized_as_onboarding(self, adapter):
"""FAKT::2️⃣ Neuer Ort im Operator-Room → is_onboarding=True."""
adapter._onboarding_state = {
"phase": "fakt_store",
"operator_room_id": "dm_room",
}
msg_obj = {
"msg": "FAKT::2️⃣ Neuer Ort",
"rid": "dm_room",
"u": {"username": "bernd"},
"_id": "msg_002",
}
asyncio.run(adapter._process_incoming(msg_obj))
adapter._process_onboarding_response.assert_called_once()
call_args = adapter._process_onboarding_response.call_args
assert call_args[0][0] == "FAKT::2️⃣ Neuer Ort"
def test_fakt_button_none_recognized_as_onboarding(self, adapter):
"""FAKT::4️⃣ Keine Sammlung im Operator-Room → is_onboarding=True."""
adapter._onboarding_state = {
"phase": "fakt_store",
"operator_room_id": "dm_room",
}
msg_obj = {
"msg": "FAKT::4️⃣ Keine Sammlung",
"rid": "dm_room",
"u": {"username": "bernd"},
"_id": "msg_003",
}
asyncio.run(adapter._process_incoming(msg_obj))
adapter._process_onboarding_response.assert_called_once()
call_args = adapter._process_onboarding_response.call_args
assert call_args[0][0] == "FAKT::4️⃣ Keine Sammlung"
def test_fakt_button_wrong_room_not_onboarding(self, adapter):
"""FAKT-Button in falschem Raum → is_onboarding=False → _process_onboarding_response NICHT aufgerufen."""
adapter._onboarding_state = {
"phase": "fakt_store",
"operator_room_id": "dm_room",
}
# Nachricht kommt aus einem anderen Raum (#general)
msg_obj = {
"msg": "FAKT::1️⃣ Standard",
"rid": "general_room",
"u": {"username": "bernd"},
"_id": "msg_004",
}
asyncio.run(adapter._process_incoming(msg_obj))
adapter._process_onboarding_response.assert_not_called()