Files
Hermes_rocket.chat_Plugin/plugin/archivar/room_map.py
T
Bernd (Hermes) 78c9a477e0 P-033: Fix Tiebreak-Bug in find_room_by_keywords
Root Cause: room_map.py:314 verwendete strict '>' statt Tiebreak-Comparator.
Bei Score-Tie (z.B. 1:1) entschied Dict-Insertion-Order, nicht Logik.

Fix (Option B, Rainer 2026-08-06):
- Neue Tiebreak-Helper: _get_matched_keywords(), _keyword_room_count(),
  _tiebreak_compare()
- Bei Score-Tie: Raum mit seltenerem Keyword (geringster room_count) gewinnt
- Bei erneutem Tie: laengstes gematchtes Keyword gewinnt
- Bei erneutem Tie: first-seen (stabil)
- Tiebreak gilt fuer Stufe 1 (100%-Keywords) UND Stufe 3 (Kontext-Keywords)

Tests: 6 neue Regressionstests in TestP033Tiebreak
- 'Rocketchat' + 'Dokumentation' -> #Rocketchat-Plugin (nicht #LAN-Doku)
- Nur 'Dokumentation' -> #LAN-Dokumentation (100%-Keyword schlaegt Kontext)
- Nur 'Rocketchat' -> #Rocketchat-Plugin
- Raritaet schlaegt Laenge
- Stable-Sort bei identischen Keywords
- Laenge gewinnt bei gleicher Raritaet

Infra: plugin/conftest.py registriert 'plugin' in sys.modules fuer
standalone-Tests (P-022 Flat-Modul-Pattern)
2026-08-06 21:56:21 +02:00

