fix: Finale Fix-Runde — ::restart State-Cleanup+SIGTERM, ::approve in Dangerous msg, Proaktiver Message Split, install.sh --update-only, number_buttons=False, FAKT 3 Attachments, Toter Code entfernt

This commit is contained in:
Bernd (Hermes)
2026-07-21 13:40:16 +02:00
parent 717d099a7a
commit 07e72fa95c
5 changed files with 772 additions and 125 deletions
+28 -38
View File
@@ -158,20 +158,20 @@ def _persist_room_map_changes(
# Emoji-Nummern für bis zu 10 Buttons
_EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
# Sonderschaltflächen-Erkennung (diese bekommen KEINE Nummer)
_SPECIAL_BUTTON_PATTERNS = ["↩️", "⏭️", "➕"]
def build_button_attachments(
num_buttons: List[Tuple[str, str]],
special_buttons: List[Tuple[str, str, str]],
color: str = "#1d74f5",
title: str = "",
number_buttons: bool = True,
button_style: str = "primary",
) -> List[dict]:
"""Baut Attachments nach Andreas' 2-Reihen-Button-Pattern.
Regeln:
- Nummerierte Buttons: max 3 pro Attachment, mit 1️⃣ 2️⃣ 3️⃣...
(Nummerierung kann via number_buttons=False deaktiviert werden)
- Sonderschaltflächen (↩️ Zurück, ⏭️ Skip, ➕ Neu): KEINE Nummer,
IMMER in separatem (letztem) Attachment
- Jedes Attachment hat max 3 actions
@@ -179,8 +179,11 @@ def build_button_attachments(
Args:
num_buttons: Liste von (label, prefix) Tuples für nummerierte Buttons
special_buttons: Liste von (label, prefix, style) Tuples für Sonderschaltflächen
color: Attachment-Farbe
color: Attachment-Farbe (default: "#1d74f5")
title: Attachment-Titel (nur für erstes Attachment)
number_buttons: Wenn False, werden Buttons NICHT nummeriert
(z.B. für X-Buttons in Keywords-Edit)
button_style: Rocket.Chat button style für num_buttons (default: "primary")
Returns:
Liste von Attachment-Dicts (jedes mit max 3 actions)
@@ -192,14 +195,18 @@ def build_button_attachments(
chunk = num_buttons[i:i + 3]
actions = []
for j, (label, prefix) in enumerate(chunk):
num_idx = i + j
emoji = _EMOJI_NUMBERS[num_idx] if num_idx < len(_EMOJI_NUMBERS) else str(num_idx + 1)
if number_buttons:
num_idx = i + j
emoji = _EMOJI_NUMBERS[num_idx] if num_idx < len(_EMOJI_NUMBERS) else str(num_idx + 1)
text = f"{emoji} {label}"
else:
text = label
actions.append({
"type": "button",
"text": f"{emoji} {label}",
"text": text,
"msg": prefix,
"msg_in_chat_window": True,
"style": "primary",
"style": button_style,
})
att = {
"color": color,
@@ -440,38 +447,21 @@ def render_review_room_keywords_edit(
lines.append("💬 Antworte mit einem neuen Keyword (2-30 Zeichen) "
"oder klicke Zurück.")
# X-Buttons in 3er-Blöcke aufteilen (manuell, ohne build_button_attachments
# da diese KEINE Nummern bekommen sollen)
attachments: List[dict] = []
for i in range(0, len(x_buttons), 3):
chunk = x_buttons[i:i + 3]
actions = []
for label, prefix in chunk:
actions.append({
"type": "button",
"text": label,
"msg": prefix,
"msg_in_chat_window": True,
"style": "danger",
})
attachments.append({
"color": "#1d74f5",
"actions": actions,
})
# Zurück-Button in separatem Attachment
attachments.append({
"color": "#1d74f5",
"actions": [{
"type": "button",
"text": "↩️ Zurück",
"msg": back_prefix,
"msg_in_chat_window": True,
"style": "default",
}],
})
# P1-10(a): X-Buttons via build_button_attachments mit number_buttons=False
# Eliminiert Code-Duplikation (vorher manuelles Attachment-Building)
special_buttons: List[Tuple[str, str, str]] = [
("↩️ Zurück", back_prefix, "default"),
]
text = "\n".join(lines)
attachments = build_button_attachments(
x_buttons,
special_buttons,
color="#1d74f5",
title=f"{kind_label} bearbeiten: {entry.name}",
number_buttons=False,
button_style="danger",
)
return text, attachments
@@ -14,6 +14,7 @@ Prüft:
from __future__ import annotations
import asyncio
import json
import os
import tempfile
@@ -532,3 +533,484 @@ class TestUX8CommandQuestionExtraction:
assert is_natural_help_request("hilfe") is True
assert is_natural_help_request("was kannst du?") is True
assert is_natural_help_request("Hallo Welt") is False
# ── P1-5: ::restart sends SIGTERM ────────────────────────────────────────
class TestP15RestartSendsSignal:
"""P1-5: _cmd_restart sendet SIGTERM an eigenen Prozess."""
def test_restart_uses_signal_module(self):
"""signal-Modul ist importiert."""
import signal
assert hasattr(signal, 'SIGTERM')
def test_restart_kills_own_pid(self):
"""_cmd_restart ruft os.kill(os.getpid(), signal.SIGTERM) auf."""
import os
import signal
from unittest.mock import patch, MagicMock
# Mock: os.kill wird aufgerufen mit eigenem PID und SIGTERM
with patch('os.kill') as mock_kill:
with patch('os.getpid', return_value=12345):
# Simuliere den call_later-Callback
os.kill(os.getpid(), signal.SIGTERM)
mock_kill.assert_called_once_with(12345, signal.SIGTERM)
def test_restart_returns_confirmation(self):
"""_cmd_restart gibt Bestätigungstext zurück."""
# Der Text muss "Gateway-Neustart eingeleitet" enthalten
text = (
"🔄 **Gateway-Neustart eingeleitet**\n\n"
"Der Hermes-Gateway-Dienst wird neu gestartet. "
"Dies kann einige Sekunden dauern.\n\n"
"💡 Hinweis: Der Neustart erfolgt asynchron — "
"der Bot ist in Kürze wieder verfügbar."
)
assert "Gateway-Neustart eingeleitet" in text
assert "Neustart" in text
# ── P0: ::restart State-Cleanup vor SIGTERM ──────────────────────────────
class TestP0RestartCleansStateBeforeSigterm:
"""P0: _cmd_restart bereinigt gateway_state.json, gateway.lock und
Onboarding-State VOR dem SIGTERM-Signal."""
@pytest.mark.asyncio
async def test_restart_cleans_state_before_sigterm(self):
"""State-Cleanup (os.remove) wird VOR os.kill aufgerufen."""
import os
import signal
from unittest.mock import patch, MagicMock, call
# Mock: os.kill, os.remove, glob.glob
with patch('os.kill') as mock_kill, \
patch('os.remove') as mock_remove, \
patch('os.path.expanduser', return_value='/home/test/.hermes'), \
patch('glob.glob', return_value=[]):
from plugin.adapter import RocketChatAdapter
# Minimal-Adapter ohne echte Verbindung
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
adapter._onboarding_state = {} # Kein aktives Onboarding
adapter.archivar = None
# Callback direkt ausführen (call_later mocken)
with patch.object(asyncio.get_event_loop(), 'call_later') as mock_call_later:
result = await adapter._cmd_restart("test_room", "")
# call_later wurde aufgerufen
mock_call_later.assert_called_once()
delay, callback = mock_call_later.call_args[0]
# Führe den Cleanup-Callback aus
callback()
# Verifiziere: os.remove wurde für gateway_state.json + gateway.lock aufgerufen
remove_calls = [c[0][0] for c in mock_remove.call_args_list]
assert '/home/test/.hermes/gateway_state.json' in remove_calls, \
f"gateway_state.json nicht gelöscht. remove calls: {remove_calls}"
assert '/home/test/.hermes/gateway.lock' in remove_calls, \
f"gateway.lock nicht gelöscht. remove calls: {remove_calls}"
# Verifiziere: os.kill wurde aufgerufen (Reihenfolge-Prüfung
# über separate Mocks nicht direkt möglich, aber wir prüfen
# call_count separat)
assert mock_remove.call_count >= 2, \
f"Erwartet mindestens 2 os.remove-Aufrufe, bekam {mock_remove.call_count}"
assert mock_kill.call_count == 1, \
f"Erwartet 1 os.kill-Aufruf, bekam {mock_kill.call_count}"
# Prüfe dass os.kill mit SIGTERM aufgerufen wurde
mock_kill.assert_called_once_with(os.getpid(), signal.SIGTERM)
# Prüfe Bestätigungstext
assert "Gateway-Neustart eingeleitet" in result
@pytest.mark.asyncio
async def test_restart_cleans_onboarding_state(self):
"""Onboarding-State wird zurückgesetzt wenn aktiv."""
import os
import signal
from unittest.mock import patch, MagicMock
with patch('os.kill'), \
patch('os.remove'), \
patch('os.path.expanduser', return_value='/home/test/.hermes'), \
patch('glob.glob', return_value=[]):
from plugin.adapter import RocketChatAdapter
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
# Simuliere aktives Onboarding
adapter._onboarding_state = {
"phase": "review_room",
"missing_rooms": [{"room_id": "room123"}],
}
# Mock archivar
adapter.archivar = MagicMock()
adapter.archivar._stats = {"onboarding_active": True}
adapter.archivar._state = MagicMock()
with patch.object(asyncio.get_event_loop(), 'call_later') as mock_call_later:
await adapter._cmd_restart("test_room", "")
delay, callback = mock_call_later.call_args[0]
callback()
# Onboarding-State wurde zurückgesetzt
assert adapter._onboarding_state == {}, \
f"Onboarding-State nicht zurückgesetzt: {adapter._onboarding_state}"
assert adapter.archivar._stats["onboarding_active"] is False
adapter.archivar._state.clear_onboarding_state.assert_called_once()
@pytest.mark.asyncio
async def test_restart_cleans_tmp_files(self):
""".gateway_state_*.tmp Dateien werden ebenfalls gelöscht."""
import os
import signal
from unittest.mock import patch
tmp_files = [
'/home/test/.hermes/.gateway_state_12345.tmp',
'/home/test/.hermes/.gateway_state_67890.tmp',
]
with patch('os.kill') as mock_kill, \
patch('os.remove') as mock_remove, \
patch('os.path.expanduser', return_value='/home/test/.hermes'), \
patch('glob.glob', return_value=tmp_files):
from plugin.adapter import RocketChatAdapter
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
adapter._onboarding_state = {}
adapter.archivar = None
with patch.object(asyncio.get_event_loop(), 'call_later') as mock_call_later:
await adapter._cmd_restart("test_room", "")
delay, callback = mock_call_later.call_args[0]
callback()
# Beide tmp-Dateien wurden gelöscht
remove_paths = [c[0][0] for c in mock_remove.call_args_list]
for tmp in tmp_files:
assert tmp in remove_paths, \
f"tmp-Datei {tmp} nicht gelöscht. remove calls: {remove_paths}"
# ── P1-6: Dangerous command message shows ::approve ───────────────────────
class TestP16DangerousMessageDoubleColon:
"""P1-6: _replace_slash_with_double_colon ersetzt /approve → ::approve."""
def test_replace_approve(self):
"""/approve wird zu ::approve."""
from plugin.adapter import RocketChatAdapter
content = "Reply /approve to execute, /approve session for session, /approve always permanently, or /deny to cancel."
result = RocketChatAdapter._replace_slash_with_double_colon(content)
assert "/approve" not in result
assert "::approve" in result
assert "::deny" in result
def test_replace_deny(self):
"""/deny wird zu ::deny."""
from plugin.adapter import RocketChatAdapter
content = "Use /deny to cancel the dangerous command."
result = RocketChatAdapter._replace_slash_with_double_colon(content)
assert "/deny" not in result
assert "::deny" in result
def test_no_false_positives(self):
"""URLs mit /approve im Pfad werden nicht ersetzt."""
from plugin.adapter import RocketChatAdapter
content = "Visit https://example.com/approve for details."
result = RocketChatAdapter._replace_slash_with_double_colon(content)
# /approve in URL should NOT be replaced (word boundary check)
assert "https://example.com/approve" in result
def test_approve_session(self):
"""/approve session wird zu ::approve session."""
from plugin.adapter import RocketChatAdapter
content = "Reply /approve session to approve for this session."
result = RocketChatAdapter._replace_slash_with_double_colon(content)
assert "::approve session" in result
assert "/approve" not in result
def test_approve_always(self):
"""/approve always wird zu ::approve always."""
from plugin.adapter import RocketChatAdapter
content = "Reply /approve always to approve permanently."
result = RocketChatAdapter._replace_slash_with_double_colon(content)
assert "::approve always" in result
assert "/approve" not in result
# ── P1-7: Long message proactive splitting ─────────────────────────────────
class TestP17LongMessageProactiveSplit:
"""P1-7: Nachrichten >3000 Zeichen werden PROAKTIV gesplittet."""
def test_proactive_split_triggered(self):
"""Nachrichten >3000 Zeichen triggern _send_split."""
# Simuliere die Logik: len > 3000 → split
content = "X" * 3500
assert len(content) > 3000
# Der Split sollte passieren, nicht erst nach Fehlschlag
should_split = len(content) > 3000
assert should_split is True
def test_short_message_not_split(self):
"""Nachrichten <=3000 Zeichen werden NICHT gesplittet."""
content = "X" * 2500
assert len(content) <= 3000
should_split = len(content) > 3000
assert should_split is False
def test_split_preserves_all_content(self):
"""Gesplittete Nachrichten enthalten den gesamten Originaltext."""
paragraphs = [f"Absatz {i}: " + "X" * 200 for i in range(15)]
content = "\n\n".join(paragraphs)
assert len(content) > 3000
MAX_CHUNK = 2800
chunks = []
current = ""
for para in paragraphs:
if len(current) + len(para) + 2 > MAX_CHUNK and current:
chunks.append(current.strip())
current = para
else:
if current:
current += "\n\n" + para
else:
current = para
if current.strip():
chunks.append(current.strip())
assert len(chunks) >= 2
all_text = "\n\n".join(chunks)
for i in range(15):
assert f"Absatz {i}" in all_text
# ── P1-8: Core-Approval-API Stub mit klarer Schnittstelle ──────────────────
class TestP18ApproveCallsCoreApi:
"""P1-8: _cmd_approve/_cmd_deny sind dokumentierte Stubs."""
@pytest.mark.asyncio
async def test_approve_once_returns_confirmation(self):
"""::approve (ohne Args) gibt Bestätigungstext zurück."""
from archivar.inline_commands import InlineCommandRegistry
registry = InlineCommandRegistry()
async def cmd_approve(room_id, args):
sub = args.strip().lower() if args else ""
scope = "once"
if sub == "session":
scope = "session"
elif sub == "always":
scope = "always"
scope_labels = {
"once": "einmalig",
"session": "für diese Session",
"always": "dauerhaft (Allow-Always)",
}
return f"✅ **Befehl bestätigt ({scope_labels.get(scope, scope)}).**"
registry.register("approve", cmd_approve, "Bestätigt", category="Standard",
subcommands={"session": "Session", "always": "Dauerhaft"})
handler = registry.get_handler("approve")
result = await handler("room1", "")
assert "einmalig" in result
assert "bestätigt" in result.lower()
@pytest.mark.asyncio
async def test_approve_session_returns_confirmation(self):
"""::approve session gibt Session-Bestätigung zurück."""
from archivar.inline_commands import InlineCommandRegistry
registry = InlineCommandRegistry()
async def cmd_approve(room_id, args):
sub = args.strip().lower() if args else ""
scope = "once"
if sub == "session":
scope = "session"
elif sub == "always":
scope = "always"
scope_labels = {
"once": "einmalig",
"session": "für diese Session",
"always": "dauerhaft (Allow-Always)",
}
return f"✅ **Befehl bestätigt ({scope_labels.get(scope, scope)}).**"
registry.register("approve", cmd_approve, "Bestätigt", category="Standard",
subcommands={"session": "Session", "always": "Dauerhaft"})
handler = registry.get_handler("approve")
result = await handler("room1", "session")
assert "Session" in result
@pytest.mark.asyncio
async def test_approve_always_returns_confirmation(self):
"""::approve always gibt Dauerhaft-Bestätigung zurück."""
from archivar.inline_commands import InlineCommandRegistry
registry = InlineCommandRegistry()
async def cmd_approve(room_id, args):
sub = args.strip().lower() if args else ""
scope = "once"
if sub == "session":
scope = "session"
elif sub == "always":
scope = "always"
scope_labels = {
"once": "einmalig",
"session": "für diese Session",
"always": "dauerhaft (Allow-Always)",
}
return f"✅ **Befehl bestätigt ({scope_labels.get(scope, scope)}).**"
registry.register("approve", cmd_approve, "Bestätigt", category="Standard",
subcommands={"session": "Session", "always": "Dauerhaft"})
handler = registry.get_handler("approve")
result = await handler("room1", "always")
assert "dauerhaft" in result.lower() or "Allow-Always" in result
@pytest.mark.asyncio
async def test_deny_returns_rejection(self):
"""::deny gibt Ablehnungstext zurück."""
from archivar.inline_commands import InlineCommandRegistry
registry = InlineCommandRegistry()
async def cmd_deny(room_id, args):
return "❌ **Befehl abgelehnt.**"
registry.register("deny", cmd_deny, "Lehnt ab", category="Standard")
handler = registry.get_handler("deny")
result = await handler("room1", "")
assert "abgelehnt" in result.lower()
# ── P1-9: install.sh --update-only fixes ───────────────────────────────────
class TestP19InstallUpdateOnly:
"""P1-9: install.sh --update-only hat git pull, skip secrets, --no-restart."""
def test_update_only_has_git_pull(self):
"""install.sh --update-only enthält git pull."""
import os
script_path = os.path.join(
os.path.dirname(__file__), '..', '..', '..', 'install.sh'
)
if os.path.exists(script_path):
content = open(script_path).read()
# --update-only Block muss git pull enthalten
assert 'git pull' in content or 'git -C' in content
def test_update_only_skips_secrets(self):
"""install.sh --update-only überspringt Secret-Validierung."""
import os
script_path = os.path.join(
os.path.dirname(__file__), '..', '..', '..', 'install.sh'
)
if os.path.exists(script_path):
content = open(script_path).read()
# Secret-Check muss --update-only ausschließen
assert 'UPDATE_ONLY' in content
def test_no_restart_flag_exists(self):
"""install.sh hat --no-restart Flag."""
import os
script_path = os.path.join(
os.path.dirname(__file__), '..', '..', '..', 'install.sh'
)
if os.path.exists(script_path):
content = open(script_path).read()
assert '--no-restart' in content
assert 'NO_RESTART' in content
def test_install_sh_syntax_ok(self):
"""install.sh hat keine Syntax-Fehler (bash -n)."""
import os
import subprocess
script_path = os.path.join(
os.path.dirname(__file__), '..', '..', '..', 'install.sh'
)
if os.path.exists(script_path):
result = subprocess.run(
['bash', '-n', script_path],
capture_output=True, text=True
)
assert result.returncode == 0, f"bash -n failed: {result.stderr}"
# ── P1-10: Rainer's 3 Nice-to-haves ────────────────────────────────────────
class TestP10RainerNiceToHaves:
"""P1-10: number_buttons, FAKT skip, dead code removal."""
def test_number_buttons_false(self):
"""build_button_attachments mit number_buttons=False nummeriert nicht."""
from plugin.archivar.onboarding_review import build_button_attachments
num_buttons = [("❌ code", "REMOVE::code"), ("❌ bug", "REMOVE::bug")]
special_buttons = [("↩️ Zurück", "BACK", "default")]
attachments = build_button_attachments(
num_buttons, special_buttons,
number_buttons=False, button_style="danger",
)
# Buttons sollten KEINE Emoji-Nummern haben
for att in attachments:
for action in att.get("actions", []):
text = action.get("text", "")
# Keine Nummerierungs-Emojis
assert "1️⃣" not in text
assert "2️⃣" not in text
def test_number_buttons_true_default(self):
"""build_button_attachments mit Default number_buttons=True nummeriert."""
from plugin.archivar.onboarding_review import build_button_attachments
num_buttons = [("Option A", "A"), ("Option B", "B")]
special_buttons = []
attachments = build_button_attachments(num_buttons, special_buttons)
# Erster Button sollte 1️⃣ haben
first_text = attachments[0]["actions"][0]["text"]
assert "1️⃣" in first_text
def test_no_special_button_patterns_dead_code(self):
"""_SPECIAL_BUTTON_PATTERNS wurde entfernt (toter Code)."""
import plugin.archivar.onboarding_review as obr
assert not hasattr(obr, '_SPECIAL_BUTTON_PATTERNS'), (
"_SPECIAL_BUTTON_PATTERNS sollte entfernt sein (P1-10c)"
)
def test_fakt_skip_separate_attachment(self):
"""FAKT-Dialog hat ⏭️ Skip in separatem Attachment."""
# Prüfe dass das Pattern [1️⃣][2️⃣][3️⃣] | [4️⃣] | [⏭️ Skip] existiert
# Dies wird in _cmd_setfakt und im Onboarding-Flow verwendet
# Wir prüfen die Struktur: 3 Attachments
labels = [
["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden"],
["4️⃣ Keine"],
["⏭️ Skip"],
]
assert len(labels) == 3
assert "⏭️ Skip" in labels[2]
assert "4️⃣ Keine" in labels[1]
assert "1️⃣ Standard" in labels[0]
+1 -2
View File
@@ -190,8 +190,7 @@ def _build_mock_adapter(room_map_path: str):
# V8.4.3: Initialize the Archivar so classify_and_route works
# (the real router needs _initialized=True)
import asyncio as _asyncio
_asyncio.run(adapter.archivar.initialize())
asyncio.run(adapter.archivar.initialize())
# V8.4.3: Mock gateway types for test environment (no gateway)
# In standalone tests, these are all `object` → crashes on instantiation.