Compare commits
3 Commits
b4ba67e80b
...
bf42ba056e
| Author | SHA1 | Date | |
|---|---|---|---|
| bf42ba056e | |||
| 5d5a361993 | |||
| 1c53a9fe07 |
+6
-2
@@ -156,10 +156,14 @@ class RocketChatREST:
|
||||
raise RocketChatRateLimitError(
|
||||
f"HTTP 429 on {method} {endpoint}"
|
||||
) from e
|
||||
logger.debug("REST %s %s HTTP %d: %s", method, endpoint, e.code, e)
|
||||
# P2-Fix: HTTP 4xx als warning, 5xx als error (vorher nur debug)
|
||||
if 400 <= e.code < 500:
|
||||
logger.warning("REST %s %s HTTP %d: %s", method, endpoint, e.code, e)
|
||||
else:
|
||||
logger.error("REST %s %s HTTP %d: %s", method, endpoint, e.code, e)
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.debug("REST %s %s failed: %s", method, endpoint, e)
|
||||
logger.warning("REST %s %s failed: %s", method, endpoint, e)
|
||||
return None
|
||||
|
||||
def login(self, user: str, password: str) -> bool:
|
||||
|
||||
@@ -325,9 +325,9 @@ def build_help_text(
|
||||
# P1-4: Status-Farben (Flughafen-Prinzip) — nur wenn PresenceEngine aktiv
|
||||
if presence_enabled:
|
||||
status_emoji = {
|
||||
"online": "🟢 online (idle, verfügbar)",
|
||||
"away": "🟡 away (Hintergrund-Task aktiv, Heartbeat pulsiert)",
|
||||
"busy": "🔴 busy (verarbeitet Nachricht)",
|
||||
"online": "🟩 online (idle, verfügbar)",
|
||||
"away": "🟨 away (Hintergrund-Task aktiv, Heartbeat pulsiert)",
|
||||
"busy": "🟥 busy (verarbeitet Nachricht)",
|
||||
}
|
||||
lines.append("### 🚦 Status-Farben")
|
||||
lines.append("")
|
||||
@@ -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(
|
||||
@@ -403,9 +420,9 @@ def build_status_text(
|
||||
# P1-4: PresenceEngine-Info (nur wenn presence_enabled explizit gesetzt)
|
||||
if presence_enabled is not None:
|
||||
status_labels = {
|
||||
"online": "🟢 online (idle, verfügbar)",
|
||||
"away": "🟡 away (Hintergrund-Task aktiv)",
|
||||
"busy": "🔴 busy (verarbeitet Nachricht)",
|
||||
"online": "🟩 online (idle, verfügbar)",
|
||||
"away": "🟨 away (Hintergrund-Task aktiv)",
|
||||
"busy": "🟥 busy (verarbeitet Nachricht)",
|
||||
}
|
||||
pulse_label = "💓 aktiv" if pulse_active else "⏸️ inaktiv"
|
||||
if presence_enabled:
|
||||
@@ -422,7 +439,44 @@ def build_status_text(
|
||||
lines.append("")
|
||||
lines.append("💡 `::hilfe` für alle Befehle | `::status` für Aktualisierung")
|
||||
|
||||
return "\n".join(lines)
|
||||
result = "\n".join(lines)
|
||||
|
||||
# P2-Fix: Rocket.Chat Payload-Limit ~5000 Zeichen.
|
||||
# Wenn der Status-Text > 5000 Zeichen ist, ersetze die room_map_summary
|
||||
# durch eine kompakte Version (nur Raum-Name + Catch-All-Status).
|
||||
MAX_STATUS_LENGTH = 5000
|
||||
if len(result) > MAX_STATUS_LENGTH and room_map_summary:
|
||||
# Baue kompakte Summary: nur Raum-Name + Catch-All-Marker
|
||||
compact_lines = ["**Raum-Map (kompakt):**"]
|
||||
for line in room_map_summary.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith(("Rocket.Chat", "Keywords", "Thema:")):
|
||||
continue
|
||||
# Zeilen wie " 1. Raumname (roomId) ★ CATCH-ALL — Thema: ..."
|
||||
if stripped and stripped[0].isdigit():
|
||||
# Extrahiere nur den Teil bis zum Catch-All-Marker
|
||||
# Format: "1. Name (id) ★ CATCH-ALL — Thema: ..."
|
||||
# oder: "1. Name (id) — Thema: ..."
|
||||
if "★ CATCH-ALL" in stripped:
|
||||
idx = stripped.index("★ CATCH-ALL") + len("★ CATCH-ALL")
|
||||
compact_lines.append(stripped[:idx])
|
||||
else:
|
||||
# Nimm nur "1. Name (id)" — schneide bei " — " ab
|
||||
dash_idx = stripped.find(" — ")
|
||||
if dash_idx > 0:
|
||||
compact_lines.append(stripped[:dash_idx])
|
||||
else:
|
||||
compact_lines.append(stripped)
|
||||
compact_summary = "\n".join(compact_lines)
|
||||
|
||||
# Ersetze die room_map_summary in lines
|
||||
for i, line in enumerate(lines):
|
||||
if line == room_map_summary:
|
||||
lines[i] = compact_summary
|
||||
break
|
||||
result = "\n".join(lines)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# ── Inline-Command-Parser ───────────────────────────────────────────────
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user