From 1c53a9fe07940a0b255d56200fe4585da47ce5a9 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Sat, 25 Jul 2026 20:12:17 +0200 Subject: [PATCH] =?UTF-8?q?P1-Fix:=20build=5Fhelp=5Ftext=20L=C3=A4ngenbegr?= =?UTF-8?q?enzung=20+=20RoomMap.save=20Refuse-Guard?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- plugin/archivar/inline_commands.py | 19 +- plugin/archivar/room_map.py | 27 ++- .../archivar/tests/test_r5_inline_commands.py | 55 +++++ plugin/archivar/tests/test_room_map.py | 208 ++++++++++++++++++ 4 files changed, 307 insertions(+), 2 deletions(-) diff --git a/plugin/archivar/inline_commands.py b/plugin/archivar/inline_commands.py index f65e568..b6e157c 100644 --- a/plugin/archivar/inline_commands.py +++ b/plugin/archivar/inline_commands.py @@ -357,7 +357,24 @@ def build_help_text( "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( diff --git a/plugin/archivar/room_map.py b/plugin/archivar/room_map.py index 9a60c5b..7f26198 100644 --- a/plugin/archivar/room_map.py +++ b/plugin/archivar/room_map.py @@ -515,6 +515,11 @@ class RoomMap: Verwendet ``fcntl.flock`` (exklusiver Lock) um parallele 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: room_map: Die zu speichernde RoomMap-Instanz path: Pfad zur JSON-Datei. Standardwert aus Umgebungsvariablen oder DEFAULT_MAP_PATH. @@ -525,7 +530,27 @@ class RoomMap: path = Path(env_path) else: 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 path.parent.mkdir(parents=True, exist_ok=True) diff --git a/plugin/archivar/tests/test_r5_inline_commands.py b/plugin/archivar/tests/test_r5_inline_commands.py index ad2e5ed..5524ea5 100644 --- a/plugin/archivar/tests/test_r5_inline_commands.py +++ b/plugin/archivar/tests/test_r5_inline_commands.py @@ -262,6 +262,61 @@ class TestBuildHelpText: assert "continue" 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: """Tests für build_status_text.""" diff --git a/plugin/archivar/tests/test_room_map.py b/plugin/archivar/tests/test_room_map.py index 43b0c35..8d732e9 100644 --- a/plugin/archivar/tests/test_room_map.py +++ b/plugin/archivar/tests/test_room_map.py @@ -516,3 +516,211 @@ class TestLLMLookup: result = room_map.find_room_by_keywords("Wie funktioniert das BAT Trading-Signal?") assert result is not None 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()