1257 lines
49 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Room-Map: Single Source of Truth für den thematischen Router.
Lädt, validiert und durchsucht die Raum-Map aus ``room-map.json``.
Ersetzt die bisherigen ``ARCHIVAR_*_ROOM`` Env-Vars durch ein
strukturiertes JSON-Datenmodell.
Usage::
from .room_map import RoomMap, RoomMapValidationError
try:
room_map = RoomMap.load()
room_map.validate(subscribed_ids)
except RoomMapValidationError as e:
logger.fatal("Room map invalid: %s", e)
raise SystemExit(1)
room = room_map.find_room_by_keywords("Das Plugin hat einen Bug")
# → RoomEntry(name="#Rocketchat-Plugin", ...)
"""
from __future__ import annotations
import fcntl
import json
import logging
import os
from dataclasses import dataclass, field
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional, Dict, List
from .keyword_matcher import match_keyword, match_keyword_exact, find_matching_keywords
logger = logging.getLogger(__name__)
# Use absolute import instead of relative import
try:
from config import DEFAULT_MAP_PATH as CONFIG_DEFAULT_MAP_PATH
DEFAULT_MAP_PATH = CONFIG_DEFAULT_MAP_PATH
except ImportError:
# Fallback for testing
DEFAULT_MAP_PATH = "~/.hermes/hermes-agent/data/room-map.json"
# ── Constants ─────────────────────────────────────────────────────────────
# DEFAULT_MAP_PATH is set above via config import or fallback
# ── Data Classes ──────────────────────────────────────────────────────────
@dataclass
class RoomEntry:
"""Ein Raum-Eintrag in der Map."""
room_id: str
"""Rocket.Chat Raum-ID."""
name: str
"""Menschenlesbarer Name (z. B. ``#Rocketchat-Plugin``)."""
theme: str
"""Thema des Raums (ein Satz)."""
description: str = ""
"""Detaillierte Beschreibung des Raums (ca. 200 Wörter)."""
keywords_100: list[str] = field(default_factory=list)
"""100% Evidenz Stichworte für Keyword-Matching."""
keywords_context: list[str] = field(default_factory=list)
"""Kontextabhängige Stichworte für Keyword-Matching."""
catch_all: bool = False
"""True wenn dieser Raum der EINE Catch-All-Raum ist."""
active_status_indikator: bool = True
"""V8.6: Aktivitäts-Indikator — Bot-Status automatisch anzeigen (PresenceEngine)."""
# V8.2: Keyword-Tracking für Lern-Persistenz und Demotion
_keyword_last_matched: Dict[str, str] = field(default_factory=dict)
"""Mapping keyword → ISO timestamp des letzten Matches (für Demotion)."""
_stay_counts: Dict[str, int] = field(default_factory=dict)
"""Mapping keyword → Anzahl 'Hier bleiben' (für Promotion zu keywords_100)."""
@property
def keywords(self) -> list[str]:
"""Legacy property for backward compatibility."""
return self.keywords_context
def match_score(self, text: str) -> int:
"""Return number of keyword matches in *text* (case-insensitive).
Uses morphological matching (stemming, fuzzy) for keywords_100
and exact matching for keywords_context.
Args:
text: The message text to match against.
Returns:
Number of matching keywords (0 if none match).
"""
# 100%-Keywords: morphological matching (stemming, fuzzy)
score_100 = sum(1 for kw in self.keywords_100 if match_keyword(kw, text))
# Context-Keywords: exact matching only (case-insensitive)
score_context = sum(1 for kw in self.keywords_context if match_keyword_exact(kw, text))
return score_100 + score_context
# ── Exception ─────────────────────────────────────────────────────────────
class RoomMapValidationError(Exception):
"""Raised when the room-map.json fails validation at startup."""
# ── P1-1 Fix A: Save-Helfer (Modul-Level) ────────────────────────────────
def _acquire_flock(file_obj, timeout: int = 5) -> None:
"""Erwirbt einen exklusiven fcntl-Lock mit Timeout.
Verwendet non-blocking flock mit Retry-Loop (thread-safe,
kein signal). Maximal *timeout* Sekunden.
Args:
file_obj: Geöffnetes File-Objekt.
timeout: Maximale Wartezeit in Sekunden.
Raises:
TimeoutError: Wenn der Lock nicht innerhalb des Timeouts erworben werden kann.
"""
import time
deadline = time.monotonic() + timeout
while True:
try:
fcntl.flock(file_obj.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
return
except BlockingIOError:
if time.monotonic() >= deadline:
raise TimeoutError(
f"Konnte File-Lock nicht innerhalb von {timeout}s erwerben"
)
time.sleep(0.05)
def _create_backup(path: Path) -> None:
"""Erstellt ein atomares Backup der existierenden Datei.
Kopiert die Datei nach '<path>.bak' via shutil.copy2 + os.replace
für atomaren Replace. No-op wenn die Quelldatei nicht existiert.
Args:
path: Pfad zur zu sichernden Datei.
"""
if not path.exists():
return
bak_path = Path(str(path) + ".bak")
try:
# Schreibe in temporäre Datei, dann atomic replace
tmp_bak = Path(str(bak_path) + ".tmp")
import shutil
shutil.copy2(path, tmp_bak)
os.replace(tmp_bak, bak_path)
logger.debug("Backup erstellt: %s", bak_path)
except OSError as e:
logger.warning(
"RoomMap.save: Konnte Backup nicht erstellen: %s", e
)
# ── RoomMap ───────────────────────────────────────────────────────────────
class RoomMap:
"""Lädt, validiert und durchsucht die Raum-Map.
Die Map ist ein JSON-Dokument (Schema siehe ``room-map.schema.json``).
Sie wird einmalig beim Gateway-Start geladen und danach im Speicher
gehalten. Änderungen an der JSON-Datei zur Laufzeit werden NICHT
automatisch erkannt — ein Gateway-Neustart ist nötig.
"""
def __init__(
self,
rooms: dict[str, RoomEntry],
excluded_room_ids: set[str],
fact_store_path: Path,
version: int = 1,
butler_mode: str = "cognitive",
fact_store_strategy: str = "manual",
fact_store_created_at: Optional[str] = None,
) -> None:
"""Initialize from pre-parsed data.
Use ``RoomMap.load()`` to parse from a JSON file.
"""
self._rooms = rooms
self._excluded_room_ids = excluded_room_ids
self._fact_store_path = fact_store_path
self._version = version
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 ───────────────────────────────────────────────────
@property
def rooms(self) -> dict[str, RoomEntry]:
"""All room entries, keyed by Rocket.Chat room ID."""
return dict(self._rooms)
@property
def catch_all_room(self) -> Optional[RoomEntry]:
"""The ONE catch-all room, or None if not exactly one."""
catch_alls = [r for r in self._rooms.values() if r.catch_all]
return catch_alls[0] if len(catch_alls) == 1 else None
@property
def excluded_room_ids(self) -> set[str]:
"""Room IDs that are excluded from all routing."""
return set(self._excluded_room_ids)
@property
def fact_store_path(self) -> Path:
"""Path for FAKT message storage (filesystem, not a chat room)."""
return self._fact_store_path
@property
def version(self) -> int:
"""Schema version of the loaded map."""
return self._version
@property
def butler_mode(self) -> str:
"""Fix C v7: Butler-Mode - 'cognitive', 'strict', or 'off'."""
return self._butler_mode
def set_butler_mode(self, mode: str) -> None:
"""Fix C v7: Setze den Butler-Mode und persistiere.
Args:
mode: 'cognitive', 'strict', or 'off'.
"""
if mode not in ("cognitive", "strict", "off"):
raise ValueError(f"Invalid 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
# ── Tiebreak Helpers ──────────────────────────────────────────────
def _get_matched_keywords(self, room: RoomEntry, text: str, keyword_type: str) -> list[str]:
"""Return the list of keywords that matched *text* for *room*.
Args:
room: The room to check.
text: The message text.
keyword_type: ``"100"`` for keywords_100 (morphological matching)
or ``"context"`` for keywords_context (exact matching).
Returns:
List of matching keyword strings.
"""
if keyword_type == "100":
return [kw for kw in room.keywords_100 if match_keyword(kw, text)]
else:
return [kw for kw in room.keywords_context if match_keyword_exact(kw, text)]
def _keyword_room_count(self, keyword: str) -> int:
"""Count how many rooms (excluding catch-all) contain *keyword*.
Searches both ``keywords_100`` and ``keywords_context`` across all
non-catch-all rooms. Lower count = rarer keyword = better tiebreak.
Args:
keyword: The keyword to count (case-sensitive, as stored).
Returns:
Number of rooms that have this keyword.
"""
count = 0
for room in self._rooms.values():
if room.catch_all:
continue
if keyword in room.keywords_100 or keyword in room.keywords_context:
count += 1
return count
def _tiebreak_compare(
self,
room_a: RoomEntry,
room_b: RoomEntry,
matched_a: list[str],
matched_b: list[str],
) -> bool:
"""Return True if *room_a* beats *room_b* in a score tie.
Tiebreak rules (Option B, Rainer 2026-08-06):
1. Room whose rarest matched keyword has the lowest *room_count* wins.
2. If still tied: room whose longest matched keyword is longer wins.
3. If still tied: *room_b* stays (stable sort — first seen wins).
Args:
room_a: Challenger room.
room_b: Current best room.
matched_a: Keywords that matched for room_a.
matched_b: Keywords that matched for room_b.
Returns:
True if room_a should replace room_b as the best match.
"""
# Rule 1: Rarest keyword (lowest room_count) wins
rarity_a = min(
(self._keyword_room_count(kw) for kw in matched_a),
default=999,
)
rarity_b = min(
(self._keyword_room_count(kw) for kw in matched_b),
default=999,
)
if rarity_a != rarity_b:
return rarity_a < rarity_b
# Rule 2: Longest matched keyword wins
longest_a = max((len(kw) for kw in matched_a), default=0)
longest_b = max((len(kw) for kw in matched_b), default=0)
if longest_a != longest_b:
return longest_a > longest_b
# Rule 3: Stable — keep current best
return False
# ── Lookup Methods ────────────────────────────────────────────────
def find_room_by_keywords(self, text: str, min_score: int = 1, origin_room_id: Optional[str] = None) -> Optional[RoomEntry]:
"""Find the room with the most keyword matches for *text*.
Uses morphological matching (stemming, fuzzy) for 100%-keywords
and exact matching for context keywords.
At equal scores, tiebreaking favours the room whose matched keyword
is the rarest across the entire room map (lowest room_count), then
the longest matched keyword (Option B, P-033 fix).
Args:
text: The message text to classify.
min_score: Minimum score required to return a room (default: 1).
V8.4.6: Gesenkt von 2 auf 1 — ein einzelnes Kontext-Keyword
reicht für einen Butler-Vorschlag.
origin_room_id: Optional room ID of the message origin for priority matching.
Returns:
The ``RoomEntry`` with the highest match score, or ``None``
if no room has any matching keywords or if the best score
is below the minimum threshold.
"""
# Stufe 1: Prüfe 100% Evidenz Keywords zuerst
# Bei mehreren Räumen mit 100%-Matches: den mit den MEISTEN Treffern nehmen.
# Bei Score-Tie: Tiebreak per Keyword-Rarität (P-033).
# Catch-All-Räume werden in Stufe 1 NICHT berücksichtigt
# (100%-Keywords auf Catch-All sind für Auto-Route gedacht, nicht für Keyword-Match)
best_100_room: Optional[RoomEntry] = None
best_100_score: int = 0
best_100_matched: list[str] = []
for room in self._rooms.values():
if room.catch_all:
continue
matched = self._get_matched_keywords(room, text, "100")
score_100 = len(matched)
if score_100 > best_100_score:
best_100_score = score_100
best_100_room = room
best_100_matched = matched
elif score_100 == best_100_score and score_100 > 0:
# P-033: Tiebreak per Keyword-Rarität
if self._tiebreak_compare(room, best_100_room, matched, best_100_matched):
best_100_room = room
best_100_matched = matched
# Wenn mindestens ein 100%-Match existiert → sofort diesen Raum zurückgeben
if best_100_room is not None and best_100_score > 0:
return best_100_room
# Stufe 2: Origin-Priorität mit kontextabhängigen Keywords
# Origin-Priorität gilt NUR für context-Keywords (100% schlagen immer durch)
# V8.4.6: Catch-All-Räume sind in Stufe 2 als Butler-Ziele erlaubt
if origin_room_id is not None and origin_room_id in self._rooms:
origin_room = self._rooms[origin_room_id]
# Prüfe kontextabhängige Keywords im Ursprungsraum
# (auch Catch-All-Räume — sie können Kontext-Keywords haben)
# Context-Keywords: exaktes Matching (kein Stemming/Fuzzy)
context_score = sum(1 for kw in origin_room.keywords_context if match_keyword_exact(kw, text))
if context_score >= min_score:
return origin_room
# Stufe 3: Globaler Scan mit kontextabhängigen Keywords
# V8.4.6: Catch-All-Räume sind in Stufe 3 als Butler-Ziele erlaubt.
# Catch-All als Keyword-Match-Ziel war für 100%-Auto-Route blockiert (Stufe 1).
# Für Kontext-Keywords (Stufe 3) sind Catch-All-Räume valide Butler-Ziele.
# P-033: Tiebreak per Keyword-Rarität bei Score-Tie.
best_room: Optional[RoomEntry] = None
best_score: int = 0
best_matched: list[str] = []
for room in self._rooms.values():
matched = self._get_matched_keywords(room, text, "context")
context_score = len(matched)
if context_score > best_score:
best_score = context_score
best_room = room
best_matched = matched
elif context_score == best_score and context_score > 0:
# P-033: Tiebreak per Keyword-Rarität
if self._tiebreak_compare(room, best_room, matched, best_matched):
best_room = room
best_matched = matched
if best_room is not None and best_score >= min_score:
return best_room
return None
def is_100_percent_match(self, text: str, room: RoomEntry) -> bool:
"""Check if *text* contains any 100%-evidence keywords for *room*.
Uses morphological matching (stemming, fuzzy) for robust matching
against plural forms, case declensions, and minor typos.
Returns True if at least one keywords_100 entry matches.
Used by the router to distinguish 100% keyword matches (auto-route, no Butler)
from context keyword matches (Butler asks, learning opportunity).
"""
return any(match_keyword(kw, text) for kw in room.keywords_100)
def calculate_weighted_score(self, text: str, room: RoomEntry) -> float:
"""
Berechnet einen gewichteten Score für ein Text-Raum-Paar.
Args:
text: Der zu bewertende Text
room: Der zu bewertende Raum
Returns:
Gewichteter Score (0.0 - 1.0)
"""
# TODO: Diese Methode wird vom ArchivarState aufgerufen, wenn
# das selbstlernende Keyword-Gewicht-System aktiv ist
# Momentan verwenden wir eine einfache Keyword-Zählung
text_lower = text.lower()
matched_keywords = [kw for kw in room.keywords_context if kw.lower() in text_lower]
if not matched_keywords:
return 0.0
# Einfache Gewichtung: Anzahl der Treffer geteilt durch Anzahl der Keywords
# In der vollständigen Implementierung würden wir hier die gelernten Gewichte verwenden
return len(matched_keywords) / len(room.keywords_context) if room.keywords_context else 0.0
def is_excluded(self, room_id: str) -> bool:
"""True if *room_id* is in the excluded list (e.g. Multi-Agent-Raum)."""
return room_id in self._excluded_room_ids
def get_room_by_id(self, room_id: str) -> Optional[RoomEntry]:
"""Hole einen Raum anhand seiner ID.
Args:
room_id: Die Rocket.Chat Raum-ID
Returns:
RoomEntry wenn gefunden, sonst None
"""
return self._rooms.get(room_id)
# ── Validation ────────────────────────────────────────────────────
def validate(self, subscribed_ids: Optional[set[str]] = None) -> list[str]:
"""Validate the map against subscription reality.
Args:
subscribed_ids: The bot's current subscribed room IDs.
When provided, checks that the catch-all room and all
mapped rooms are in the subscription list.
Returns:
List of error messages (empty = valid).
Raises:
RoomMapValidationError: For fatal errors (0 or >1 catch-all,
catch-all in excluded rooms).
"""
errors: list[str] = []
# Count catch-all rooms
catch_alls = [r for r in self._rooms.values() if r.catch_all]
if len(catch_alls) == 0:
raise RoomMapValidationError(
"FATAL: No catch_all room defined in room-map.json. "
"Exactly one room must have 'catch_all: true'."
)
if len(catch_alls) > 1:
names = ", ".join(r.name for r in catch_alls)
raise RoomMapValidationError(
f"FATAL: Multiple catch_all rooms: {names}. "
"Exactly one room must have 'catch_all: true'."
)
catch_all = catch_alls[0]
# Catch-all must not be in excluded rooms
if catch_all.room_id in self._excluded_room_ids:
raise RoomMapValidationError(
f"FATAL: Catch-all room '{catch_all.name}' is in excluded_rooms. "
"The catch-all room cannot be excluded from routing."
)
# Subscription checks (non-fatal warnings)
if subscribed_ids is not None:
if catch_all.room_id not in subscribed_ids:
errors.append(
f"Catch-all room '{catch_all.name}' "
f"({catch_all.room_id[:8]}...) is not in subscribed rooms"
)
for room in self._rooms.values():
if room.room_id not in subscribed_ids:
errors.append(
f"Room '{room.name}' ({room.room_id[:8]}...) "
"is not in subscribed rooms"
)
return errors
# ── Factory ───────────────────────────────────────────────────────
@classmethod
def load(cls, path: Optional[Path] = None) -> RoomMap:
"""Load and validate a room-map.json file.
Args:
path: Path to the JSON file. Defaults to
``ARCHIVAR_ROOM_MAP_PATH`` env var or
``~/.hermes/hermes-agent/data/room-map.json``.
Returns:
A validated ``RoomMap`` instance.
Raises:
FileNotFoundError: If the map file does not exist.
json.JSONDecodeError: If the file is not valid JSON.
RoomMapValidationError: If the map fails semantic validation.
"""
if path is None:
env_path = os.getenv("ARCHIVAR_ROOM_MAP_PATH", "").strip()
if env_path:
path = Path(env_path)
else:
path = Path(os.path.expanduser(DEFAULT_MAP_PATH))
if not path.exists():
raise FileNotFoundError(
f"Room map not found at {path}. "
"Create one with room-map.schema.json as template."
)
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
return cls._from_dict(data)
def add_or_update_room(self, room_id: str, name: str, theme: str = "", description: str = "", keywords_100: Optional[list] = None, keywords_context: Optional[list] = None, catch_all: bool = False) -> None:
"""Fügt Raum zur In-Memory-Map hinzu ODER aktualisiert bestehenden.
Args:
room_id: Rocket.Chat Raum-ID
name: Menschenlesbarer Name (z.B. "#Rocketchat-Plugin")
theme: Thema des Raums (ein Satz)
description: Detaillierte Beschreibung des Raums (ca. 200 Wörter)
keywords_100: 100% Evidenz Stichworte für Keyword-Matching
keywords_context: Kontextabhängige Stichworte für Keyword-Matching
catch_all: True wenn dieser Raum der EINE Catch-All-Raum ist
"""
if keywords_100 is None:
keywords_100 = []
if keywords_context is None:
keywords_context = []
# Erstelle oder aktualisiere den RoomEntry
self._rooms[room_id] = RoomEntry(
room_id=room_id,
name=name,
theme=theme,
description=description,
keywords_100=keywords_100,
keywords_context=keywords_context,
catch_all=catch_all
)
# Wenn dies ein Catch-All-Raum ist, stellen wir sicher, dass es nur einen gibt
if catch_all:
for rid, room in self._rooms.items():
if rid != room_id and room.catch_all:
# Entferne catch_all von anderen Räumen
room.catch_all = False
# Version erhöhen, damit is_stale() im FAISS-Index erkennt,
# dass die RoomMap geändert wurde und der Index neu gebaut werden muss.
self._version += 1
def reload(self, path: Optional[Path] = None) -> None:
"""Lädt room-map.json neu von Disk.
Aktualisiert die In-Memory-Repräsentation.
Kein Gateway-Neustart nötig.
Args:
path: Pfad zur JSON-Datei. Standardwert aus Umgebungsvariablen oder DEFAULT_MAP_PATH.
"""
if path is None:
env_path = os.getenv("ARCHIVAR_ROOM_MAP_PATH", "").strip()
if env_path:
path = Path(env_path)
else:
path = Path(os.path.expanduser(DEFAULT_MAP_PATH))
if path.exists():
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
# Parse die neue Daten und aktualisiere die Instanz
new_map = self._from_dict(data)
self._rooms = new_map._rooms
self._excluded_room_ids = new_map._excluded_room_ids
self._fact_store_path = new_map._fact_store_path
self._version = new_map._version
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
def save(room_map: 'RoomMap', path: Optional[Path] = None, force: bool = False) -> None:
"""Speichert die RoomMap in eine JSON-Datei mit File-Lock.
Verwendet ``fcntl.flock`` (exklusiver Lock) um parallele
Schreibzugriffe zu verhindern. Blockiert maximal 5 Sekunden.
P1-1 Fix A: Refuse-Guard mit ID-Set-Differenz, TOCTOU-Schutz
durch Lock-VOR-Lesen, Backup-Mechanismus (.bak), und force-Parameter.
Args:
room_map: Die zu speichernde RoomMap-Instanz
path: Pfad zur JSON-Datei. Standardwert aus Umgebungsvariablen oder DEFAULT_MAP_PATH.
force: Wenn True, wird der Refuse-Guard umgangen (für administrative
Aufrufe wie Onboarding-Reset).
"""
if path is None:
env_path = os.getenv("ARCHIVAR_ROOM_MAP_PATH", "").strip()
if env_path:
path = Path(env_path)
else:
path = Path(os.path.expanduser(DEFAULT_MAP_PATH))
# Erstelle das Verzeichnis falls es nicht existiert
path.parent.mkdir(parents=True, exist_ok=True)
# Konvertiere die Map in ein serialisierbares Dict
data = {
"version": room_map._version,
"rooms": {},
"excluded_rooms": list(room_map._excluded_room_ids),
"fact_store_path": str(room_map._fact_store_path),
"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():
data["rooms"][room_id] = {
"name": room_entry.name,
"theme": room_entry.theme,
"description": room_entry.description,
"keywords_100": room_entry.keywords_100,
"keywords_context": room_entry.keywords_context,
"catch_all": room_entry.catch_all,
"active_status_indikator": room_entry.active_status_indikator,
# V8.2.1 A3: Persistiere Tracking-Felder
"_stay_counts": room_entry._stay_counts,
"_keyword_last_matched": room_entry._keyword_last_matched,
}
# P1-1 Fix A: TOCTOU-geschützter Refuse-Guard mit ID-Set-Differenz.
# Lock wird VOR dem Lesen erworben, nicht erst beim Schreiben.
# Öffne im read+write Modus für Lock + mögliches Schreiben.
file_exists = path.exists()
if file_exists:
try:
with open(path, "r+", encoding="utf-8") as f:
# Lock erwerben (max 5s Timeout via non-blocking + retry)
_acquire_flock(f, timeout=5)
# Unter Lock: Disk-Inhalt lesen
f.seek(0)
try:
disk_data = json.load(f)
except json.JSONDecodeError:
logger.warning(
"RoomMap.save: Disk-Inhalt ist kein gültiges JSON. "
"Überschreibe mit neuer Map."
)
disk_data = None
if disk_data is not None and not force:
disk_room_ids = set(disk_data.get("rooms", {}).keys())
mem_room_ids = set(room_map._rooms.keys())
# ID-Set-Differenz: Wenn Disk-IDs nicht Teilmenge
# von In-Memory-IDs sind → refuse
if not disk_room_ids.issubset(mem_room_ids):
missing_from_memory = disk_room_ids - mem_room_ids
logger.warning(
"RoomMap.save REFUSED: Disk-Räume %s fehlen in "
"In-Memory-Map (Disk: %d Räume, Memory: %d Räume). "
"Überschreiben verweigert um Datenverlust zu vermeiden. "
"Nutze force=True für administrative Überschreibung.",
sorted(missing_from_memory),
len(disk_room_ids), len(mem_room_ids),
)
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
return
# P1-1 Fix A: Backup vor dem Schreiben (.bak)
_create_backup(path)
# Schreibe neue Daten (seek+truncate+write unter Lock)
f.seek(0)
f.truncate()
json.dump(data, f, indent=2, ensure_ascii=False)
f.flush()
os.fsync(f.fileno())
fcntl.flock(f.fileno(), fcntl.LOCK_UN)
except FileNotFoundError:
# Datei wurde zwischen exists()-Check und open() gelöscht —
# falle durch zu Neuanlage
file_exists = False
if not file_exists:
# Neue Datei anlegen (kein Lock nötig, da Datei nicht existiert)
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
f.flush()
os.fsync(f.fileno())
# ── V8.2: A1 — Onboarding-Widerspruchsprüfung ──────────────────────
def check_keyword_conflicts(
self,
keywords: list[str],
exclude_room_id: str = "",
keyword_type: str = "100",
) -> list[dict]:
"""Prüft ob Keywords bereits in anderen Räumen existieren.
Args:
keywords: Liste der zu prüfenden Keywords.
exclude_room_id: Raum-ID die ausgeschlossen wird (der eigene Raum).
keyword_type: Typ der neuen Keywords: "100" (100%-Keyword) oder
"context" (Kontext-Keyword).
Returns:
Liste von Konflikten:
[{"keyword": str, "room_id": str, "room_name": str,
"conflict_type": str, "existing_type": str}]
conflict_type:
- "CRITICAL": 100%-Keyword kollidiert mit 100%-Keyword
- "WARNING": 100%-Keyword kollidiert mit Kontext-Keyword
- "INFO": Kontext-Keyword kollidiert mit 100%-Keyword
- "OK": Kontext-Keyword kollidiert mit Kontext-Keyword
"""
conflicts = []
for room_id, room in self._rooms.items():
if room_id == exclude_room_id:
continue
if room.catch_all:
continue
for kw in keywords:
kw_lower = kw.lower()
# Prüfe gegen 100%-Keywords im existierenden Raum
for existing_kw in room.keywords_100:
if existing_kw.lower() == kw_lower:
if keyword_type == "100":
conflict_type = "CRITICAL"
else:
conflict_type = "INFO"
conflicts.append({
"keyword": kw,
"room_id": room_id,
"room_name": room.name,
"conflict_type": conflict_type,
"existing_type": "100",
})
break
else:
# Prüfe gegen Kontext-Keywords im existierenden Raum
for existing_kw in room.keywords_context:
if existing_kw.lower() == kw_lower:
if keyword_type == "100":
conflict_type = "WARNING"
else:
conflict_type = "OK"
conflicts.append({
"keyword": kw,
"room_id": room_id,
"room_name": room.name,
"conflict_type": conflict_type,
"existing_type": "context",
})
break
return conflicts
# ── V8.2: A3 — Lernfunktion-Persistenz ──────────────────────────────
def add_keyword_context(self, room_id: str, keyword: str) -> bool:
"""Fügt ein Keyword zu keywords_context hinzu.
Normalisiert: strip().lower(). Validiert Länge (2-30), keine Leerzeichen,
kein Duplikat.
Args:
room_id: Die Raum-ID.
keyword: Das neue kontextabhängige Keyword.
Returns:
True wenn hinzugefügt, False bei Validierungsfehler oder nicht-existenter room_id.
"""
room = self._rooms.get(room_id)
if room is None:
return False
kw = keyword.strip().lower()
if len(kw) < 2 or len(kw) > 30:
return False
if " " in kw:
return False
if kw in (k.lower() for k in room.keywords_context):
return False
room.keywords_context.append(kw)
self._version += 1
return True
def remove_keyword_context(self, room_id: str, keyword: str) -> bool:
"""Entfernt ein Keyword aus keywords_context.
Args:
room_id: Die Raum-ID.
keyword: Das zu entfernende Keyword.
Returns:
True wenn entfernt, False wenn nicht vorhanden oder room_id nicht existiert.
"""
room = self._rooms.get(room_id)
if room is None:
return False
kw_lower = keyword.strip().lower()
for i, kw in enumerate(room.keywords_context):
if kw.lower() == kw_lower:
room.keywords_context.pop(i)
self._version += 1
return True
return False
# ── Phase 1: Schreib-API für Onboarding Review-Flow ─────────────────
def set_theme(self, room_id: str, theme: str) -> None:
"""Setzt das Theme eines Raums.
Args:
room_id: Die Raum-ID.
theme: Das neue Theme (darf nicht leer oder nur Whitespace sein).
Raises:
KeyError: Wenn die room_id nicht existiert.
ValueError: Wenn theme leer oder nur Whitespace ist.
"""
if room_id not in self._rooms:
raise KeyError(f"Raum '{room_id}' existiert nicht in der Room-Map")
if not theme.strip():
raise ValueError("Theme darf nicht leer sein")
self._rooms[room_id].theme = theme.strip()
# Theme-Änderung erfordert KEINEN FAISS-Rebuild (Theme nicht im Vektor-Index)
self._version += 1
def add_keyword_100(self, room_id: str, keyword: str) -> bool:
"""Fügt ein Keyword zu keywords_100 hinzu.
Normalisiert: strip().lower(). Validiert Länge (2-30), keine Leerzeichen,
kein Duplikat.
Args:
room_id: Die Raum-ID.
keyword: Das neue 100%-Keyword.
Returns:
True wenn hinzugefügt, False bei Validierungsfehler oder nicht-existenter room_id.
"""
room = self._rooms.get(room_id)
if room is None:
return False
kw = keyword.strip().lower()
if len(kw) < 2 or len(kw) > 30:
return False
if " " in kw:
return False
if kw in (k.lower() for k in room.keywords_100):
return False
room.keywords_100.append(kw)
self._version += 1
return True
def remove_keyword_100(self, room_id: str, keyword: str) -> bool:
"""Entfernt ein Keyword aus keywords_100.
Args:
room_id: Die Raum-ID.
keyword: Das zu entfernende Keyword.
Returns:
True wenn entfernt, False wenn nicht vorhanden oder room_id nicht existiert.
"""
room = self._rooms.get(room_id)
if room is None:
return False
kw_lower = keyword.strip().lower()
for i, kw in enumerate(room.keywords_100):
if kw.lower() == kw_lower:
room.keywords_100.pop(i)
self._version += 1
return True
return False
def remove_room(self, room_id: str) -> None:
"""Fügt einen Raum zu excluded_room_ids hinzu (Ausschluss-Pattern).
Der Raum bleibt in rooms{} erhalten (nicht gelöscht — rückgängig machbar).
Catch-All-Raum kann nicht entfernt werden.
Args:
room_id: Die Raum-ID.
Raises:
KeyError: Wenn die room_id nicht existiert.
ValueError: Wenn der Raum der Catch-All-Raum ist.
"""
if room_id not in self._rooms:
raise KeyError(f"Raum '{room_id}' existiert nicht in der Room-Map")
if self._rooms[room_id].catch_all:
raise ValueError(
f"Catch-All-Raum '{self._rooms[room_id].name}' kann nicht entfernt werden"
)
self._excluded_room_ids.add(room_id)
self._version += 1
def increment_stay_count(self, room_id: str, keyword: str) -> int:
"""Inkrementiert den stay-Count für ein Keyword.
Args:
room_id: Die Raum-ID.
keyword: Das Keyword.
Returns:
Aktueller Count nach Inkrement.
"""
room = self._rooms.get(room_id)
if room is None:
return 0
count = room._stay_counts.get(keyword, 0) + 1
room._stay_counts[keyword] = count
return count
def promote_to_keywords_100(self, room_id: str, keyword: str) -> bool:
"""Promoted ein Keyword von keywords_context zu keywords_100.
Args:
room_id: Die Raum-ID.
keyword: Das zu promotende Keyword.
Returns:
True wenn erfolgreich promoted.
"""
room = self._rooms.get(room_id)
if room is None:
return False
kw_lower = keyword.lower()
# Aus keywords_context entfernen
room.keywords_context = [
kw for kw in room.keywords_context if kw.lower() != kw_lower
]
# Zu keywords_100 hinzufügen (wenn nicht schon da)
if kw_lower not in (kw.lower() for kw in room.keywords_100):
room.keywords_100.append(keyword)
# Stay-Count zurücksetzen
room._stay_counts.pop(keyword, None)
self._version += 1
return True
def set_keyword_last_matched(
self, room_id: str, keyword: str, timestamp: str
) -> bool:
"""Setzt den last_matched-Timestamp für ein Keyword.
Args:
room_id: Die Raum-ID.
keyword: Das Keyword.
timestamp: ISO-Format Timestamp.
Returns:
True wenn gesetzt.
"""
room = self._rooms.get(room_id)
if room is None:
return False
room._keyword_last_matched[keyword] = timestamp
return True
def demote_stale_keywords(self, max_age_days: int = 90) -> int:
"""Demoted keywords_100 → keywords_context wenn länger als
max_age_days kein Match.
Rainer Auflage P2: Demotion-Mechanismus.
Args:
max_age_days: Maximale Tage ohne Match bevor Demotion.
Returns:
Anzahl der demoted Keywords.
"""
now = datetime.now()
demoted = 0
for room in self._rooms.values():
if room.catch_all:
continue
to_demote = []
for kw in list(room.keywords_100):
last_match_str = room._keyword_last_matched.get(kw)
if last_match_str:
try:
last_match = datetime.fromisoformat(last_match_str)
if (now - last_match) > timedelta(days=max_age_days):
to_demote.append(kw)
except (ValueError, TypeError):
# Kein gültiger Timestamp → als stale behandeln
to_demote.append(kw)
else:
# Kein last_matched gesetzt → initial, nicht demoten
# Setze initialen Timestamp
room._keyword_last_matched[kw] = now.isoformat()
for kw in to_demote:
room.keywords_100.remove(kw)
if kw.lower() not in (k.lower() for k in room.keywords_context):
room.keywords_context.append(kw)
room._keyword_last_matched.pop(kw, None)
demoted += 1
if demoted > 0:
self._version += 1
return demoted
@classmethod
def _from_dict(cls, data: dict) -> RoomMap:
"""Parse a deserialized map dict into a ``RoomMap`` instance."""
version = data.get("version", 1)
# Parse rooms
rooms: dict[str, RoomEntry] = {}
for room_id, room_data in data.get("rooms", {}).items():
# Abwärtskompatibilität: Wenn keywords_100 fehlt (alte room-map.json),
# alte keywords-Liste als keywords_context interpretieren, keywords_100 bleibt leer
if "keywords_100" in room_data:
# Neue Struktur (Version 2+)
keywords_100 = room_data.get("keywords_100", [])
keywords_context = room_data.get("keywords_context", [])
else:
# Alte Struktur (Version 1) - Abwärtskompatibilität
keywords_100 = []
keywords_context = room_data.get("keywords", [])
rooms[room_id] = RoomEntry(
room_id=room_id,
name=room_data.get("name", room_id),
theme=room_data.get("theme", ""),
description=room_data.get("description", ""),
keywords_100=keywords_100,
keywords_context=keywords_context,
catch_all=room_data.get("catch_all", False),
active_status_indikator=room_data.get("active_status_indikator", True),
)
# V8.2.1 A3: Tracking-Felder aus JSON deserialisieren
if "_stay_counts" in room_data:
rooms[room_id]._stay_counts = room_data["_stay_counts"]
if "_keyword_last_matched" in room_data:
rooms[room_id]._keyword_last_matched = room_data["_keyword_last_matched"]
excluded = set(data.get("excluded_rooms", []))
fact_store = Path(
os.path.expanduser(data.get("fact_store_path", "~/archivar_docs"))
)
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(
rooms=rooms,
excluded_room_ids=excluded,
fact_store_path=fact_store,
version=version,
butler_mode=butler_mode,
fact_store_strategy=fact_store_strategy,
fact_store_created_at=fact_store_created_at,
)
# ── Migration from Legacy Env Vars ────────────────────────────────────────
def _migrate_from_env_vars() -> Optional[dict]:
"""Build a temporary map dict from deprecated ARCHIVAR_*_ROOM env vars.
Logs a WARNING that the env var approach is deprecated and the user
should migrate to room-map.json.
Returns:
A dict suitable for ``RoomMap._from_dict()``, or ``None`` if
no legacy env vars are set.
"""
fakt = os.getenv("ARCHIVAR_FAKT_ROOM", "").strip()
frage = os.getenv("ARCHIVAR_FRAGE_ROOM", "").strip()
alarm = os.getenv("ARCHIVAR_ALARM_ROOM", "").strip()
catchall = os.getenv("ARCHIVAR_CATCHALL_ROOM", "").strip()
project_json = os.getenv("ARCHIVAR_PROJECT_ROOMS", "").strip()
has_any = any([fakt, frage, alarm, catchall, project_json])
if not has_any:
return None
logger.warning(
"Using deprecated ARCHIVAR_*_ROOM env vars. "
"Please migrate to room-map.json. "
"See docs/archivar-architektur.md for migration guide."
)
rooms: dict[str, dict] = {}
# Catch-all room
if catchall:
rooms[catchall] = {
"name": "Catch-All (legacy)",
"theme": "Legacy catch-all from ARCHIVAR_CATCHALL_ROOM",
"description": "Legacy catch-all room for all topics without their own room.",
"keywords": [],
"catch_all": True,
}
# ALARM room
if alarm and alarm != catchall:
rooms[alarm] = {
"name": "ALARM Room (legacy)",
"theme": "Legacy alarm room from ARCHIVAR_ALARM_ROOM",
"description": "Legacy alarm room for critical alerts and urgent notifications.",
"keywords": ["alarm", "dringend", "sofort", "kritisch", "ausfall"],
"catch_all": False,
}
# FAKT room (legacy — now goes to doc_store, but keep for migration)
if fakt and fakt != catchall and fakt != alarm:
rooms[fakt] = {
"name": "FAKT Room (legacy)",
"theme": "Legacy fakt room from ARCHIVAR_FAKT_ROOM",
"description": "Legacy fakt room for documentation and factual information.",
"keywords": ["dokumentation", "fakt", "info"],
"catch_all": False,
}
# FRAGE room(s)
if frage and frage != catchall:
rooms[frage] = {
"name": "FRAGE Room (legacy)",
"theme": "Legacy frage room from ARCHIVAR_FRAGE_ROOM",
"description": "Legacy question room for help requests and problem solving.",
"keywords": ["frage", "hilfe", "problem"],
"catch_all": False,
}
# Project-specific rooms
if project_json:
try:
projects = json.loads(project_json)
for proj_key, proj_room_id in projects.items():
if proj_room_id not in rooms:
rooms[proj_room_id] = {
"name": f"Project: {proj_key} (legacy)",
"theme": f"Legacy project room for {proj_key}",
"description": f"Legacy project room for {proj_key} related discussions and tasks.",
"keywords": [proj_key],
"catch_all": False,
}
except json.JSONDecodeError:
logger.warning("Failed to parse ARCHIVAR_PROJECT_ROOMS JSON")
return {
"version": 1,
"rooms": rooms,
"excluded_rooms": [],
"fact_store_path": os.path.expanduser("~/archivar_docs"),
}