P1-Fix: build_help_text Längenbegrenzung + RoomMap.save Refuse-Guard

- build_help_text: Wenn Hilfe-Text > 4000 Zeichen, wird room_map_summary
  durch Platzhalter ersetzt. Verhindert HTTP 400 bei Rocket.Chat
  (Payload-Limit ~5000 Zeichen, ::hilfe mit 5 Räumen war 4571 Zeichen).
- RoomMap.save: Refuse-Guard prüft vor dem Schreiben, ob die existierende
  Disk-Datei mehr Räume enthält als die In-Memory-Map. Verweigert das
  Schreiben mit Warning wenn Disk > In-Memory. Verhindert Datenverlust
  beim Multiroom-Toggle (false→true schrieb leere Map).
- Tests: test_build_help_text_length_limit (max 4000 Zeichen),
  test_build_help_text_keeps_summary_when_short,
  TestRoomMapSaveRefuseGuard (4 Tests: refuse, allow-more, allow-equal,
  allow-no-disk).

Closes: Rainers Review P1-Fixes 1+2+3
This commit is contained in:
Bernd (Hermes)
2026-07-25 20:12:17 +02:00
parent b4ba67e80b
commit 1c53a9fe07
4 changed files with 307 additions and 2 deletions
+18 -1
View File
@@ -357,7 +357,24 @@ def build_help_text(
"Moderatorenrechte in den Themenräumen haben." "Moderatorenrechte in den Themenräumen haben."
) )
return "\n".join(lines) result = "\n".join(lines)
# P1-Fix: Rocket.Chat hat ein Payload-Limit von ~5000 Zeichen.
# Wenn der Hilfe-Text > 4000 Zeichen ist, lasse die room_map_summary
# weg und ersetze sie durch einen kurzen Hinweis.
MAX_HELP_LENGTH = 4000
if len(result) > MAX_HELP_LENGTH and room_map_summary:
# Finde den Index der room_map_summary in lines und ersetze sie
for i, line in enumerate(lines):
if line == room_map_summary:
lines[i] = (
"Raum-Map-Übersicht aus Platzgründen weggelassen "
"(> 4000 Zeichen). `::status` für Details."
)
break
result = "\n".join(lines)
return result
def build_status_text( def build_status_text(
+26 -1
View File
@@ -515,6 +515,11 @@ class RoomMap:
Verwendet ``fcntl.flock`` (exklusiver Lock) um parallele Verwendet ``fcntl.flock`` (exklusiver Lock) um parallele
Schreibzugriffe zu verhindern. Blockiert maximal 5 Sekunden. Schreibzugriffe zu verhindern. Blockiert maximal 5 Sekunden.
P1-Fix: Refuse-Guard — verweigert das Schreiben, wenn die
existierende Datei auf Disk mehr Räume enthält als die
In-Memory-Map. Verhindert, dass eine leere/kleinere Map
eine konfigurierte überschreibt (z.B. beim Multiroom-Toggle).
Args: Args:
room_map: Die zu speichernde RoomMap-Instanz room_map: Die zu speichernde RoomMap-Instanz
path: Pfad zur JSON-Datei. Standardwert aus Umgebungsvariablen oder DEFAULT_MAP_PATH. path: Pfad zur JSON-Datei. Standardwert aus Umgebungsvariablen oder DEFAULT_MAP_PATH.
@@ -525,7 +530,27 @@ class RoomMap:
path = Path(env_path) path = Path(env_path)
else: else:
path = Path(os.path.expanduser(DEFAULT_MAP_PATH)) path = Path(os.path.expanduser(DEFAULT_MAP_PATH))
# P1-Fix: Refuse-Guard — prüfe ob Disk-Inhalt mehr Räume hat als In-Memory
if path.exists():
try:
with open(path, "r", encoding="utf-8") as f:
disk_data = json.load(f)
disk_room_count = len(disk_data.get("rooms", {}))
mem_room_count = len(room_map._rooms)
if disk_room_count > mem_room_count:
logger.warning(
"RoomMap.save REFUSED: Disk hat %d Räume, In-Memory nur %d. "
"Überschreiben verweigert um Datenverlust zu vermeiden.",
disk_room_count, mem_room_count,
)
return
except (json.JSONDecodeError, OSError) as e:
logger.warning(
"RoomMap.save: Konnte Disk-Inhalt nicht lesen für Refuse-Guard: %s. "
"Fahre mit Schreiben fort.", e
)
# Erstelle das Verzeichnis falls es nicht existiert # Erstelle das Verzeichnis falls es nicht existiert
path.parent.mkdir(parents=True, exist_ok=True) path.parent.mkdir(parents=True, exist_ok=True)
@@ -262,6 +262,61 @@ class TestBuildHelpText:
assert "continue" in text assert "continue" in text
assert "Natürliche Sprach-Befehle" in text assert "Natürliche Sprach-Befehle" in text
def test_build_help_text_length_limit(self):
"""P1-Fix: Hilfe-Text darf 4000 Zeichen nicht überschreiten."""
from archivar.inline_commands import (
InlineCommandRegistry,
build_help_text,
)
registry = InlineCommandRegistry()
async def dummy(room_id, args):
return "ok"
# Registriere viele Befehle um einen langen Text zu erzeugen
all_cmds = [
("sethome", "Standard"), ("reset", "Standard"), ("busy", "Standard"),
("allowalways", "Standard"), ("commands", "Info"), ("restart", "Gateway"),
("update", "Gateway"),
("setfakt", "Konfiguration"), ("hilfe", "Hilfe"), ("status", "Hilfe"),
("multiroom", "Plugin"), ("onboarding", "Plugin"), ("curate", "Plugin"),
]
for name, cat in all_cmds:
registry.register(name, dummy, f"Help for {name}", category=cat)
# Erzeuge eine große room_map_summary (simuliert 5 Räume)
big_summary = "Rocket.Chat Raum-Map:\n"
for i in range(5):
big_summary += (
f" {i+1}. #Raum{i+1} (room_id_{i+1}...) — "
f"Thema: Dies ist ein sehr langer Beschreibungstext für Raum {i+1} "
f"um die Länge der Hilfeseite künstlich zu erhöhen\n"
)
text = build_help_text(registry, room_map_summary=big_summary)
assert len(text) <= 4000, (
f"Hilfe-Text ist {len(text)} Zeichen lang, "
f"maximal erlaubt sind 4000"
)
def test_build_help_text_keeps_summary_when_short(self):
"""P1-Fix: Kurze room_map_summary bleibt erhalten."""
from archivar.inline_commands import (
InlineCommandRegistry,
build_help_text,
)
registry = InlineCommandRegistry()
async def dummy(room_id, args):
return "ok"
registry.register("hilfe", dummy, "Zeigt Hilfeseite", category="Hilfe")
short_summary = "Raum-Map: 1 Raum"
text = build_help_text(registry, room_map_summary=short_summary)
assert "Raum-Map: 1 Raum" in text
assert len(text) <= 4000
class TestBuildStatusText: class TestBuildStatusText:
"""Tests für build_status_text.""" """Tests für build_status_text."""
+208
View File
@@ -516,3 +516,211 @@ class TestLLMLookup:
result = room_map.find_room_by_keywords("Wie funktioniert das BAT Trading-Signal?") result = room_map.find_room_by_keywords("Wie funktioniert das BAT Trading-Signal?")
assert result is not None assert result is not None
assert result.name == "#BAT" assert result.name == "#BAT"
# ── P1-Fix: RoomMap.save Refuse-Guard ──────────────────────────────────────
class TestRoomMapSaveRefuseGuard:
"""P1-Fix: RoomMap.save verweigert Schreiben wenn Disk > In-Memory."""
def test_save_refuses_when_disk_has_more_rooms(self):
"""save() verweigert wenn Disk mehr Räume hat als In-Memory."""
import tempfile
from pathlib import Path
# Erstelle eine Disk-Datei mit 3 Räumen
disk_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r2": {"name": "#Room2", "theme": "t2", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r3": {"name": "#Room3", "theme": "t3", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
tmpdir = tempfile.TemporaryDirectory()
try:
map_path = Path(tmpdir.name) / "room-map.json"
with open(map_path, "w") as f:
json.dump(disk_data, f)
# Erstelle eine In-Memory-Map mit nur 1 Raum (kleiner als Disk)
small_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
small_map = RoomMap._from_dict(small_data)
# Versuche zu speichern — sollte verweigert werden
RoomMap.save(small_map, path=map_path)
# Disk sollte unverändert sein (3 Räume)
with open(map_path, "r") as f:
saved_data = json.load(f)
assert len(saved_data["rooms"]) == 3, (
f"Disk sollte 3 Räume haben, hat aber {len(saved_data['rooms'])}"
)
finally:
tmpdir.cleanup()
def test_save_allows_when_memory_has_more_rooms(self):
"""save() erlaubt Schreiben wenn In-Memory mehr Räume hat als Disk."""
import tempfile
from pathlib import Path
# Erstelle eine Disk-Datei mit 1 Raum
disk_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
tmpdir = tempfile.TemporaryDirectory()
try:
map_path = Path(tmpdir.name) / "room-map.json"
with open(map_path, "w") as f:
json.dump(disk_data, f)
# Erstelle eine In-Memory-Map mit 3 Räumen (größer als Disk)
big_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r2": {"name": "#Room2", "theme": "t2", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r3": {"name": "#Room3", "theme": "t3", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
big_map = RoomMap._from_dict(big_data)
# Speichern — sollte erlaubt sein
RoomMap.save(big_map, path=map_path)
# Disk sollte jetzt 3 Räume haben
with open(map_path, "r") as f:
saved_data = json.load(f)
assert len(saved_data["rooms"]) == 3, (
f"Disk sollte 3 Räume haben, hat aber {len(saved_data['rooms'])}"
)
finally:
tmpdir.cleanup()
def test_save_allows_when_equal_rooms(self):
"""save() erlaubt Schreiben wenn Disk und In-Memory gleich viele Räume haben."""
import tempfile
from pathlib import Path
disk_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r2": {"name": "#Room2", "theme": "t2", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
tmpdir = tempfile.TemporaryDirectory()
try:
map_path = Path(tmpdir.name) / "room-map.json"
with open(map_path, "w") as f:
json.dump(disk_data, f)
# In-Memory hat auch 2 Räume (aber anderer Name)
mem_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1_Renamed", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
"r2": {"name": "#Room2", "theme": "t2", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": False,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
mem_map = RoomMap._from_dict(mem_data)
# Speichern — sollte erlaubt sein (gleiche Anzahl)
RoomMap.save(mem_map, path=map_path)
with open(map_path, "r") as f:
saved_data = json.load(f)
assert saved_data["rooms"]["r1"]["name"] == "#Room1_Renamed", (
"Umbenennung sollte persistiert werden"
)
finally:
tmpdir.cleanup()
def test_save_allows_when_disk_does_not_exist(self):
"""save() erlaubt Schreiben wenn Disk-Datei nicht existiert."""
import tempfile
from pathlib import Path
tmpdir = tempfile.TemporaryDirectory()
try:
map_path = Path(tmpdir.name) / "room-map.json"
# Keine Disk-Datei
mem_data = {
"version": 1,
"rooms": {
"r1": {"name": "#Room1", "theme": "t1", "description": "",
"keywords_100": [], "keywords_context": [], "catch_all": True,
"active_status_indikator": True,
"_stay_counts": {}, "_keyword_last_matched": {}},
},
"excluded_rooms": [],
"fact_store_path": "/tmp/test",
}
mem_map = RoomMap._from_dict(mem_data)
# Speichern — sollte erlaubt sein (keine Disk-Datei)
RoomMap.save(mem_map, path=map_path)
assert map_path.exists(), "Datei sollte erstellt worden sein"
finally:
tmpdir.cleanup()