BUGFIX: FAISS Phase-1 TypeError float+str in adapter_integration.py:292

Root cause: RoomIndexManager.stats() returns a dict with mixed types
(bool, int, float, str). sum() iterated over all values and crashed
when hitting built_at_iso (str) after built_at (float).

Fix: Replace stats() call with direct .size and .room_ids properties.
Also commit FAISS Phase-1 files (booster.py, room_index.py, seed_data.py)
that were deployed to Gateway but not yet in repo.

Tests: 58 passed (0 failures)
This commit is contained in:
Bernd (Hermes)
2026-06-16 20:31:57 +02:00
parent 43d14b2d58
commit 03d3bb44df
4 changed files with 933 additions and 3 deletions
+4 -3
View File
@@ -286,11 +286,12 @@ class ArchivarMessageHandler:
if self._room_index is not None and self._booster is not None: if self._room_index is not None and self._booster is not None:
try: try:
self._room_index.build_index() self._room_index.build_index()
index_stats = self._room_index.stats() room_count = self._room_index.size
room_ids = self._room_index.room_ids
logger.info( logger.info(
"FAISS Phase-1: Index gebaut — %d Vektoren in %d Räumen: %s", "FAISS Phase-1: Index gebaut — %d Vektoren in %d Räumen: %s",
sum(index_stats.values()), len(index_stats), room_count, room_count,
", ".join(f"{rid[:12]}…={n}" for rid, n in index_stats.items()) ", ".join(f"{rid[:12]}…" for rid in room_ids)
) )
# Router mit FAISS-Objekten neu erstellen # Router mit FAISS-Objekten neu erstellen
self._router = BidirectionalRouter( self._router = BidirectionalRouter(
+178
View File
@@ -0,0 +1,178 @@
"""
Keyword-Booster für Archivar v5.
Verfeinert FAISS-Suchergebnisse durch Keyword-Analyse:
- Eindeutige Keywords (nur in einem Raum) geben +0.05 Boost
- Mehrdeutige Keywords sind neutral
- Bei knappen Top-2 entscheidet die Anzahl eindeutiger Keywords
Usage::
from .room_map import RoomMap
from .booster import KeywordBooster
room_map = RoomMap.load()
booster = KeywordBooster(room_map)
scores = [("room_a", 0.87), ("room_b", 0.85), ("room_c", 0.62)]
text = "Das Plugin hat einen Bug im Router"
boosted = booster.boost(text, scores)
# → [("room_a", 0.92), ("room_b", 0.85), ("room_c", 0.62)]
"""
from __future__ import annotations
import logging
from typing import Dict, List, Set, Tuple
logger = logging.getLogger(__name__)
class KeywordBooster:
"""Keyword-basierter Score-Booster für RoomIndexManager.search()-Ergebnisse.
Baut aus einer geladenen RoomMap ein Mapping: keyword → set of room_ids.
Wendet dann Boosts auf FAISS-Scores an basierend auf Keyword-Eindeutigkeit.
"""
def __init__(self, room_map) -> None:
"""Initialisiere den Booster mit einer geladenen RoomMap.
Args:
room_map: Eine ``RoomMap``-Instanz (aus ``room_map.py``).
"""
self._room_map = room_map
self._keyword_to_rooms: Dict[str, Set[str]] = {}
self._build_mapping()
# ── Mapping ───────────────────────────────────────────────────────
def _build_mapping(self) -> None:
"""Baut keyword → set(room_ids) aus allen keywords_100 + keywords_context."""
self._keyword_to_rooms.clear()
for room_id, entry in self._room_map.rooms.items():
if entry.catch_all:
continue # Catch-All nimmt nicht an Keyword-Boosts teil
all_keywords: List[str] = []
all_keywords.extend(entry.keywords_100)
all_keywords.extend(entry.keywords_context)
for kw in all_keywords:
kw_lower = kw.lower().strip()
if not kw_lower:
continue
if kw_lower not in self._keyword_to_rooms:
self._keyword_to_rooms[kw_lower] = set()
self._keyword_to_rooms[kw_lower].add(room_id)
logger.debug(
"KeywordBooster mapping built: %d keywords across %d rooms",
len(self._keyword_to_rooms),
len(self._room_map.rooms),
)
# ── Public API ─────────────────────────────────────────────────────
def boost(
self,
text: str,
scores: List[Tuple[str, float]],
) -> List[Tuple[str, float]]:
"""Wendet Keyword-Boosts auf FAISS-Scores an.
Args:
text: Der Nachrichtentext (für Keyword-Extraktion).
scores: Liste von ``(room_id, score)``-Tupeln aus
``RoomIndexManager.search()``, absteigend nach Score sortiert.
Returns:
Neue Liste von ``(room_id, adjusted_score)``-Tupeln,
absteigend nach adjusted_score sortiert.
"""
if not scores:
return []
# ── Score-Dict aufbauen ──────────────────────────────────
score_dict: Dict[str, float] = {room_id: score for room_id, score in scores}
# ── Keywords im Text finden ───────────────────────────────
text_lower = text.lower()
matched_keywords: List[str] = [
kw for kw in self._keyword_to_rooms if kw in text_lower
]
if not matched_keywords:
# Keine Keywords → Scores unverändert zurück
return sorted(scores, key=lambda x: x[1], reverse=True)
# ── Boost-Phase: +0.05 für eindeutige Keywords ────────────
for kw in matched_keywords:
rooms = self._keyword_to_rooms[kw]
if len(rooms) == 1:
unique_room = next(iter(rooms))
if unique_room in score_dict:
score_dict[unique_room] += 0.05
logger.debug(
"Boost +0.05: keyword='%s' → room='%s' (unique)",
kw,
unique_room[:8],
)
# ── Nach Boost sortieren ──────────────────────────────────
boosted = sorted(score_dict.items(), key=lambda x: x[1], reverse=True)
# ── Konfliktlösung: Top-2 Diff < 0.03 ────────────────────
if len(boosted) >= 2:
top1_room, top1_score = boosted[0]
top2_room, top2_score = boosted[1]
diff = top1_score - top2_score
if diff < 0.03:
# Zähle eindeutige Keyword-Treffer für beide Räume
unique_count_1 = self._count_unique_matches(text_lower, top1_room)
unique_count_2 = self._count_unique_matches(text_lower, top2_room)
if unique_count_1 > unique_count_2:
score_dict[top1_room] += 0.02
logger.debug(
"Conflict resolution: +0.02 for '%s' (%d unique vs %d)",
top1_room[:8],
unique_count_1,
unique_count_2,
)
elif unique_count_2 > unique_count_1:
score_dict[top2_room] += 0.02
logger.debug(
"Conflict resolution: +0.02 for '%s' (%d unique vs %d)",
top2_room[:8],
unique_count_2,
unique_count_1,
)
# Bei Gleichstand: kein zusätzlicher Boost
# ── Finale Sortierung ─────────────────────────────────────
return sorted(score_dict.items(), key=lambda x: x[1], reverse=True)
# ── Helpers ────────────────────────────────────────────────────────
def _count_unique_matches(self, text_lower: str, room_id: str) -> int:
"""Zählt wie viele eindeutige Keywords (nur in diesem Raum) im Text vorkommen.
Args:
text_lower: Der Text in lowercase.
room_id: Die zu prüfende Raum-ID.
Returns:
Anzahl der eindeutigen Keyword-Treffer für diesen Raum.
"""
count = 0
for kw, rooms in self._keyword_to_rooms.items():
if len(rooms) == 1 and room_id in rooms and kw in text_lower:
count += 1
return count
def reload(self) -> None:
"""Baut das Keyword-Mapping neu (nach RoomMap.reload())."""
self._build_mapping()
+617
View File
@@ -0,0 +1,617 @@
"""
FAISS-Index-Manager für Archivar v5.
Baut und verwaltet einen FAISS-Index über Raum-Embeddings für schnelle
Ähnlichkeitssuche. Jeder Raum wird durch seinen Theme-Text und alle
Keywords repräsentiert — der kombinierte Text wird via Ollama Embedding-API
vektorisiert und in einem ``IndexFlatIP`` (Inner Product = Kosinus-Ähnlichkeit
bei normalisierten Vektoren) abgelegt.
Der Index wird auf Disk persistiert (``room_index.faiss`` + ``room_index.meta``)
und kann beim Start geladen werden, um teure Neuberechnungen zu vermeiden.
Usage::
from .room_map import RoomMap
from .classifier import OllamaEmbeddingClient
from .room_index import RoomIndexManager
room_map = RoomMap.load()
emb_client = OllamaEmbeddingClient()
index_mgr = RoomIndexManager(room_map, emb_client)
if not index_mgr.load():
index_mgr.build_index()
index_mgr.save()
query_vec = emb_client.get_embedding("Das Plugin hat einen Bug")
hits = index_mgr.search(query_vec, k=3)
# → [("room_id_abc", 0.87), ("room_id_def", 0.62), ...]
"""
from __future__ import annotations
import fcntl
import json
import logging
import os
import time
from pathlib import Path
from typing import Dict, List, Optional, Tuple
import numpy as np
try:
import faiss
except ImportError:
faiss = None # type: ignore[assignment]
from .config import OLLAMA_CONFIG
from .classifier import EmbeddingClient
from .room_map import RoomMap, RoomEntry
logger = logging.getLogger(__name__)
# ── Constants ─────────────────────────────────────────────────────────────
_DEFAULT_INDEX_DIR: str = os.path.expanduser(
os.getenv("ARCHIVAR_INDEX_DIR", "~/.hermes/hermes-agent/data")
)
_INDEX_FILENAME: str = "room_index.faiss"
_META_FILENAME: str = "room_index.meta"
# ── Exception ──────────────────────────────────────────────────────────────
class RoomIndexError(Exception):
"""Raised when FAISS operations fail (build, search, save, load)."""
# ── RoomIndexManager ───────────────────────────────────────────────────────
class RoomIndexManager:
"""FAISS-Index-Manager für Raum-Embeddings.
Attributes:
embedding_dim: Dimension der Embedding-Vektoren (default 768 für
nomic-embed-text).
index: Der FAISS-Index (``IndexFlatIP``). None vor ``build_index()``
oder ``load()``.
_room_ids: Parallele Liste — Index-Position → room_id.
_room_map: Referenz auf die ``RoomMap`` (für Theme/Keyword-Zugriff).
_emb_client: ``EmbeddingClient`` für Ollama-API-Calls.
_index_dir: Verzeichnis für Persistenz-Dateien.
"""
def __init__(
self,
room_map: RoomMap,
embedding_client: EmbeddingClient,
index_dir: Optional[str] = None,
embedding_dim: Optional[int] = None,
) -> None:
"""
Args:
room_map: Eine geladene und validierte ``RoomMap``-Instanz.
embedding_client: Ein ``EmbeddingClient`` (z. B.
``OllamaEmbeddingClient``) für die Vektorisierung.
index_dir: Verzeichnis für Index-Persistenz. Default:
``ARCHIVAR_INDEX_DIR`` oder ``~/.hermes/hermes-agent/data``.
embedding_dim: Dimension der Vektoren. Default aus
``OLLAMA_CONFIG["embedding_dim"]`` (768).
"""
if faiss is None:
raise RoomIndexError(
"faiss is not installed. Install with: pip install faiss-cpu"
)
self._room_map = room_map
self._emb_client = embedding_client
self._index_dir = Path(index_dir or _DEFAULT_INDEX_DIR)
self._embedding_dim = embedding_dim or OLLAMA_CONFIG["embedding_dim"]
# FAISS state
self.index: Optional[faiss.IndexFlatIP] = None
self._room_ids: List[str] = []
self._built_at: float = 0.0
self._version: int = 1
# ── Properties ─────────────────────────────────────────────────────
@property
def is_built(self) -> bool:
"""True wenn der Index gebaut oder geladen wurde."""
return self.index is not None and len(self._room_ids) > 0
@property
def size(self) -> int:
"""Anzahl der Räume im Index."""
return len(self._room_ids) if self._room_ids else 0
@property
def room_ids(self) -> List[str]:
"""Kopie der Raum-ID-Liste (Index-Position → room_id)."""
return list(self._room_ids)
@property
def index_path(self) -> Path:
"""Pfad zur FAISS-Index-Datei."""
return self._index_dir / _INDEX_FILENAME
@property
def meta_path(self) -> Path:
"""Pfad zur Metadaten-Datei (room_ids, version, timestamp)."""
return self._index_dir / _META_FILENAME
# ── Build ──────────────────────────────────────────────────────────
def build_index(self) -> None:
"""Baut den FAISS-Index aus allen Räumen der RoomMap.
Für jeden Raum (außer Catch-All) wird ein kombinierter Text aus
Theme + allen Keywords gebildet, via Embedding-API vektorisiert
und normalisiert in einen ``IndexFlatIP`` eingefügt.
Catch-All-Räume werden NICHT in den Index aufgenommen — sie
dienen als Fallback und sollen nie via Similarity-Match getroffen
werden.
Raises:
RoomIndexError: Wenn keine Räume zum Indizieren vorhanden sind
oder die Embedding-API für alle Räume fehlschlägt.
"""
rooms = [
(rid, entry)
for rid, entry in self._room_map.rooms.items()
if not entry.catch_all
]
if not rooms:
raise RoomIndexError(
"No indexable rooms in RoomMap (all are catch-all or empty). "
"Add at least one non-catch-all room with theme/keywords."
)
vectors: List[np.ndarray] = []
room_ids: List[str] = []
failed: int = 0
for room_id, entry in rooms:
text = self._room_to_text(entry)
if not text.strip():
logger.warning(
"Room '%s' has no theme or keywords — skipping index",
entry.name,
)
continue
vec = self._embed_text(text)
if vec is None:
logger.warning(
"Failed to embed room '%s' — skipping", entry.name
)
failed += 1
continue
# Normalisieren für Kosinus-Ähnlichkeit via Inner Product
vec = vec / np.linalg.norm(vec)
vectors.append(vec)
room_ids.append(room_id)
if not vectors:
raise RoomIndexError(
f"Failed to embed any room ({failed} failures). "
"Check Ollama connectivity and model availability."
)
# Baue IndexFlatIP (Inner Product = Kosinus-Ähnlichkeit bei normierten Vektoren)
matrix = np.array(vectors, dtype=np.float32)
index = faiss.IndexFlatIP(self._embedding_dim)
index.add(matrix)
self.index = index
self._room_ids = room_ids
self._built_at = time.time()
self._version = self._room_map.version
logger.info(
"RoomIndex built: %d rooms, dim=%d, %d embedding failures",
len(room_ids),
self._embedding_dim,
failed,
)
# ── Search ─────────────────────────────────────────────────────────
def search(
self,
query_embedding: List[float],
k: int = 5,
min_score: float = 0.0,
) -> List[Tuple[str, float]]:
"""Sucht die *k* ähnlichsten Räume zu einem Query-Embedding.
Args:
query_embedding: Der Embedding-Vektor der Nachricht (768 floats).
k: Anzahl der zurückgegebenen Top-Treffer.
min_score: Minimaler Score (0.0–1.0) für Treffer. Treffer
darunter werden herausgefiltert.
Returns:
Liste von ``(room_id, score)``-Tupeln, absteigend nach Score
sortiert. Score ist Kosinus-Ähnlichkeit (0.0–1.0).
Raises:
RoomIndexError: Wenn der Index noch nicht gebaut/geladen wurde.
"""
if not self.is_built:
raise RoomIndexError(
"Index not built or loaded. Call build_index() or load() first."
)
# Normalisieren
qvec = np.array(query_embedding, dtype=np.float32)
qvec = qvec / np.linalg.norm(qvec)
qvec = qvec.reshape(1, -1)
k_eff = min(k, self.size)
scores, indices = self.index.search(qvec, k_eff) # type: ignore[union-attr]
results: List[Tuple[str, float]] = []
for score, idx in zip(scores[0], indices[0]):
if idx < 0 or idx >= len(self._room_ids):
continue # FAISS kann -1 für "kein Treffer" liefern
if score < min_score:
continue
results.append((self._room_ids[idx], float(score)))
return results
def search_text(
self,
text: str,
k: int = 5,
min_score: float = 0.0,
) -> List[Tuple[str, float]]:
"""Convenience: Embed *text* und suche die ähnlichsten Räume.
Args:
text: Der Nachrichtentext.
k: Anzahl der Top-Treffer.
min_score: Minimaler Kosinus-Score.
Returns:
Liste von ``(room_id, score)``-Tupeln, oder leere Liste
wenn die Embedding-API fehlschlägt.
"""
vec = self._embed_text(text)
if vec is None:
logger.warning("search_text: embedding failed for '%.80s...'", text)
return []
return self.search(vec, k=k, min_score=min_score)
# ── Incremental Updates ────────────────────────────────────────────
def add_room(self, room_id: str, entry: RoomEntry) -> bool:
"""Fügt einen einzelnen Raum zum Index hinzu.
Hängt den normalisierten Embedding-Vektor an den bestehenden
FAISS-Index an. Der Index MUSS bereits gebaut/geladen sein.
Args:
room_id: Rocket.Chat Raum-ID.
entry: Der ``RoomEntry`` mit Theme und Keywords.
Returns:
True wenn erfolgreich hinzugefügt, False wenn Embedding
fehlschlug oder der Raum bereits im Index ist.
Raises:
RoomIndexError: Wenn der Index noch nicht gebaut/geladen wurde.
"""
if not self.is_built:
raise RoomIndexError(
"Index not built or loaded. Call build_index() or load() first."
)
if room_id in self._room_ids:
logger.debug("Room '%s' already in index — skipping", room_id)
return False
if entry.catch_all:
logger.debug("Room '%s' is catch-all — skipping index", entry.name)
return False
text = self._room_to_text(entry)
if not text.strip():
logger.warning("Room '%s' has no theme/keywords — skipping", entry.name)
return False
vec = self._embed_text(text)
if vec is None:
logger.warning("Failed to embed room '%s'", entry.name)
return False
vec = vec / np.linalg.norm(vec)
vec = vec.reshape(1, -1).astype(np.float32)
self.index.add(vec) # type: ignore[union-attr]
self._room_ids.append(room_id)
logger.info("Added room '%s' (%s) to index", entry.name, room_id[:8])
return True
def remove_room(self, room_id: str) -> bool:
"""Entfernt einen Raum aus dem Index.
FAISS ``IndexFlatIP`` unterstützt kein ``remove_ids`` — daher
wird der gesamte Index neu gebaut (``rebuild()``).
Args:
room_id: Die zu entfernende Raum-ID.
Returns:
True wenn der Raum entfernt wurde, False wenn er nicht
im Index war.
"""
if room_id not in self._room_ids:
return False
logger.info(
"Removing room '%s' from index — triggering rebuild", room_id[:8]
)
self.rebuild()
return True
def rebuild(self) -> None:
"""Baut den Index komplett neu aus der aktuellen RoomMap.
Nützlich nach ``RoomMap.reload()`` oder mehreren add/remove-
Operationen. Löscht den bestehenden Index und baut ihn frisch.
"""
self.index = None
self._room_ids = []
self.build_index()
# ── Persistence ─────────────────────────────────────────────────────
def save(self, index_dir: Optional[str] = None) -> str:
"""Persistiert den FAISS-Index und Metadaten auf Disk.
Schreibt zwei Dateien:
- ``room_index.faiss``: Der FAISS-Index (via ``faiss.write_index``).
- ``room_index.meta``: JSON mit room_ids, version, timestamp, dim.
Verwendet ``fcntl.flock`` für sicheres Schreiben bei parallelen
Prozessen.
Args:
index_dir: Alternatives Verzeichnis. Default: ``self._index_dir``.
Returns:
Pfad zur FAISS-Index-Datei.
Raises:
RoomIndexError: Wenn der Index nicht gebaut ist.
"""
if not self.is_built:
raise RoomIndexError(
"Cannot save: index not built. Call build_index() first."
)
directory = Path(index_dir) if index_dir else self._index_dir
directory.mkdir(parents=True, exist_ok=True)
faiss_path = directory / _INDEX_FILENAME
meta_path = directory / _META_FILENAME
# ── FAISS-Index schreiben ──────────────────────────────────
try:
faiss.write_index(self.index, str(faiss_path)) # type: ignore[union-attr]
except Exception as e:
raise RoomIndexError(f"Failed to write FAISS index: {e}") from e
# ── Metadaten schreiben (mit File-Lock) ────────────────────
meta = {
"version": self._version,
"embedding_dim": self._embedding_dim,
"room_ids": self._room_ids,
"built_at": self._built_at,
"saved_at": time.time(),
"room_count": len(self._room_ids),
}
with open(meta_path, "w", encoding="utf-8") as f:
try:
fcntl.flock(f.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
logger.warning(
"RoomIndex.save: meta file locked, retrying with blocking lock"
)
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
try:
json.dump(meta, f, indent=2, ensure_ascii=False)
f.flush()
os.fsync(f.fileno())
finally:
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
logger.info(
"RoomIndex saved: %d rooms → %s",
len(self._room_ids),
faiss_path,
)
return str(faiss_path)
def load(self, index_dir: Optional[str] = None) -> bool:
"""Lädt den FAISS-Index und Metadaten von Disk.
Args:
index_dir: Alternatives Verzeichnis. Default: ``self._index_dir``.
Returns:
True wenn erfolgreich geladen, False wenn die Dateien nicht
existieren oder inkonsistent sind.
"""
directory = Path(index_dir) if index_dir else self._index_dir
faiss_path = directory / _INDEX_FILENAME
meta_path = directory / _META_FILENAME
if not faiss_path.exists():
logger.info("No saved index at %s — needs build_index()", faiss_path)
return False
if not meta_path.exists():
logger.warning(
"FAISS index exists but meta file missing at %s — needs rebuild",
meta_path,
)
return False
# ── Metadaten laden ────────────────────────────────────────
try:
with open(meta_path, "r", encoding="utf-8") as f:
meta = json.load(f)
except (json.JSONDecodeError, OSError) as e:
logger.error("Failed to read index meta: %s", e)
return False
# Validierung
stored_dim = meta.get("embedding_dim", 0)
if stored_dim != self._embedding_dim:
logger.warning(
"Embedding dimension mismatch: stored=%d, current=%d — needs rebuild",
stored_dim,
self._embedding_dim,
)
return False
room_ids = meta.get("room_ids", [])
if not room_ids:
logger.warning("Meta file has empty room_ids — needs rebuild")
return False
# ── FAISS-Index laden ──────────────────────────────────────
try:
index = faiss.read_index(str(faiss_path))
except Exception as e:
logger.error("Failed to read FAISS index: %s", e)
return False
if not isinstance(index, faiss.IndexFlatIP):
logger.error(
"Loaded index is %s, expected IndexFlatIP — needs rebuild",
type(index).__name__,
)
return False
if index.d != self._embedding_dim:
logger.warning(
"Loaded index dim=%d, expected %d — needs rebuild",
index.d,
self._embedding_dim,
)
return False
if index.ntotal != len(room_ids):
logger.warning(
"Index size mismatch: index=%d, meta=%d — needs rebuild",
index.ntotal,
len(room_ids),
)
return False
# ── Zustand übernehmen ─────────────────────────────────────
self.index = index
self._room_ids = room_ids
self._built_at = meta.get("built_at", 0.0)
self._version = meta.get("version", 1)
logger.info(
"RoomIndex loaded: %d rooms, dim=%d, version=%d from %s",
len(room_ids),
self._embedding_dim,
self._version,
faiss_path,
)
return True
def is_stale(self, room_map_version: Optional[int] = None) -> bool:
"""Prüft ob der Index veraltet ist (RoomMap-Version neuer).
Args:
room_map_version: Aktuelle Version der RoomMap. Default:
``self._room_map.version``.
Returns:
True wenn der Index neu gebaut werden sollte.
"""
if not self.is_built:
return True
current_version = (
room_map_version if room_map_version is not None
else self._room_map.version
)
return current_version > self._version
# ── Internal Helpers ────────────────────────────────────────────────
@staticmethod
def _room_to_text(entry: RoomEntry) -> str:
"""Bildet einen Embedding-Text aus Theme + allen Keywords.
Der kombinierte Text wird von der Embedding-API vektorisiert.
Keywords werden mit höherem Gewicht dupliziert, damit sie im
Embedding-Raum stärker repräsentiert sind.
"""
parts: List[str] = []
if entry.theme:
parts.append(entry.theme)
# Keywords doppelt für stärkere Gewichtung im Embedding
for kw in entry.keywords_100:
parts.extend([kw, kw])
for kw in entry.keywords_context:
parts.append(kw)
return " ".join(parts)
def _embed_text(self, text: str) -> Optional[np.ndarray]:
"""Embed *text* via ``EmbeddingClient`` und gib numpy-Array zurück.
Returns:
float32 numpy array der Länge ``embedding_dim``, oder None
bei Fehler.
"""
raw = self._emb_client.get_embedding(text)
if raw is None:
return None
if len(raw) != self._embedding_dim:
logger.error(
"Embedding dimension mismatch: got %d, expected %d",
len(raw),
self._embedding_dim,
)
return None
return np.array(raw, dtype=np.float32)
# ── Stats / Debug ──────────────────────────────────────────────────
def stats(self) -> dict:
"""Gibt Diagnose-Statistiken als Dict zurück."""
return {
"is_built": self.is_built,
"room_count": self.size,
"embedding_dim": self._embedding_dim,
"version": self._version,
"built_at": self._built_at,
"built_at_iso": (
time.strftime("%Y-%m-%dT%H:%M:%S", time.localtime(self._built_at))
if self._built_at else None
),
"index_dir": str(self._index_dir),
"index_path": str(self.index_path),
"meta_path": str(self.meta_path),
}
+134
View File
@@ -0,0 +1,134 @@
"""
Archivar v5 — FAISS Phase-1 Seed-Daten.
Agent-kuratierte Trainingsbasis: Stichwortlisten + repräsentative Nachrichten
pro Raum, nach SINN zugeordnet (nicht nach historischem Ort).
Jeder Eintrag: {"text": "...", "room": "room_id", "source": "agent_curated"}
"""
SEED_DATA = {
# ── #Rocketchat-Plugin ──────────────────────────────────────────────
"6a19b0ff02aeecd36b1aa16c": {
"stichworte": (
"RC-Plugin-Entwicklung, Adapter, DDP, WebSocket, Buttons, "
"Archivar, Routing, Gateway-Integration, Rocket.Chat-API, "
"CLARIFY, Message-Handling, Raum-Management, install.sh, "
"Deployment, Plugin, Hermes Gateway, Onboarding, "
"Button-Garantie, Move-Request, Embedding, FAISS, "
"Phase-1-Routing, Intent-Klassifikation, room-map.json"
),
"messages": [
# Architektur-Strategie (heutiges Gespräch)
{"text": "FAISS als Phase-1-Raum-Index für Archivar v5 — Drei-Schichten-Logik: FAISS + Keyword-Booster + LLM", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
{"text": "Der Archivar und der Agent sind ein Team. Einer sagt wohin und der andere entscheidet, ob es eine Antwort braucht.", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
{"text": "Vier Bausteine: _CURRENT_ORIGIN_ROOM, _THEMATIC_TARGET_ROOM, _question_counter, Priority-0-Routing", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
{"text": "Kontext-Reset fehlt als fünfter Baustein — _THEMATIC_TARGET_ROOM wird nicht zurückgesetzt nach DM", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
# BUTTON_CLICK-Fix
{"text": "BUTTON_CLICK-False-Positive: adapter.py:583 matched CLARIFY-Antworten mit :: als Button-Click", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
{"text": "Fix: not text.startswith('CLARIFY:') in Zeile 583 — ein Wort, chirurgisch deployt", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
# Button-Garantie
{"text": "Button-Garantie: Move-Request von Textoptionen auf native Action-Buttons umgestellt — ✅Ja/📍Hier/📌Generell", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
{"text": "Onboarding-Buttons: blaue Nummern statt Text-Labels, 12 auf 6 reduziert, skip_all/later global", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
# Deployment
{"text": "Deployment-Pipeline mit 3 Guards gehärtet: Syntax-Check, Vollständigkeits-Check, Pycache-Löschung", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
{"text": "install.sh State-Cleanup vor Gateway-Restart in allen 3 Pfaden — gateway_state.json + reset-failed", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
{"text": "Deployment-Pfad-Mismatch: Gateway lädt aus ~/.hermes/, nicht /usr/local/lib/. __pycache__ macht Fix unsichtbar.", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
# Archivar
{"text": "Archivar v4: Embedding-Vorfilter (nomic-embed-text) → LLM_ROOM_PROMPT (qwen2.5:7b) → room_id → Move-Request → Route", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
{"text": "LLM-Raum-Router: Median 2.4s, P95 2.6s, Cold-Start 7.9s. Timeout 10s, Fallback CATCH_ALL.", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
{"text": "Timeout-Fallback braucht Raumliste — ohne Kontext ist der Agent blind, mit Raumliste kann er selbst entscheiden", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
{"text": "room-map.json v2: 100%-Keywords, ein Treffer = sofortiger Match, kein min_score=2 mehr", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
# Gateway
{"text": "Gateway-Crash-Recovery: rm gateway_state.json + gateway.lock → reset-failed → restart", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
{"text": "systemctl stop während aktiver Session = Crash. Drain timeoutet 60s, StartLimitBurst exhausted.", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
{"text": "gateway-preflight-briefing: Vor jedem Gateway-Start Briefing-Prompt mit Entwicklungsstand posten", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
# Own-Message-Filter
{"text": "Own-Message-Filter: StartObsidian und projekt sync via rocketchat_send werden verworfen — direkt ausführen", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
# SOUL.md
{"text": "SOUL.md: delegate_task vererbt Eltern-Modell an ALLE Subagenten — Team-Agenten NUR via terminal mit Profil", "room": "6a19b0ff02aeecd36b1aa16c", "source": "agent_curated"},
],
},
# ── #BAT-Team ───────────────────────────────────────────────────────
"6a049d493a62ef8f1ead2320": {
"stichworte": (
"BAT Trading Platform, Docker, Next.js, Prisma, API, Web-UI, "
"Krypto-Analyse, Wyckoff-Methodik, Boot-Window, install.sh, "
"Container, Pre-Prod, .45, Build-VM, .101, docker-compose, "
"pnpm, postgresql, pg_dump, API_KEY, Narrensicher-Test, "
"Snapshot, Abweichungen, DATABASE_URL, Gateway, Tor, DB"
),
"messages": [
# Narrensicher-Test
{"text": "BAT Narrensicher-Test auf .45: 13 Abweichungen dokumentiert, install.sh --url http://192.168.180.45:3003", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
{"text": "patch_compose() auf generisches Pattern umgestellt: bat_user:[^@]*@db matched JEDEN Platzhalter", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
# Docker
{"text": "docker compose down -v ist der Nuklear-Fix für P1000 — Docker cached Compose-Konfigurationen, --force-recreate reicht nicht", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
{"text": "Docker-DNS fehlt auf frischem Debian: /etc/docker/daemon.json mit dns: [192.168.180.1, 8.8.8.8] nötig", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
{"text": "Web-Container: prisma generate fehlte → Build scheiterte an Cannot find module .prisma/client/default", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
{"text": "Gateway: Doppelter Protokoll-Fehler wss://https://... → getaddrinfo ENOTFOUND https", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
# API_KEY
{"text": "API_KEY wurde nie generiert — install.sh muss ALLE Secrets generieren, nicht nur DB-Passwort", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
{"text": "Next.js NEXT_PUBLIC_* ist eine Falle: Server-seitige API_KEY-Env-Vars sind für Client unsichtbar", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
# pg_dump
{"text": "pg_dump: drei Teilprobleme — pg_dump not found, Unix-Socket statt TCP, Version-Mismatch v15↔v16", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
{"text": "postgresql-client-16 via pgdg-Repo ins Dockerfile — Debian-Repos haben nur v15", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
# SSH
{"text": "SSH-Key-Mapping: bat_preprod_key für Build-VM→.45, gitea_hermes_key für .45→Gitea:222", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
# Features
{"text": "4 Features auf .45 deployt: KI-Provider, DB-Backup, Deutsche UI-Übersetzung, Freie Agenten-Konfiguration", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
{"text": "AUTH_PUBLIC-Entscheidungsmatrix: Key-Test ja (keine Secrets), DB-Info nein (Passwort), Backup NIEMALS", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
# Stash
{"text": "2-Wochen-alter Stash im BAT-Repo: node:22-bookworm-libssl Dockerfile + Boot-Window-Registrierung", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
{"text": "Stash-Duplikat-Pattern: Vor git stash pop prüfen ob Feature bereits committed ist", "room": "6a049d493a62ef8f1ead2320", "source": "agent_curated"},
],
},
# ── #LAN-Dokumentation ──────────────────────────────────────────────
"6a1c56d4b73efec2bebec2db": {
"stichworte": (
"LAN Dokumentation, Homelab, Netzwerk, Proxmox, Subnetze, "
"IP-Adressen, Router, Switch, Heimnetz, RZBLN, VLAN, "
"Firewall, pfSense, Build-VM, .101, .45, .47, Server, "
"Infrastruktur, Verkabelung, DHCP, DNS"
),
"messages": [
{"text": "Build-VM .101: 23G/14C i9-13900H/244G, Pre-Prod .45 bat, Gitea/Doku .47", "room": "6a1c56d4b73efec2bebec2db", "source": "agent_curated"},
{"text": "Susi: 62.238.14.195/Hetzner, SSH bernd, DGX-Spark qwen3-next-80b-fp8, vLLM :7999", "room": "6a1c56d4b73efec2bebec2db", "source": "agent_curated"},
{"text": "Gitea-Repos USER Andreas, git@192.168.180.47:222, SSH-Key gitea_hermes_key", "room": "6a1c56d4b73efec2bebec2db", "source": "agent_curated"},
{"text": "Docker-DNS: /etc/docker/daemon.json mit dns: [192.168.180.1, 8.8.8.8] für Container-Netzwerk", "room": "6a1c56d4b73efec2bebec2db", "source": "agent_curated"},
{"text": "Samba-Vault-Zugriff: benutzerbasierte Authentifizierung valid users = bernd, kein nobody:nogroup", "room": "6a1c56d4b73efec2bebec2db", "source": "agent_curated"},
{"text": "Host-Neustart: Gateway überlebt, Docker-Stack 5/5 UP, beide Plattformen connected", "room": "6a1c56d4b73efec2bebec2db", "source": "agent_curated"},
],
},
# ── #Protonbridge-Plugin ────────────────────────────────────────────
"69f8beaef06dba03be82f9fc": {
"stichworte": (
"Proton Mail Bridge, Hermes Mailschnittstelle, Email-Integration, "
"IMAP, SMTP, ProtonMail, Himalaya, Mail-Gateway, Bridge, "
"PR #39288, Th0rgal, Proton-API, Passwort-Management"
),
"messages": [
{"text": "Proton Mail Bridge: lokaler IMAP/SMTP-Proxy localhost:1143/localhost:1025 — funktioniert heute", "room": "69f8beaef06dba03be82f9fc", "source": "agent_curated"},
{"text": "PR #39288 (Th0rgal): Native Proton-Integration, 1.200 Zeilen, 5 Dateien, noch nicht gemerged", "room": "69f8beaef06dba03be82f9fc", "source": "agent_curated"},
{"text": "Gateway + Himalaya-Strategie: Gateway für IMAP-IDLE-Push, Himalaya CLI für SMTP-Antworten", "room": "69f8beaef06dba03be82f9fc", "source": "agent_curated"},
{"text": "Himalaya: Rust-CLI-Email-Client, TOML-Konfiguration, pipe cat << EOF | himalaya template send", "room": "69f8beaef06dba03be82f9fc", "source": "agent_curated"},
{"text": "Proton Mail REST-API existiert nicht — Bridge-Weg ist der einzig funktionierende Pfad heute", "room": "69f8beaef06dba03be82f9fc", "source": "agent_curated"},
],
},
}