feat: V8.5 — FAKT-Speicherort-Dialog beim Onboarding (4 Optionen, Pfad-Validierung, strategy-aware doc_store)
This commit is contained in:
+227
-10
@@ -1519,6 +1519,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
or (is_operator_room and self._onboarding_state.get("current_room_index", -1) >= 0) # v2 Interview läuft
|
or (is_operator_room and self._onboarding_state.get("current_room_index", -1) >= 0) # v2 Interview läuft
|
||||||
or (is_operator_room and self._onboarding_state.get("phase") == "butler_mode") # Fix C v7: Butler-Mode Phase
|
or (is_operator_room and self._onboarding_state.get("phase") == "butler_mode") # Fix C v7: Butler-Mode Phase
|
||||||
or (is_operator_room and self._onboarding_state.get("phase") == "catch_all_change") # Catch-All Phase
|
or (is_operator_room and self._onboarding_state.get("phase") == "catch_all_change") # Catch-All Phase
|
||||||
|
or (is_operator_room and self._onboarding_state.get("phase") == "fakt_store") # Thema 3: FAKT-Speicherort Phase
|
||||||
or (is_operator_room and "=" in stripped) # v1 Legacy: Name = Thema
|
or (is_operator_room and "=" in stripped) # v1 Legacy: Name = Thema
|
||||||
or (is_operator_room and stripped.startswith("#")) # v1 Legacy: #Name = Thema
|
or (is_operator_room and stripped.startswith("#")) # v1 Legacy: #Name = Thema
|
||||||
or (is_operator_room and stripped.lower().startswith("raum:")) # v1 Legacy: Raum: Name = Thema
|
or (is_operator_room and stripped.lower().startswith("raum:")) # v1 Legacy: Raum: Name = Thema
|
||||||
@@ -2942,17 +2943,220 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
)
|
)
|
||||||
logger.info("[rocketchat] Fix C v7: Butler-Mode gesetzt auf '%s' (Text)", mode)
|
logger.info("[rocketchat] Fix C v7: Butler-Mode gesetzt auf '%s' (Text)", mode)
|
||||||
|
|
||||||
# Onboarding abschließen
|
# Thema 3: FAKT-Speicherort-Dialog statt direktem Abschluss
|
||||||
|
self._onboarding_state = {
|
||||||
|
"phase": "fakt_store",
|
||||||
|
"operator_room_id": operator_room_id,
|
||||||
|
}
|
||||||
if self.archivar is not None:
|
if self.archivar is not None:
|
||||||
self.archivar._stats["onboarding_active"] = False
|
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||||||
self.archivar._state.clear_onboarding_state()
|
|
||||||
self._onboarding_state = {}
|
# FAKT-Speicherort-Frage senden
|
||||||
# FIX E: Raum-Map Summary nach Onboarding aktualisieren
|
_build = self._get_build_custom_buttons()
|
||||||
self._room_map_summary = self._build_room_map_summary()
|
fakt_text = (
|
||||||
if self._room_map_summary:
|
"📁 **FAKT-Speicherort** — Wo soll ich Fakten (deine Notizen) ablegen?\n\n"
|
||||||
logger.info("[rocketchat] FIX E: Raum-Map Summary nach Onboarding aktualisiert (%d Räume)",
|
"1️⃣ **Standard** — `.hermes/wissenssammlung` in deinem Home-Verzeichnis\n"
|
||||||
len(self._room_map_summary.splitlines()) - 1)
|
"2️⃣ **Neuer Ort** — Du gibst einen Pfad an, ich lege das Verzeichnis an\n"
|
||||||
logger.info("[rocketchat] Onboarding v2 vollständig abgeschlossen (mit Butler-Mode)")
|
"3️⃣ **Bestehender Ort** — Du gibst einen Pfad an, ich verweise darauf\n"
|
||||||
|
"4️⃣ **Keine Sammlung** — FAKT-Nachrichten werden nicht persistiert\n\n"
|
||||||
|
"👉 Klicke auf einen Button oder antworte mit 1–4:"
|
||||||
|
)
|
||||||
|
fakt_buttons = _build(
|
||||||
|
["1️⃣ Standard", "2️⃣ Neuer Ort", "3️⃣ Bestehender Ort", "4️⃣ Keine Sammlung"],
|
||||||
|
prefix="FAKT",
|
||||||
|
style="primary",
|
||||||
|
)
|
||||||
|
fakt_attachments = [{
|
||||||
|
"color": "#1d74f5",
|
||||||
|
"title": "FAKT-Speicherort wählen",
|
||||||
|
"actions": fakt_buttons,
|
||||||
|
}]
|
||||||
|
await self._post_message_with_retry(
|
||||||
|
operator_room_id, fakt_text, attachments=fakt_attachments
|
||||||
|
)
|
||||||
|
logger.info("[rocketchat] Thema 3: FAKT-Speicherort-Frage gesendet")
|
||||||
|
return
|
||||||
|
|
||||||
|
# ── Thema 3: FAKT-Speicherort-Dialog ─────────────────────────────
|
||||||
|
if state.get("phase") == "fakt_store":
|
||||||
|
single_line = text.strip()
|
||||||
|
fakt_sub_phase = state.get("fakt_sub_phase", "")
|
||||||
|
|
||||||
|
# Sub-Phase: User gibt Pfad ein (für Option 2 oder 3)
|
||||||
|
if fakt_sub_phase in ("new_path", "existing_path"):
|
||||||
|
from plugin.archivar.onboarding import (
|
||||||
|
validate_fact_store_path,
|
||||||
|
create_and_verify_fact_store,
|
||||||
|
verify_existing_fact_store,
|
||||||
|
)
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
validation = validate_fact_store_path(single_line)
|
||||||
|
if not validation["valid"]:
|
||||||
|
await self._post_message_with_retry(
|
||||||
|
operator_room_id,
|
||||||
|
f"❌ {validation['error']}\n\nBitte gib einen gültigen absoluten Pfad ein:"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
norm_path = validation["normalized_path"]
|
||||||
|
|
||||||
|
if fakt_sub_phase == "new_path":
|
||||||
|
result = create_and_verify_fact_store(norm_path)
|
||||||
|
else:
|
||||||
|
result = verify_existing_fact_store(norm_path)
|
||||||
|
|
||||||
|
if not result["success"]:
|
||||||
|
await self._post_message_with_retry(
|
||||||
|
operator_room_id,
|
||||||
|
f"❌ {result['error']}\n\nBitte versuche einen anderen Pfad:"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Erfolg: Persistiere in room-map.json
|
||||||
|
strategy = "manual"
|
||||||
|
now_iso = datetime.now(timezone.utc).isoformat()
|
||||||
|
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||||||
|
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||||||
|
from archivar.room_map import RoomMap
|
||||||
|
from archivar.config import ROOM_MAP_PATH
|
||||||
|
from pathlib import Path as PathLib
|
||||||
|
RoomMap.save(self.archivar._room_map, PathLib(ROOM_MAP_PATH))
|
||||||
|
self.archivar._room_map.reload()
|
||||||
|
|
||||||
|
# Aktualisiere doc_store mit neuem Pfad
|
||||||
|
if self.archivar._doc_store is not None:
|
||||||
|
self.archivar._doc_store.set_base_dir(PathLib(norm_path))
|
||||||
|
else:
|
||||||
|
from plugin.archivar.doc_store import DocumentationStore
|
||||||
|
self.archivar._doc_store = DocumentationStore(base_dir=PathLib(norm_path))
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] FAKT-Store: strategy='manual', path=%s, created_at=%s",
|
||||||
|
norm_path, now_iso,
|
||||||
|
)
|
||||||
|
await self._post_message_with_retry(
|
||||||
|
operator_room_id,
|
||||||
|
f"✅ FAKT-Speicherort: `{norm_path}`\n"
|
||||||
|
f"Strategie: {'Neues Verzeichnis angelegt' if fakt_sub_phase == 'new_path' else 'Bestehendes Verzeichnis referenziert'}\n"
|
||||||
|
f"Änderbar mit `::setfakt`."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Onboarding abschließen
|
||||||
|
await self._complete_onboarding(operator_room_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Haupt-Phase: Button-Klick oder Text-Antwort
|
||||||
|
if single_line.startswith("FAKT::"):
|
||||||
|
_, choice = single_line.split("::", 1)
|
||||||
|
choice = choice.strip()
|
||||||
|
else:
|
||||||
|
choice = single_line
|
||||||
|
|
||||||
|
from plugin.archivar.onboarding import (
|
||||||
|
validate_fact_store_path,
|
||||||
|
create_and_verify_fact_store,
|
||||||
|
get_default_fact_store_path,
|
||||||
|
)
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
# Option 1: Standard
|
||||||
|
if "Standard" in choice or "1️⃣" in choice or choice == "1":
|
||||||
|
default_path = get_default_fact_store_path()
|
||||||
|
result = create_and_verify_fact_store(default_path)
|
||||||
|
if not result["success"]:
|
||||||
|
await self._post_message_with_retry(
|
||||||
|
operator_room_id,
|
||||||
|
f"❌ Standard-Pfad konnte nicht erstellt werden: {result['error']}"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
strategy = "auto"
|
||||||
|
now_iso = datetime.now(timezone.utc).isoformat()
|
||||||
|
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||||||
|
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||||||
|
from archivar.room_map import RoomMap
|
||||||
|
from archivar.config import ROOM_MAP_PATH
|
||||||
|
from pathlib import Path as PathLib
|
||||||
|
RoomMap.save(self.archivar._room_map, PathLib(ROOM_MAP_PATH))
|
||||||
|
self.archivar._room_map.reload()
|
||||||
|
|
||||||
|
# Aktualisiere doc_store
|
||||||
|
if self.archivar._doc_store is not None:
|
||||||
|
self.archivar._doc_store.set_base_dir(PathLib(default_path))
|
||||||
|
else:
|
||||||
|
from plugin.archivar.doc_store import DocumentationStore
|
||||||
|
self.archivar._doc_store = DocumentationStore(base_dir=PathLib(default_path))
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] FAKT-Store: strategy='auto', path=%s, created_at=%s",
|
||||||
|
default_path, now_iso,
|
||||||
|
)
|
||||||
|
await self._post_message_with_retry(
|
||||||
|
operator_room_id,
|
||||||
|
f"✅ FAKT-Speicherort: `{default_path}` (Standard)\n"
|
||||||
|
f"Änderbar mit `::setfakt`."
|
||||||
|
)
|
||||||
|
await self._complete_onboarding(operator_room_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Option 2: Neuer Ort
|
||||||
|
elif "Neuer Ort" in choice or "2️⃣" in choice or choice == "2":
|
||||||
|
self._onboarding_state["fakt_sub_phase"] = "new_path"
|
||||||
|
if self.archivar is not None:
|
||||||
|
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||||||
|
await self._post_message_with_retry(
|
||||||
|
operator_room_id,
|
||||||
|
"📁 Bitte gib den absoluten Pfad für den neuen FAKT-Speicherort ein "
|
||||||
|
"(z.B. `/home/bernd/meine-notizen`):"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Option 3: Bestehender Ort
|
||||||
|
elif "Bestehender Ort" in choice or "3️⃣" in choice or choice == "3":
|
||||||
|
self._onboarding_state["fakt_sub_phase"] = "existing_path"
|
||||||
|
if self.archivar is not None:
|
||||||
|
self.archivar._state.set_onboarding_state(self._onboarding_state)
|
||||||
|
await self._post_message_with_retry(
|
||||||
|
operator_room_id,
|
||||||
|
"📁 Bitte gib den absoluten Pfad zum bestehenden FAKT-Speicherort ein "
|
||||||
|
"(z.B. `/data/Wissensdatenbank`):"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
# Option 4: Keine Sammlung
|
||||||
|
elif "Keine Sammlung" in choice or "4️⃣" in choice or choice == "4":
|
||||||
|
strategy = "none"
|
||||||
|
now_iso = datetime.now(timezone.utc).isoformat()
|
||||||
|
self.archivar._room_map.set_fact_store_strategy(strategy)
|
||||||
|
self.archivar._room_map.set_fact_store_created_at(now_iso)
|
||||||
|
from archivar.room_map import RoomMap
|
||||||
|
from archivar.config import ROOM_MAP_PATH
|
||||||
|
from pathlib import Path as PathLib
|
||||||
|
RoomMap.save(self.archivar._room_map, PathLib(ROOM_MAP_PATH))
|
||||||
|
self.archivar._room_map.reload()
|
||||||
|
|
||||||
|
# Deaktiviere doc_store
|
||||||
|
self.archivar._doc_store = None
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] FAKT-Store: strategy='none', created_at=%s",
|
||||||
|
now_iso,
|
||||||
|
)
|
||||||
|
await self._post_message_with_retry(
|
||||||
|
operator_room_id,
|
||||||
|
"✅ FAKT-Speicherort: **Keine Wissensammlung**\n"
|
||||||
|
"FAKT-Nachrichten werden im Chat beantwortet, aber nicht persistiert.\n"
|
||||||
|
"Änderbar mit `::setfakt`."
|
||||||
|
)
|
||||||
|
await self._complete_onboarding(operator_room_id)
|
||||||
|
return
|
||||||
|
|
||||||
|
else:
|
||||||
|
await self._post_message_with_retry(
|
||||||
|
operator_room_id,
|
||||||
|
"❌ Bitte wähle eine Option: 1 (Standard), 2 (Neuer Ort), 3 (Bestehender Ort) oder 4 (Keine Sammlung)."
|
||||||
|
)
|
||||||
return
|
return
|
||||||
|
|
||||||
# ── V8.4.2: Keyword-Konflikt-Auflösung ──────────────────────────
|
# ── V8.4.2: Keyword-Konflikt-Auflösung ──────────────────────────
|
||||||
@@ -3644,6 +3848,19 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
await self._post_message_with_retry(operator_room_id, "\n".join(lines), attachments=attachments)
|
await self._post_message_with_retry(operator_room_id, "\n".join(lines), attachments=attachments)
|
||||||
logger.info("[rocketchat] Onboarding v2 abgeschlossen: alle Räume eingerichtet")
|
logger.info("[rocketchat] Onboarding v2 abgeschlossen: alle Räume eingerichtet")
|
||||||
|
|
||||||
|
async def _complete_onboarding(self, operator_room_id: str) -> None:
|
||||||
|
"""Thema 3: Onboarding final abschließen (nach FAKT-Speicherort-Dialog)."""
|
||||||
|
if self.archivar is not None:
|
||||||
|
self.archivar._stats["onboarding_active"] = False
|
||||||
|
self.archivar._state.clear_onboarding_state()
|
||||||
|
self._onboarding_state = {}
|
||||||
|
# FIX E: Raum-Map Summary nach Onboarding aktualisieren
|
||||||
|
self._room_map_summary = self._build_room_map_summary()
|
||||||
|
if self._room_map_summary:
|
||||||
|
logger.info("[rocketchat] FIX E: Raum-Map Summary nach Onboarding aktualisiert (%d Räume)",
|
||||||
|
len(self._room_map_summary.splitlines()) - 1)
|
||||||
|
logger.info("[rocketchat] Onboarding v2 vollständig abgeschlossen (mit FAKT-Speicherort)")
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _derive_keywords(room_name: str, theme: str) -> list:
|
def _derive_keywords(room_name: str, theme: str) -> list:
|
||||||
"""Leitet Stichworte aus Raumname und Thema ab.
|
"""Leitet Stichworte aus Raumname und Thema ab.
|
||||||
|
|||||||
@@ -175,8 +175,18 @@ class ArchivarMessageHandler:
|
|||||||
self._state = ArchivarState(ARCHIVAR_STATE_PATH)
|
self._state = ArchivarState(ARCHIVAR_STATE_PATH)
|
||||||
self._state.load()
|
self._state.load()
|
||||||
|
|
||||||
# doc_store writes to fact_store_path from room_map
|
# Thema 3: Strategy-aware DocumentationStore
|
||||||
self._doc_store = DocumentationStore(base_dir=self._room_map.fact_store_path)
|
strategy = self._room_map.fact_store_strategy
|
||||||
|
if strategy == "none":
|
||||||
|
self._doc_store = None
|
||||||
|
logger.info("FAKT-Store: strategy='none' — kein DocumentationStore")
|
||||||
|
else:
|
||||||
|
fact_path = self._room_map.fact_store_path
|
||||||
|
if strategy == "auto":
|
||||||
|
# mkdir -p falls Pfad nicht existiert
|
||||||
|
fact_path.mkdir(parents=True, exist_ok=True)
|
||||||
|
logger.info("FAKT-Store: strategy='auto' — Verzeichnis erstellt: %s", fact_path)
|
||||||
|
self._doc_store = DocumentationStore(base_dir=fact_path)
|
||||||
|
|
||||||
# Cache for subscribed room IDs (set later via set_subscribed_room_ids)
|
# Cache for subscribed room IDs (set later via set_subscribed_room_ids)
|
||||||
self._subscribed_room_ids_cache: Optional[set] = None
|
self._subscribed_room_ids_cache: Optional[set] = None
|
||||||
@@ -411,6 +421,7 @@ class ArchivarMessageHandler:
|
|||||||
self._stats["meta"] += 1
|
self._stats["meta"] += 1
|
||||||
elif decision.is_unrouteable:
|
elif decision.is_unrouteable:
|
||||||
self._stats["classified"] += 1
|
self._stats["classified"] += 1
|
||||||
|
if self._doc_store is not None:
|
||||||
stored = self._doc_store.store(
|
stored = self._doc_store.store(
|
||||||
text=text,
|
text=text,
|
||||||
category=decision.category,
|
category=decision.category,
|
||||||
@@ -421,6 +432,11 @@ class ArchivarMessageHandler:
|
|||||||
"Unrouteable [%s] stored in doc_store: %s",
|
"Unrouteable [%s] stored in doc_store: %s",
|
||||||
decision.category, stored,
|
decision.category, stored,
|
||||||
)
|
)
|
||||||
|
else:
|
||||||
|
logger.info(
|
||||||
|
"Unrouteable [%s] NOT stored — fact_store_strategy='none'",
|
||||||
|
decision.category,
|
||||||
|
)
|
||||||
elif decision.is_fallback:
|
elif decision.is_fallback:
|
||||||
self._stats["fallback"] += 1
|
self._stats["fallback"] += 1
|
||||||
elif decision.is_catch_all:
|
elif decision.is_catch_all:
|
||||||
@@ -1161,8 +1177,8 @@ class ArchivarMessageHandler:
|
|||||||
self._router.set_subscribed_room_ids(room_ids)
|
self._router.set_subscribed_room_ids(room_ids)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def doc_store(self) -> DocumentationStore:
|
def doc_store(self) -> Optional[DocumentationStore]:
|
||||||
"""Documentation store for unrouteable messages."""
|
"""Documentation store for unrouteable messages (None if strategy='none')."""
|
||||||
return self._doc_store
|
return self._doc_store
|
||||||
|
|
||||||
@property
|
@property
|
||||||
|
|||||||
@@ -131,3 +131,14 @@ class DocumentationStore:
|
|||||||
def base_dir(self) -> Path:
|
def base_dir(self) -> Path:
|
||||||
"""Base directory for stored documents."""
|
"""Base directory for stored documents."""
|
||||||
return self._base_dir
|
return self._base_dir
|
||||||
|
|
||||||
|
def set_base_dir(self, new_base_dir: Path) -> None:
|
||||||
|
"""Thema 3: Ändere das Basisverzeichnis zur Laufzeit.
|
||||||
|
|
||||||
|
Setzt nur den Pfad — erstellt das Verzeichnis NICHT.
|
||||||
|
Das Verzeichnis wird erst bei ``store()`` via ``mkdir -p`` erstellt.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
new_base_dir: Neues Basisverzeichnis.
|
||||||
|
"""
|
||||||
|
self._base_dir = Path(new_base_dir)
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
"""
|
||||||
|
FAKT-Speicherort-Dialog beim Onboarding (Thema 3).
|
||||||
|
|
||||||
|
Stellt die Pfad-Validierung und den 4-Optionen-Dialog für den
|
||||||
|
FAKT-Speicherort bereit. Wird vom Adapter nach der Butler-Mode-Frage
|
||||||
|
aufgerufen.
|
||||||
|
|
||||||
|
Sicherheitsanforderungen:
|
||||||
|
- Pfad muss absolut sein
|
||||||
|
- Keine '..' (Path-Traversal)
|
||||||
|
- System-Verzeichnisse blockiert: /etc, /var, /usr, /boot, /sys, /proc
|
||||||
|
- HOME-relativ wird normalisiert
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional, Dict, Any
|
||||||
|
|
||||||
|
# System-Verzeichnisse, die blockiert werden
|
||||||
|
BLOCKED_PREFIXES = [
|
||||||
|
"/etc",
|
||||||
|
"/var",
|
||||||
|
"/usr",
|
||||||
|
"/boot",
|
||||||
|
"/sys",
|
||||||
|
"/proc",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def validate_fact_store_path(raw_path: str) -> Dict[str, Any]:
|
||||||
|
"""Validiere einen FAKT-Speicherort-Pfad.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
raw_path: Der vom Benutzer eingegebene Pfad (kann HOME-relativ sein).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict mit:
|
||||||
|
- valid (bool): True wenn der Pfad gültig ist
|
||||||
|
- error (str | None): Fehlermeldung wenn invalid
|
||||||
|
- normalized_path (str | None): Normalisierter absoluter Pfad
|
||||||
|
"""
|
||||||
|
if not raw_path or not raw_path.strip():
|
||||||
|
return {"valid": False, "error": "Pfad darf nicht leer sein.", "normalized_path": None}
|
||||||
|
|
||||||
|
raw_path = raw_path.strip()
|
||||||
|
|
||||||
|
# Prüfe: keine '..' (Path-Traversal) — VOR der Normalisierung prüfen
|
||||||
|
if ".." in raw_path:
|
||||||
|
return {
|
||||||
|
"valid": False,
|
||||||
|
"error": "Path-Traversal ('..') ist nicht erlaubt.",
|
||||||
|
"normalized_path": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Prüfe: muss absolut sein oder mit ~ beginnen
|
||||||
|
if not (raw_path.startswith("/") or raw_path.startswith("~")):
|
||||||
|
return {
|
||||||
|
"valid": False,
|
||||||
|
"error": "Der Pfad muss absolut sein (z.B. /home/bernd/wissenssammlung).",
|
||||||
|
"normalized_path": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
# HOME-relativ normalisieren
|
||||||
|
expanded = os.path.expanduser(raw_path)
|
||||||
|
|
||||||
|
# In absoluten Pfad umwandeln
|
||||||
|
try:
|
||||||
|
abs_path = os.path.abspath(expanded)
|
||||||
|
except (ValueError, OSError) as e:
|
||||||
|
return {"valid": False, "error": f"Ungültiger Pfad: {e}", "normalized_path": None}
|
||||||
|
|
||||||
|
# Prüfe: System-Verzeichnisse blockiert
|
||||||
|
resolved = str(Path(abs_path).resolve())
|
||||||
|
for blocked in BLOCKED_PREFIXES:
|
||||||
|
if resolved == blocked or resolved.startswith(blocked + "/") or resolved.startswith(blocked + os.sep):
|
||||||
|
return {
|
||||||
|
"valid": False,
|
||||||
|
"error": f"System-Verzeichnis '{blocked}' ist blockiert. Bitte wähle einen Pfad unter /home oder /tmp.",
|
||||||
|
"normalized_path": None,
|
||||||
|
}
|
||||||
|
|
||||||
|
return {"valid": True, "error": None, "normalized_path": resolved}
|
||||||
|
|
||||||
|
|
||||||
|
def create_and_verify_fact_store(path: str) -> Dict[str, Any]:
|
||||||
|
"""Erstelle das FAKT-Speicherort-Verzeichnis und prüfe Schreibbarkeit.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: Normalisierter absoluter Pfad.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict mit:
|
||||||
|
- success (bool): True wenn Verzeichnis erstellt und schreibbar
|
||||||
|
- error (str | None): Fehlermeldung bei Misserfolg
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
os.makedirs(path, exist_ok=True)
|
||||||
|
except OSError as e:
|
||||||
|
return {"success": False, "error": f"Konnte Verzeichnis nicht erstellen: {e}"}
|
||||||
|
|
||||||
|
# Schreibtest
|
||||||
|
try:
|
||||||
|
test_file = os.path.join(path, ".hermes_write_test")
|
||||||
|
with open(test_file, "w") as f:
|
||||||
|
f.write("test")
|
||||||
|
os.remove(test_file)
|
||||||
|
except OSError as e:
|
||||||
|
return {"success": False, "error": f"Schreibtest fehlgeschlagen: {e}"}
|
||||||
|
|
||||||
|
return {"success": True, "error": None}
|
||||||
|
|
||||||
|
|
||||||
|
def verify_existing_fact_store(path: str) -> Dict[str, Any]:
|
||||||
|
"""Prüfe ob ein bestehendes Verzeichnis referenzierbar und schreibbar ist.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: Normalisierter absoluter Pfad.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dict mit:
|
||||||
|
- success (bool): True wenn Verzeichnis existiert und schreibbar
|
||||||
|
- error (str | None): Fehlermeldung bei Misserfolg
|
||||||
|
"""
|
||||||
|
if not os.path.isdir(path):
|
||||||
|
return {"success": False, "error": f"Verzeichnis existiert nicht: {path}"}
|
||||||
|
|
||||||
|
# Schreibtest
|
||||||
|
try:
|
||||||
|
test_file = os.path.join(path, ".hermes_write_test")
|
||||||
|
with open(test_file, "w") as f:
|
||||||
|
f.write("test")
|
||||||
|
os.remove(test_file)
|
||||||
|
except OSError as e:
|
||||||
|
return {"success": False, "error": f"Schreibtest fehlgeschlagen: {e}"}
|
||||||
|
|
||||||
|
return {"success": True, "error": None}
|
||||||
|
|
||||||
|
|
||||||
|
def get_default_fact_store_path() -> str:
|
||||||
|
"""Gibt den Standard-FAKT-Speicherort zurück (Option 1).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Absoluter Pfad zu .hermes/wissenssammlung im HOME-Verzeichnis.
|
||||||
|
"""
|
||||||
|
return os.path.expanduser("~/.hermes/wissenssammlung")
|
||||||
@@ -126,6 +126,8 @@ class RoomMap:
|
|||||||
fact_store_path: Path,
|
fact_store_path: Path,
|
||||||
version: int = 1,
|
version: int = 1,
|
||||||
butler_mode: str = "cognitive",
|
butler_mode: str = "cognitive",
|
||||||
|
fact_store_strategy: str = "manual",
|
||||||
|
fact_store_created_at: Optional[str] = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Initialize from pre-parsed data.
|
"""Initialize from pre-parsed data.
|
||||||
|
|
||||||
@@ -136,6 +138,8 @@ class RoomMap:
|
|||||||
self._fact_store_path = fact_store_path
|
self._fact_store_path = fact_store_path
|
||||||
self._version = version
|
self._version = version
|
||||||
self._butler_mode = butler_mode # Fix C v7: 'cognitive' | 'strict' | 'off'
|
self._butler_mode = butler_mode # Fix C v7: 'cognitive' | 'strict' | 'off'
|
||||||
|
self._fact_store_strategy = fact_store_strategy # Thema 3: 'auto' | 'manual' | 'none'
|
||||||
|
self._fact_store_created_at = fact_store_created_at # Thema 3: ISO-Timestamp
|
||||||
|
|
||||||
# ── Properties ───────────────────────────────────────────────────
|
# ── Properties ───────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -180,6 +184,36 @@ class RoomMap:
|
|||||||
raise ValueError(f"Invalid butler_mode: {mode}")
|
raise ValueError(f"Invalid butler_mode: {mode}")
|
||||||
self._butler_mode = mode
|
self._butler_mode = mode
|
||||||
|
|
||||||
|
# ── Thema 3: FAKT-Speicherort-Properties ──────────────────────────
|
||||||
|
|
||||||
|
@property
|
||||||
|
def fact_store_strategy(self) -> str:
|
||||||
|
"""Thema 3: FAKT-Speicherort-Strategie — 'auto', 'manual', oder 'none'."""
|
||||||
|
return self._fact_store_strategy
|
||||||
|
|
||||||
|
def set_fact_store_strategy(self, strategy: str) -> None:
|
||||||
|
"""Thema 3: Setze die FAKT-Speicherort-Strategie.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
strategy: 'auto', 'manual', or 'none'.
|
||||||
|
"""
|
||||||
|
if strategy not in ("auto", "manual", "none"):
|
||||||
|
raise ValueError(f"Invalid fact_store_strategy: {strategy}")
|
||||||
|
self._fact_store_strategy = strategy
|
||||||
|
|
||||||
|
@property
|
||||||
|
def fact_store_created_at(self) -> Optional[str]:
|
||||||
|
"""Thema 3: ISO-Timestamp der FAKT-Speicherort-Erstellung (Telemetrie)."""
|
||||||
|
return self._fact_store_created_at
|
||||||
|
|
||||||
|
def set_fact_store_created_at(self, timestamp: Optional[str]) -> None:
|
||||||
|
"""Thema 3: Setze den FAKT-Speicherort-Erstellungszeitpunkt.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
timestamp: ISO-Format Timestamp oder None.
|
||||||
|
"""
|
||||||
|
self._fact_store_created_at = timestamp
|
||||||
|
|
||||||
# ── Lookup Methods ────────────────────────────────────────────────
|
# ── Lookup Methods ────────────────────────────────────────────────
|
||||||
|
|
||||||
def find_room_by_keywords(self, text: str, min_score: int = 1, origin_room_id: Optional[str] = None) -> Optional[RoomEntry]:
|
def find_room_by_keywords(self, text: str, min_score: int = 1, origin_room_id: Optional[str] = None) -> Optional[RoomEntry]:
|
||||||
@@ -459,6 +493,8 @@ class RoomMap:
|
|||||||
self._fact_store_path = new_map._fact_store_path
|
self._fact_store_path = new_map._fact_store_path
|
||||||
self._version = new_map._version
|
self._version = new_map._version
|
||||||
self._butler_mode = new_map._butler_mode # Fix C v7
|
self._butler_mode = new_map._butler_mode # Fix C v7
|
||||||
|
self._fact_store_strategy = new_map._fact_store_strategy # Thema 3
|
||||||
|
self._fact_store_created_at = new_map._fact_store_created_at # Thema 3
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def save(room_map: 'RoomMap', path: Optional[Path] = None) -> None:
|
def save(room_map: 'RoomMap', path: Optional[Path] = None) -> None:
|
||||||
@@ -488,7 +524,11 @@ class RoomMap:
|
|||||||
"excluded_rooms": list(room_map._excluded_room_ids),
|
"excluded_rooms": list(room_map._excluded_room_ids),
|
||||||
"fact_store_path": str(room_map._fact_store_path),
|
"fact_store_path": str(room_map._fact_store_path),
|
||||||
"butler_mode": room_map._butler_mode, # Fix C v7
|
"butler_mode": room_map._butler_mode, # Fix C v7
|
||||||
|
"fact_store_strategy": room_map._fact_store_strategy, # Thema 3
|
||||||
}
|
}
|
||||||
|
# Thema 3: fact_store_created_at nur persistieren wenn gesetzt
|
||||||
|
if room_map._fact_store_created_at is not None:
|
||||||
|
data["fact_store_created_at"] = room_map._fact_store_created_at
|
||||||
|
|
||||||
for room_id, room_entry in room_map._rooms.items():
|
for room_id, room_entry in room_map._rooms.items():
|
||||||
data["rooms"][room_id] = {
|
data["rooms"][room_id] = {
|
||||||
@@ -760,6 +800,9 @@ class RoomMap:
|
|||||||
os.path.expanduser(data.get("fact_store_path", "~/archivar_docs"))
|
os.path.expanduser(data.get("fact_store_path", "~/archivar_docs"))
|
||||||
)
|
)
|
||||||
butler_mode = data.get("butler_mode", "cognitive") # Fix C v7
|
butler_mode = data.get("butler_mode", "cognitive") # Fix C v7
|
||||||
|
# Thema 3: FAKT-Speicherort-Felder
|
||||||
|
fact_store_strategy = data.get("fact_store_strategy", "manual") # Migration: default 'manual'
|
||||||
|
fact_store_created_at = data.get("fact_store_created_at", None)
|
||||||
|
|
||||||
return cls(
|
return cls(
|
||||||
rooms=rooms,
|
rooms=rooms,
|
||||||
@@ -767,6 +810,8 @@ class RoomMap:
|
|||||||
fact_store_path=fact_store,
|
fact_store_path=fact_store,
|
||||||
version=version,
|
version=version,
|
||||||
butler_mode=butler_mode,
|
butler_mode=butler_mode,
|
||||||
|
fact_store_strategy=fact_store_strategy,
|
||||||
|
fact_store_created_at=fact_store_created_at,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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()
|
||||||
@@ -1,19 +0,0 @@
|
|||||||
{
|
|
||||||
"rooms": {},
|
|
||||||
"keyword_weights": {},
|
|
||||||
"sticky_keywords": {},
|
|
||||||
"manual_overrides": {},
|
|
||||||
"promotion_candidates": {},
|
|
||||||
"stay_tracker": {},
|
|
||||||
"onboarding_state": {},
|
|
||||||
"never_route": {
|
|
||||||
"r_proton": {
|
|
||||||
"lan-dokumentation": {
|
|
||||||
"state": "AKTIV",
|
|
||||||
"timestamp": "2026-07-13T20:34:20.149597",
|
|
||||||
"last_extended": "2026-07-13T20:34:20.149597",
|
|
||||||
"extension_count": 0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Reference in New Issue
Block a user