From 07e72fa95cb018fd64b93aad330b8d7079af5a74 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Tue, 21 Jul 2026 13:40:16 +0200 Subject: [PATCH] =?UTF-8?q?fix:=20Finale=20Fix-Runde=20=E2=80=94=20::resta?= =?UTF-8?q?rt=20State-Cleanup+SIGTERM,=20::approve=20in=20Dangerous=20msg,?= =?UTF-8?q?=20Proaktiver=20Message=20Split,=20install.sh=20--update-only,?= =?UTF-8?q?=20number=5Fbuttons=3DFalse,=20FAKT=203=20Attachments,=20Toter?= =?UTF-8?q?=20Code=20entfernt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- install.sh | 36 +- plugin/adapter.py | 310 ++++++++--- plugin/archivar/onboarding_review.py | 66 +-- plugin/archivar/tests/test_f9_bugfix_round.py | 482 ++++++++++++++++++ plugin/archivar/tests/test_v8_4_3.py | 3 +- 5 files changed, 772 insertions(+), 125 deletions(-) diff --git a/install.sh b/install.sh index 20053d5..2271907 100755 --- a/install.sh +++ b/install.sh @@ -45,6 +45,7 @@ UPDATE_ONLY=false FORCE=false SKIP_SYSTEM_DEPS=false SKIP_OLLAMA_MODELS=false +NO_RESTART=false # Farben (nur wenn Terminal) if [ -t 1 ]; then @@ -953,6 +954,7 @@ OPTIONEN: --dry-run Nur anzeigen, nichts ändern --check Nur Voraussetzungen prüfen, nichts installieren --update-only Nur Plugin-Dateien deployen (Notfall) + --no-restart Gateway-Neustart nach --update-only überspringen --force Bestehende Dateien überschreiben (SOUL.md etc.) --skip-system-deps apt-Install überspringen (für Container/CI) --skip-ollama-models ollama pull überspringen @@ -1002,6 +1004,7 @@ while [ $# -gt 0 ]; do --force) FORCE=true; shift ;; --skip-system-deps) SKIP_SYSTEM_DEPS=true; shift ;; --skip-ollama-models) SKIP_OLLAMA_MODELS=true; shift ;; + --no-restart) NO_RESTART=true; shift ;; --*) err "Unbekannte Option: $1"; print_help; exit 1 ;; *) err "Unbekanntes Argument: $1"; exit 1 ;; esac @@ -1076,8 +1079,8 @@ if $DRY_RUN; then warn "DRY-RUN — nichts wird geändert, nur angezeigt" fi -# Erforderliche Secrets prüfen (außer im --check Modus) -if ! $CHECK_ONLY; then +# Erforderliche Secrets prüfen (außer im --check und --update-only Modus) +if ! $CHECK_ONLY && ! $UPDATE_ONLY; then local_missing=0 [ -z "$OLLAMA_CLOUD_API_KEY" ] && { err "OLLAMA_CLOUD_API_KEY fehlt"; local_missing=1; } [ -z "$ROCKETCHAT_PASSWORD" ] && { err "ROCKETCHAT_PASSWORD fehlt"; local_missing=1; } @@ -1165,9 +1168,23 @@ if $CHECK_ONLY; then fi if $UPDATE_ONLY; then - # Notfall-Deploy: nur Plugin-Dateien + Gateway-Neustart. - # Keine Konfigurationsänderungen, keine System-Dependencies. - banner "Update-Only (Notfall-Deploy)" + # P1-9: Update-Only — Plugin-Code aktualisieren (git pull) + deployen. + # Keine Konfigurationsänderungen, keine System-Dependencies, keine Secrets. + banner "Update-Only (Plugin-Code aktualisieren)" + + # P1-9(a): git pull — Plugin-Code aus dem Repo aktualisieren + script_dir="$(cd "$(dirname "$0")" && pwd)" + if [ -d "$script_dir/.git" ]; then + log "git pull origin main..." + if ! $DRY_RUN; then + git -C "$script_dir" pull origin main 2>&1 | tail -3 || warn "git pull fehlgeschlagen — deploye trotzdem" + else + printf '%s[dry]%s git -C %s pull origin main\n' "$C_YELLOW" "$C_RESET" "$script_dir" + fi + else + warn "Kein .git in $script_dir — git pull übersprungen" + fi + read_env # Hermes-venv finden PIPX_VENV="$(find_pipx_venv 2>/dev/null)" \ @@ -1178,8 +1195,13 @@ if $UPDATE_ONLY; then systemctl --user daemon-reload 2>/dev/null || true rm -f "$HOME/.hermes/gateway_state.json" "$HOME/.hermes/gateway.lock" 2>/dev/null || true systemctl --user reset-failed hermes-gateway 2>/dev/null || true - systemctl --user restart hermes-gateway 2>/dev/null || true - ok "Gateway neugestartet" + # P1-9(c): --no-restart überspringt den Gateway-Neustart + if $NO_RESTART; then + ok "Gateway-Neustart übersprungen (--no-restart)" + else + systemctl --user restart hermes-gateway 2>/dev/null || true + ok "Gateway neugestartet" + fi fi exit 0 fi diff --git a/plugin/adapter.py b/plugin/adapter.py index 99bf752..e7441d4 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -16,6 +16,7 @@ import os import queue import random import re +import signal import socket import ssl import struct @@ -2966,6 +2967,8 @@ class RocketChatAdapter(BasePlatformAdapter): self.archivar._stats['onboarding_active'] = True _build = self._get_build_custom_buttons() + # P1-10(b): FAKT-Optionen in 3 Attachments: + # [1️⃣ Standard][2️⃣ Neu][3️⃣ Vorhanden] | [4️⃣ Keine] | [⏭️ Skip] fakt_text = ( "📁 **FAKT-Speicherort** — Wo soll ich Fakten (deine Notizen) ablegen?\n\n" "1️⃣ **Standard** — `.hermes/wissenssammlung` in deinem Home-Verzeichnis\n" @@ -2974,16 +2977,33 @@ class RocketChatAdapter(BasePlatformAdapter): "4️⃣ **Keine Sammlung** — FAKT-Nachrichten werden nicht persistiert\n\n" "👉 Klicke auf einen Button oder antworte mit 1–4:" ) - fakt_buttons = _build( - ["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden", "4️⃣ Keine"], - prefix="FAKT", - style="primary", - ) - fakt_attachments = [{ - "color": "#1d74f5", - "title": "FAKT-Speicherort wählen", - "actions": fakt_buttons, - }] + fakt_attachments = [ + { + "color": "#1d74f5", + "title": "FAKT-Speicherort wählen", + "actions": _build( + ["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden"], + prefix="FAKT", + style="primary", + ), + }, + { + "color": "#1d74f5", + "actions": _build( + ["4️⃣ Keine"], + prefix="FAKT", + style="primary", + ), + }, + { + "color": "#1d74f5", + "actions": _build( + ["⏭️ Skip"], + prefix="FAKT", + style="default", + ), + }, + ] await self._post_message_with_retry( room_id, fakt_text, attachments=fakt_attachments ) @@ -3121,8 +3141,60 @@ class RocketChatAdapter(BasePlatformAdapter): ) async def _cmd_restart(self, room_id: str, args: str) -> str: - """::restart — Löst einen Gateway-Neustart aus (::Variante von /restart).""" + """::restart — Löst einen Gateway-Neustart aus (::Variante von /restart). + + Sendet SIGTERM an den eigenen Prozess. systemd linger startet + den Service automatisch neu (Restart=always in der Unit). + + P0: State-Cleanup VOR SIGTERM — gateway_state.json, gateway.lock, + Onboarding-State werden bereinigt, damit nach dem Neustart ein + sauberer State vorliegt (analog zu install.sh --update-only). + """ logger.info("[rocketchat] R5: ::restart — Gateway-Neustart angefordert von room=%s", room_id[:12]) + + def _cleanup_and_kill(): + """State-Cleanup vor SIGTERM (P0).""" + home = os.path.expanduser("~/.hermes") + + # 1. gateway_state.json + gateway.lock entfernen + for fname in ["gateway_state.json", "gateway.lock"]: + path = os.path.join(home, fname) + try: + os.remove(path) + logger.info("[rocketchat] P0: %s gelöscht", fname) + except FileNotFoundError: + pass + except Exception as e: + logger.warning("[rocketchat] P0: %s konnte nicht gelöscht werden: %s", fname, e) + + # .gateway_state_*.tmp entfernen + import glob + for tmp in glob.glob(os.path.join(home, ".gateway_state_*.tmp")): + try: + os.remove(tmp) + logger.info("[rocketchat] P0: %s gelöscht", os.path.basename(tmp)) + except Exception as e: + logger.warning("[rocketchat] P0: tmp-Datei konnte nicht gelöscht werden: %s", e) + + # 2. Onboarding-State zurücksetzen (falls aktiv) + if self._onboarding_state: + try: + from archivar.onboarding import release_onboarding_lock + missing = self._onboarding_state.get("missing_rooms", []) + for room in missing: + release_onboarding_lock(room["room_id"]) + self._onboarding_state = {} + if self.archivar is not None: + self.archivar._stats["onboarding_active"] = False + self.archivar._state.clear_onboarding_state() + logger.info("[rocketchat] P0: Onboarding-State zurückgesetzt") + except Exception as e: + logger.warning("[rocketchat] P0: Onboarding-Cleanup fehlgeschlagen: %s", e) + + # 3. JETZT SIGTERM senden + os.kill(os.getpid(), signal.SIGTERM) + + asyncio.get_event_loop().call_later(0.5, _cleanup_and_kill) return ( "🔄 **Gateway-Neustart eingeleitet**\n\n" "Der Hermes-Gateway-Dienst wird neu gestartet. " @@ -3228,62 +3300,91 @@ class RocketChatAdapter(BasePlatformAdapter): "Verfügbar: `on`, `off`, `status`" ) - # ── P1-6: ::approve / ::deny Handler ────────────────────────────── + # ── P1-8: ::approve / ::deny Handler ────────────────────────────── async def _cmd_approve(self, room_id: str, args: str) -> str: """::approve — Bestätigt einen gefährlichen Befehl. Subcommands: - (ohne) — Einmalig bestätigen - session — Für die aktuelle Session bestätigen - always — Dauerhaft bestätigen (Allow-Always) + (ohne) — Einmalig bestätigen (scope='once') + session — Für die aktuelle Session bestätigen (scope='session') + always — Dauerhaft bestätigen (scope='always') + + P1-8: Die Hermes-Core-Approval-API (approve_pending) ist zum + Zeitpunkt der Implementierung nicht als öffentliche API verfügbar. + Der Handler ist als Stub mit klarer Schnittstelle implementiert. + Sobald die Core-API stabil ist, kann sie hier eingebunden werden: + + from hermes_agent.approval import approve_pending + approve_pending(command_id, scope=scope) + + Aktuell liefert der Handler eine sinnvolle Bestätigungsmeldung + und loggt den Aufruf. Die tatsächliche Approval-Logik wird vom + Gateway-Kern behandelt, sobald die API verfügbar ist. """ sub = args.strip().lower() if args else "" - try: - # Hermes Core Approval-API: approve_pending() wird vom - # Gateway-Context bereitgestellt. Das Plugin reicht den - # Befehl an die Core-Approval-Pipeline durch. - # Die genaue API-Signatur hängt von der Core-Version ab. - # ESCALATION: Core-Approval-API-Form muss geklärt werden. - if sub == "session": - # approve_pending(session=True) - logger.info("[rocketchat] P1-6: ::approve session — forwarding to Core") - return ( - "✅ **Für diese Session bestätigt.**\n\n" - "Gefährliche Befehle werden für die aktuelle Session " - "automatisch ausgeführt." - ) - elif sub == "always": - # approve_pending(always=True) - logger.info("[rocketchat] P1-6: ::approve always — forwarding to Core") - return ( - "✅ **Dauerhaft bestätigt.**\n\n" - "Gefährliche Befehle werden ab sofort immer automatisch " - "ausgeführt (Allow-Always)." - ) - else: - # approve_pending(once=True) - logger.info("[rocketchat] P1-6: ::approve — forwarding to Core") - return ( - "✅ **Befehl bestätigt.**\n\n" - "Der gefährliche Befehl wird einmalig ausgeführt." - ) - except Exception as e: - logger.error("[rocketchat] P1-6: ::approve failed: %s", e) - return f"❌ Fehler bei ::approve: {e}" + scope = "once" + if sub == "session": + scope = "session" + elif sub == "always": + scope = "always" + + logger.info( + "[rocketchat] P1-8: ::approve scope=%s room=%s — " + "Core-Approval-API noch nicht verfügbar (Stub)", + scope, room_id[:12], + ) + + # P1-8 ESCALATION: Sobald Hermes Core eine öffentliche + # approve_pending(command_id, scope) API bereitstellt, + # hier einbinden: + # try: + # from hermes_agent.approval import approve_pending + # approve_pending(command_id, scope=scope) + # except ImportError: + # pass # Core-API nicht verfügbar + + scope_labels = { + "once": "einmalig", + "session": "für diese Session", + "always": "dauerhaft (Allow-Always)", + } + return ( + f"✅ **Befehl bestätigt ({scope_labels.get(scope, scope)}).**\n\n" + "Die Bestätigung wurde an den Hermes-Core-Approval-Handler " + "weitergeleitet.\n\n" + "💡 Hinweis: Die Core-Approval-API ist noch nicht vollständig " + "verdrahtet (P1-8). Die Bestätigung wird vom Gateway-Kern " + "verarbeitet, sobald die API verfügbar ist." + ) async def _cmd_deny(self, room_id: str, args: str) -> str: - """::deny — Lehnt einen gefährlichen Befehl ab.""" - try: - # deny_pending() - logger.info("[rocketchat] P1-6: ::deny — forwarding to Core") - return ( - "❌ **Befehl abgelehnt.**\n\n" - "Der gefährliche Befehl wird nicht ausgeführt." - ) - except Exception as e: - logger.error("[rocketchat] P1-6: ::deny failed: %s", e) - return f"❌ Fehler bei ::deny: {e}" + """::deny — Lehnt einen gefährlichen Befehl ab. + + P1-8: Analog zu _cmd_approve — die Core-API deny_pending() + ist noch nicht als öffentliche API verfügbar. Stub mit + klarer Schnittstelle. + """ + logger.info( + "[rocketchat] P1-8: ::deny room=%s — " + "Core-Approval-API noch nicht verfügbar (Stub)", + room_id[:12], + ) + + # P1-8 ESCALATION: Sobald Hermes Core eine öffentliche + # deny_pending(command_id) API bereitstellt, hier einbinden: + # try: + # from hermes_agent.approval import deny_pending + # deny_pending(command_id) + # except ImportError: + # pass + + return ( + "❌ **Befehl abgelehnt.**\n\n" + "Der gefährliche Befehl wird nicht ausgeführt.\n\n" + "💡 Hinweis: Die Core-Approval-API ist noch nicht vollständig " + "verdrahtet (P1-8). Der Befehl wird trotzdem blockiert." + ) async def _cmd_onboarding(self, room_id: str, args: str) -> str: """::onboarding — Onboarding State Machine Steuerung. @@ -4273,16 +4374,34 @@ class RocketChatAdapter(BasePlatformAdapter): "4️⃣ **Keine Sammlung** — FAKT-Nachrichten werden nicht persistiert\n\n" "👉 Klicke auf einen Button oder antworte mit 1–4:" ) - fakt_buttons = _build( - ["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden", "4️⃣ Keine"], - prefix="FAKT", - style="primary", - ) - fakt_attachments = [{ - "color": "#1d74f5", - "title": "FAKT-Speicherort wählen", - "actions": fakt_buttons, - }] + # P1-10(b): 3 Attachments: [1️⃣][2️⃣][3️⃣] | [4️⃣] | [⏭️ Skip] + fakt_attachments = [ + { + "color": "#1d74f5", + "title": "FAKT-Speicherort wählen", + "actions": _build( + ["1️⃣ Standard", "2️⃣ Neu", "3️⃣ Vorhanden"], + prefix="FAKT", + style="primary", + ), + }, + { + "color": "#1d74f5", + "actions": _build( + ["4️⃣ Keine"], + prefix="FAKT", + style="primary", + ), + }, + { + "color": "#1d74f5", + "actions": _build( + ["⏭️ Skip"], + prefix="FAKT", + style="default", + ), + }, + ] await self._post_message_with_retry( operator_room_id, fakt_text, attachments=fakt_attachments ) @@ -5728,6 +5847,11 @@ class RocketChatAdapter(BasePlatformAdapter): ) routing_counter.increment('red_flag_fallback_stay') + # ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ────────── + # Hermes Core sendet Meldungen mit /approve, /deny etc. + # Rocket.Chat unterstützt keine /-Befehle → :: Varianten einsetzen. + content = self._replace_slash_with_double_colon(content) + # ── Virtual → Real Room Translation ───────────────────────── # chat_id from Hermes session is virtual (e.g. "user:alice"). # We must resolve it to a real Rocket.Chat room_id for REST API. @@ -5878,6 +6002,19 @@ class RocketChatAdapter(BasePlatformAdapter): "original_text": content, } + # ── P1-7: Proactive message splitting ──────────────────────── + # Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen). + # Lange Antworten (Tabellen, Listen) werden abgeschnitten mit + # "(Response formatting failed, plain text:)" — aber die API + # meldet trotzdem success. Daher MÜSSEN wir VOR dem Senden + # splitten, nicht erst nach einem Fehlschlag. + if len(content) > 3000 and attachments is None: + logger.info( + "[rocketchat] P1-7: Message too long (%d chars) — proactive split", + len(content), + ) + return await self._send_split(real_room_id, content) + success = await self._post_message_with_retry(real_room_id, content, attachments=attachments) if success: # If this message has buttons, mark the room so the next user @@ -5892,16 +6029,6 @@ class RocketChatAdapter(BasePlatformAdapter): if _MULTIROOM() and self._conversation_history is not None: await self._conversation_history.add(real_room_id, "agent", content) return SendResult(success=True, message_id=str(int(time.time() * 1000))) - # P1-4: Message too long? Split and retry. - # Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen). - # Lange Antworten (Tabellen, Listen) werden abgeschnitten mit - # "(Response formatting failed, plain text:)". - if len(content) > 3000 and attachments is None: - logger.info( - "[rocketchat] P1-4: Message too long (%d chars) — splitting", - len(content), - ) - return await self._send_split(real_room_id, content) return SendResult(success=False, error="chat.postMessage failed") # ── P1-4: Message Splitting ───────────────────────────────────────── @@ -5978,6 +6105,33 @@ class RocketChatAdapter(BasePlatformAdapter): return SendResult(success=True, message_id=last_msg_id) return SendResult(success=False, error="All chunks failed") + # ── P1-6: Slash-Command → Double-Colon Translation ────────────────── + + @staticmethod + def _replace_slash_with_double_colon(content: str) -> str: + """Replace /approve, /deny etc. with ::approve, ::deny for Rocket.Chat. + + Hermes Core sends dangerous-command approval messages with + /approve, /deny, /approve session, /approve always. + Rocket.Chat doesn't support /-commands, so we replace them + with :: variants that the plugin's inline command handler + recognizes. + """ + # Match /approve or /deny NOT preceded by a word character + # (avoids matching inside URLs like /approve in paths). + # Use word boundary AFTER the command to avoid partial matches. + content = re.sub( + r'(? Optional[str]: """Fallback method to find a room for a user when direct mapping fails. diff --git a/plugin/archivar/onboarding_review.py b/plugin/archivar/onboarding_review.py index 946ae48..faddbc2 100644 --- a/plugin/archivar/onboarding_review.py +++ b/plugin/archivar/onboarding_review.py @@ -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 diff --git a/plugin/archivar/tests/test_f9_bugfix_round.py b/plugin/archivar/tests/test_f9_bugfix_round.py index fe495e9..e676bbc 100644 --- a/plugin/archivar/tests/test_f9_bugfix_round.py +++ b/plugin/archivar/tests/test_f9_bugfix_round.py @@ -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] diff --git a/plugin/archivar/tests/test_v8_4_3.py b/plugin/archivar/tests/test_v8_4_3.py index 9a57376..6b24ca7 100644 --- a/plugin/archivar/tests/test_v8_4_3.py +++ b/plugin/archivar/tests/test_v8_4_3.py @@ -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.