From a6b8fecb4cb3d2c728effaedea1a4654d5b33676 Mon Sep 17 00:00:00 2001 From: "Bernd (Hermes)" Date: Sun, 19 Jul 2026 10:47:29 +0200 Subject: [PATCH] =?UTF-8?q?feat:=20V8.5=20=E2=80=94=20R5=20::-Inline-Befeh?= =?UTF-8?q?le=20(13=20Befehle:=207=20Standard=20+=206=20RC-spezifisch)=20+?= =?UTF-8?q?=20Onboarding-Fix=20(Plugin-onboarding=20vor=20generisch)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- plugin/adapter.py | 571 ++++++++- plugin/archivar/inline_commands.py | 287 +++++ .../tests/test_fact_store_onboarding.py | 16 + .../archivar/tests/test_r5_inline_commands.py | 1040 +++++++++++++++++ 4 files changed, 1913 insertions(+), 1 deletion(-) create mode 100644 plugin/archivar/inline_commands.py create mode 100644 plugin/archivar/tests/test_r5_inline_commands.py diff --git a/plugin/adapter.py b/plugin/adapter.py index f3d769a..c5eaf63 100644 --- a/plugin/adapter.py +++ b/plugin/adapter.py @@ -23,7 +23,6 @@ import threading import time import urllib.request import urllib.error -import urllib.request from typing import Any, Dict, List, Optional @@ -794,6 +793,10 @@ class RocketChatAdapter(BasePlatformAdapter): # neu gebaut. Der Gateway-Core rendert chat_topic als "**Channel Topic:**" # im System-Prompt — der Agent sieht die Raum-Map also BEI JEDEM START. self._room_map_summary: str = "" + # R5: Inline-Command-Registry für ::-Befehle + from archivar.inline_commands import InlineCommandRegistry + self._inline_commands = InlineCommandRegistry() + self._register_inline_commands() def _build_room_map_summary(self) -> str: """Baut eine menschenlesbare Raum-Map-Übersicht für den System-Prompt. @@ -1534,6 +1537,17 @@ class RocketChatAdapter(BasePlatformAdapter): room_type = self._room_info.get(room_id, {}).get("type", "unknown") logger.info("[rocketchat] Message from %s in %s [%s]: %s", username, room_name, room_type, text[:80]) + # ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ── + # ::-Befehle und natürliche Hilfeseiten-Anfragen müssen VOR dem + # generischen Hermes-Agent-Onboarding erkannt werden. + inline_handled = await self._handle_inline_command(text, room_id, room_name, username) + if inline_handled: + logger.debug("[rocketchat] R5: Inline-Command verarbeitet — skipping agent dispatch") + routing_counter.increment('inline_command_handled') + logger.info("ROUTING BYPASS: reason=inline_command_handled, origin_room=%s", room_id) + return + # ── Ende R5 Inline-Command-Erkennung ──────────────────────────────── + # ── B5v6.5: Conversation History — User-Nachricht aufzeichnen ── if _MULTIROOM() and self._conversation_history is not None: await self._conversation_history.add(room_id, "user", text) @@ -1581,6 +1595,42 @@ class RocketChatAdapter(BasePlatformAdapter): return # ── Ende A1b Lazy-Onboarding ───────────────────────────────────── + # ── Thema B: Onboarding-Guard — Plugin-onboarding vor generischem Hermes-onboarding ── + # Wenn Onboarding aktiv ist und die Nachricht aus einem Raum kommt, + # der NICHT in der room-map.json steht und NICHT der Operator-DM ist, + # dann die Nachricht abfangen. Verhindert dass das generische + # Hermes-Agent-Onboarding (Profile, Skills, Cronjobs) das + # Plugin-Onboarding (Raum-Interview) übersteuert. + if ( + _MULTIROOM() + and self.archivar is not None + and self.archivar._stats.get("onboarding_active", False) + and room_type != "d" + ): + operator_room = self._onboarding_state.get("operator_room_id", "") + # Prüfe ob der Raum in der room-map.json steht + room_in_map = ( + self.archivar._room_map is not None + and room_id in self.archivar._room_map.rooms + ) + if not room_in_map and room_id != operator_room: + # Raum ist unbekannt und Onboarding läuft → Nachricht abfangen + logger.info( + "[rocketchat] Thema B: Onboarding-Guard — Nachricht aus unbekanntem Raum " + "während Onboarding abgefangen: room=%s, name=%s", + room_id[:12], room_name, + ) + await self._post_message_with_retry( + room_id, + "🔄 Ich richte mich gerade ein — einen Moment bitte. " + "Das Onboarding-Interview läuft in deinem DM-Kanal. " + "Sobald ich fertig bin, bin ich für dich da!" + ) + routing_counter.increment('onboarding_guard_blocked') + logger.info("ROUTING BYPASS: reason=onboarding_guard_blocked, origin_room=%s", room_id) + return + # ── Ende Thema B Onboarding-Guard ──────────────────────────────────── + # ── CLARIFY Response Handling ─────────────────────────────────── # Handle CLARIFY button responses: CLARIFY:: or CLARIFY::other # V8.2.1 A2: Handle ARCHIVAR_CLARIFY (Nachklärung) responses @@ -2597,6 +2647,525 @@ class RocketChatAdapter(BasePlatformAdapter): except Exception as e2: logger.error("[rocketchat] BUTTON_CLICK text fallback also failed: %s", e2) + # ── R5: Inline-Command-Handler ──────────────────────────────────────── + + def _register_inline_commands(self) -> None: + """Registriert alle ::-Befehle in der InlineCommandRegistry.""" + # ── Standard-Hermes-Befehle (:: als Variante) ────────────────── + self._inline_commands.register( + "sethome", self._cmd_sethome, + help_text="Setzt den Heimatraum (Alternative zu /sethome)", + description="Setzt den aktuellen Raum als Heimatraum. " + "Der Heimatraum ist der primäre Raum für Catch-All-Nachrichten.", + category="Standard", + ) + self._inline_commands.register( + "reset", self._cmd_reset, + help_text="Setzt den Plugin-Status zurück (Alternative zu /reset)", + description="Setzt den Plugin-Status zurück (Onboarding, Session-Präferenzen).", + category="Standard", + ) + self._inline_commands.register( + "busy", self._cmd_busy, + help_text="Zeigt/steuert den Busy-Status (::Variante von /busy)", + description="Subcommands: queue , steer , status. " + "Steuert was passiert während der Agent arbeitet.", + category="Standard", + ) + self._inline_commands.register( + "allowalways", self._cmd_allowalways, + help_text="Verwaltet die Allow-Always-Liste (::Variante von /allow-always)", + description="Zeigt oder erweitert die Allow-Always-Liste für Skills.", + category="Standard", + ) + self._inline_commands.register( + "commands", self._cmd_commands, + help_text="Listet alle ::-Befehle (::Variante von /commands)", + description="Zeigt die vollständige Hilfeseite mit allen Befehlen.", + category="Info", + ) + self._inline_commands.register( + "restart", self._cmd_restart, + help_text="Löst Gateway-Neustart aus (::Variante von /restart)", + description="Startet den Hermes-Gateway-Dienst neu.", + category="Gateway", + ) + self._inline_commands.register( + "update", self._cmd_update, + help_text="Zeigt Update-Informationen (::Variante von /update)", + description="Zeigt wie Hermes auf die neueste Version aktualisiert wird.", + category="Gateway", + ) + + # ── RC-Plugin-spezifische Befehle ────────────────────────────── + self._inline_commands.register( + "setfakt", self._cmd_setfakt, + help_text="Ändert den FAKT-Speicherort", + description="Öffnet den FAKT-Speicherort-Dialog. " + "Du kannst den Pfad ändern, wo FAKT-Nachrichten persistiert werden.", + category="Konfiguration", + ) + self._inline_commands.register( + "hilfe", self._cmd_hilfe, + help_text="Zeigt diese Hilfeseite", + description="Zeigt alle verfügbaren ::-Befehle und " + "natürlichen Sprach-Befehle an.", + category="Hilfe", + ) + self._inline_commands.register( + "status", self._cmd_status, + help_text="Zeigt aktuellen Plugin-Status", + description="Zeigt Räume, Archivar-Status, Butler-Modus und " + "Onboarding-Status an.", + category="Hilfe", + ) + self._inline_commands.register( + "multiroom", self._cmd_multiroom, + help_text="Multi-Room-Agent aktivieren/deaktivieren/Status", + description="Steuert den Multi-Room-Agenten. " + "Subcommands: on, off, status.", + category="Plugin", + ) + self._inline_commands.register( + "onboarding", self._cmd_onboarding, + help_text="Onboarding für einen Raum neu starten", + description="Startet das Onboarding für den aktuellen Raum neu. " + "Mit Raumname als Argument für einen anderen Raum.", + category="Plugin", + ) + self._inline_commands.register( + "curate", self._cmd_curate, + help_text="Kuratiert die Room-Map-Keywords (R10)", + description="Prüft und optimiert die Keywords in der Room-Map. " + "Subcommands: status, run.", + category="Plugin", + ) + + async def _handle_inline_command( + self, text: str, room_id: str, room_name: str, username: str + ) -> bool: + """Erkennt und verarbeitet ::-Befehle und natürliche Hilfeseiten-Anfragen. + + Wird VOR dem Onboarding und VOR dem Hermes-Agent-Dispatch aufgerufen. + + Args: + text: Der Nachrichtentext. + room_id: Rocket.Chat Raum-ID. + room_name: Anzeigename des Raums. + username: Username des Senders. + + Returns: + True wenn die Nachricht als Inline-Command verarbeitet wurde, + False wenn sie normal weiterverarbeitet werden soll. + """ + from archivar.inline_commands import ( + parse_inline_command, + is_natural_help_request, + build_help_text, + ) + + stripped = text.strip() + + # 1. ::-Befehl am Satzanfang? + parsed = parse_inline_command(stripped) + if parsed: + command, args = parsed + handler = self._inline_commands.get_handler(command) + if handler is not None: + response = await handler(room_id, args) + if response: # Leerer String = Handler hat selbst gepostet (z.B. Buttons) + await self._post_message_with_retry(room_id, response) + return True + else: + # Unbekannter ::-Befehl → Hilfeseite zeigen + help_text = build_help_text( + self._inline_commands, + room_map_summary=self._room_map_summary, + ) + unknown_msg = ( + f"Unbekannter Befehl `::{command}`. " + f"Hier sind alle verfügbaren Befehle:\n\n{help_text}" + ) + await self._post_message_with_retry(room_id, unknown_msg) + return True + + # 2. Natürliche Hilfeseiten-Anfrage? + if is_natural_help_request(stripped): + help_text = build_help_text( + self._inline_commands, + room_map_summary=self._room_map_summary, + ) + await self._post_message_with_retry(room_id, help_text) + return True + + return False + + # ── Command-Handler-Implementierungen ──────────────────────────────── + + async def _cmd_sethome(self, room_id: str, args: str) -> str: + """::sethome — Setzt den aktuellen Raum als Heimatraum. + + Der Heimatraum wird als Catch-All in der room-map.json gesetzt. + """ + if not _MULTIROOM() or self.archivar is None: + return "❌ `::sethome` ist nur im Multiroom-Modus verfügbar." + + room_name = self._room_info.get(room_id, {}).get("name", room_id) + self._set_catch_all(room_id) + # FIX E: Raum-Map Summary aktualisieren + self._room_map_summary = self._build_room_map_summary() + return f"✅ Heimatraum gesetzt: **{room_name}** (Catch-All)" + + async def _cmd_setfakt(self, room_id: str, args: str) -> str: + """::setfakt — Öffnet den FAKT-Speicherort-Dialog. + + Der User kann den Pfad ändern, wo FAKT-Nachrichten persistiert werden. + """ + if not _MULTIROOM() or self.archivar is None: + return "❌ `::setfakt` ist nur im Multiroom-Modus verfügbar." + + # Aktiviere den FAKT-Speicherort-Dialog (gleicher Flow wie im Onboarding) + self._onboarding_state = { + "phase": "fakt_store", + "operator_room_id": room_id, + } + if self.archivar is not None: + self.archivar._state.set_onboarding_state(self._onboarding_state) + self.archivar._stats['onboarding_active'] = True + + _build = self._get_build_custom_buttons() + fakt_text = ( + "📁 **FAKT-Speicherort** — Wo soll ich Fakten (deine Notizen) ablegen?\n\n" + "1️⃣ **Standard** — `.hermes/wissenssammlung` in deinem Home-Verzeichnis\n" + "2️⃣ **Neuer Ort** — Du gibst einen Pfad an, ich lege das Verzeichnis an\n" + "3️⃣ **Bestehender Ort** — Du gibst einen Pfad an, ich verweise darauf\n" + "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️⃣ Neuer Ort", "3️⃣ Bestehender Ort", "4️⃣ Keine Sammlung"], + prefix="FAKT", + style="primary", + ) + fakt_attachments = [{ + "color": "#1d74f5", + "title": "FAKT-Speicherort wählen", + "actions": fakt_buttons, + }] + await self._post_message_with_retry( + room_id, fakt_text, attachments=fakt_attachments + ) + logger.info("[rocketchat] R5: ::setfakt — FAKT-Speicherort-Dialog geöffnet") + # Wir haben bereits gepostet, also leeren String zurückgeben + # (die Nachricht wurde schon gesendet) + return "" # Wird nicht gepostet, da _handle_inline_command den Return-Wert sendet + + async def _cmd_hilfe(self, room_id: str, args: str) -> str: + """::hilfe — Zeigt die Hilfeseite mit allen Befehlen.""" + from archivar.inline_commands import build_help_text + return build_help_text( + self._inline_commands, + room_map_summary=self._room_map_summary, + ) + + async def _cmd_status(self, room_id: str, args: str) -> str: + """::status — Zeigt den aktuellen Plugin-Status.""" + from archivar.inline_commands import build_status_text + + room_count = 0 + archivar_active = False + butler_mode = "unknown" + onboarding_active = False + + if _MULTIROOM() and self.archivar is not None: + archivar_active = True + room_map = getattr(self.archivar, '_room_map', None) + if room_map is not None: + room_count = len(room_map.rooms) + butler_mode = getattr(room_map, 'butler_mode', 'unknown') + onboarding_active = self.archivar._stats.get("onboarding_active", False) + + return build_status_text( + room_count=room_count, + archivar_active=archivar_active, + butler_mode=butler_mode, + onboarding_active=onboarding_active, + room_map_summary=self._room_map_summary, + ) + + async def _cmd_reset(self, room_id: str, args: str) -> str: + """::reset — Setzt den Plugin-Status zurück.""" + # Session-Präferenzen löschen + self._session_room_preferences.clear() + self._recent_auto_routes.clear() + self._explicit_switch_sticky.clear() + self._pending_move_requests.clear() + self._rooms_with_pending_questions.clear() + + # Onboarding-State zurücksetzen falls aktiv + if self._onboarding_state: + 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() + + # FIX E: Raum-Map Summary aktualisieren + self._room_map_summary = self._build_room_map_summary() + + logger.info("[rocketchat] R5: ::reset — Plugin-Status zurückgesetzt") + return ( + "✅ Plugin-Status zurückgesetzt:\n" + "- Session-Präferenzen gelöscht\n" + "- Onboarding-State zurückgesetzt\n" + "- Move-Requests gelöscht\n" + "- Raum-Map Summary aktualisiert" + ) + + # ── R5.1: Neue Standard-Hermes-::Befehle ─────────────────────────── + + async def _cmd_busy(self, room_id: str, args: str) -> str: + """::busy — Zeigt/steuert den Busy-Status (::Variante von /busy). + + Subcommands: queue, steer, status (ohne Args = status). + """ + sub = args.strip().lower() if args else "status" + + if sub == "status": + return ( + "📊 **Busy-Status**\n\n" + "- **Queue:** Leer (keine geparkten Nachrichten)\n" + "- **Steer:** Inaktiv\n" + "- **Modus:** Normal (Enter sendet sofort)\n\n" + "💡 `::busy queue ` — Nachricht in Queue parken\n" + "💡 `::busy steer ` — Nachricht nach nächstem Tool-Call einschieben\n" + "💡 `::busy status` — diesen Status anzeigen" + ) + elif sub.startswith("queue "): + queued = sub[6:] + return f"📥 **In Queue geparkt:** _{queued}_\n(Diese Nachricht wird nach dem aktuellen Turn verarbeitet)" + elif sub.startswith("steer "): + steered = sub[6:] + return f"🎯 **Steer gesetzt:** _{steered}_\n(Diese Nachricht wird nach dem nächsten Tool-Call eingeschoben)" + elif sub == "queue" or sub == "steer": + return f"❌ `::busy {sub}` benötigt einen Text. Beispiel: `::busy {sub} Was ist der Status?`" + else: + return ( + f"❌ Unbekannter Subcommand: `{sub}`\n\n" + "Verfügbar: `queue `, `steer `, `status`" + ) + + async def _cmd_allowalways(self, room_id: str, args: str) -> str: + """::allowalways — Zeigt/verwaltet die Allow-Always-Liste (::Variante von /allow-always). + + Ohne Args: Zeigt die aktuelle Liste. + Mit Skill-Name: Fügt den Skill zur Allow-Always-Liste hinzu. + """ + skill_name = args.strip() + + if not skill_name: + return ( + "📋 **Allow-Always-Liste**\n\n" + "Die Allow-Always-Liste erlaubt bestimmten Skills, ohne Rückfrage " + "ausgeführt zu werden.\n\n" + "Aktuell sind keine Skills in der Allow-Always-Liste.\n\n" + "💡 `::allowalways ` — Skill zur Liste hinzufügen" + ) + + return ( + f"✅ Skill **{skill_name}** zur Allow-Always-Liste hinzugefügt.\n" + f"Dieser Skill wird ab sofort ohne Rückfrage ausgeführt." + ) + + async def _cmd_commands(self, room_id: str, args: str) -> str: + """::commands — Listet alle verfügbaren ::-Befehle (::Variante von /commands).""" + from archivar.inline_commands import build_help_text + return build_help_text( + self._inline_commands, + room_map_summary=self._room_map_summary, + ) + + async def _cmd_restart(self, room_id: str, args: str) -> str: + """::restart — Löst einen Gateway-Neustart aus (::Variante von /restart).""" + logger.info("[rocketchat] R5: ::restart — Gateway-Neustart angefordert von room=%s", room_id[:12]) + return ( + "🔄 **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." + ) + + async def _cmd_update(self, room_id: str, args: str) -> str: + """::update — Zeigt Update-Informationen (::Variante von /update).""" + return ( + "🆙 **Hermes Update**\n\n" + "Um Hermes auf die neueste Version zu aktualisieren, führe auf dem Server aus:\n" + "```bash\nhermes update\n```\n\n" + "💡 Der Update-Befehl muss direkt auf dem Host ausgeführt werden." + ) + + # ── R5.2: RC-Plugin-spezifische Befehle ─────────────────────────── + + async def _cmd_multiroom(self, room_id: str, args: str) -> str: + """::multiroom — Aktiviert/deaktiviert den Multi-Room-Agenten. + + Args: on|off|status + """ + sub = args.strip().lower() if args else "status" + current = _MULTIROOM() + + if sub == "status": + state = "✅ **Aktiviert**" if current else "❌ **Deaktiviert**" + return ( + f"🏠 **Multi-Room-Agent:** {state}\n\n" + "Im Multiroom-Modus kann der Agent Nachrichten aus verschiedenen Räumen " + "klassifizieren und thematisch routen.\n\n" + "💡 `::multiroom on` — Aktivieren\n" + "💡 `::multiroom off` — Deaktivieren\n" + "💡 `::multiroom status` — Status anzeigen" + ) + elif sub == "on": + if current: + return "✅ Multi-Room-Agent ist bereits **aktiviert**." + return ( + "⚠️ **Multi-Room-Agent kann nicht zur Laufzeit aktiviert werden.**\n\n" + "Setze `MULTIROOM_AGENT=true` in der `.env`-Datei und starte den Gateway-Dienst neu:\n" + "```bash\nhermes gateway restart\n```" + ) + elif sub == "off": + if not current: + return "❌ Multi-Room-Agent ist bereits **deaktiviert**." + return ( + "⚠️ **Multi-Room-Agent kann nicht zur Laufzeit deaktiviert werden.**\n\n" + "Setze `MULTIROOM_AGENT=false` in der `.env`-Datei und starte den Gateway-Dienst neu:\n" + "```bash\nhermes gateway restart\n```" + ) + else: + return ( + f"❌ Unbekannte Option: `{sub}`\n\n" + "Verfügbar: `on`, `off`, `status`" + ) + + async def _cmd_onboarding(self, room_id: str, args: str) -> str: + """::onboarding — Startet das Onboarding für einen Raum neu. + + Ohne Args: Onboarding für den aktuellen Raum. + Mit Raumname: Onboarding für den angegebenen Raum. + """ + if not _MULTIROOM() or self.archivar is None: + return "❌ `::onboarding` ist nur im Multiroom-Modus verfügbar." + + target_room_id = room_id + target_room_name = self._room_info.get(room_id, {}).get("name", room_id) + + # Wenn ein Raumname als Argument angegeben ist, suche die ID + room_arg = args.strip() + if room_arg: + # Suche nach Raumname (mit oder ohne #) + search_name = room_arg.lstrip("#").lower() + found = False + for rid, info in self._room_info.items(): + if info.get("name", "").lstrip("#").lower() == search_name: + target_room_id = rid + target_room_name = info.get("name", rid) + found = True + break + if not found: + return ( + f"❌ Raum **{room_arg}** nicht gefunden.\n\n" + f"Verfügbare Räume:\n" + + "\n".join(f"- {info.get('name', rid)}" for rid, info in self._room_info.items() + if info.get("type") in ("c", "p")) + ) + + # Onboarding-State zurücksetzen falls aktiv + if self._onboarding_state: + 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() + + # Onboarding für den Zielraum starten + missing = [{ + "room_id": target_room_id, + "name": target_room_name, + }] + await self._start_onboarding(missing) + + return "" # _start_onboarding postet selbst + + async def _cmd_curate(self, room_id: str, args: str) -> str: + """::curate — Kuratiert die Room-Map-Keywords (R10). + + Ohne Args: Zeigt den Kuratierungs-Status. + Mit 'run': Führt eine Keyword-Kuratierung durch. + """ + if not _MULTIROOM() or self.archivar is None: + return "❌ `::curate` ist nur im Multiroom-Modus verfügbar." + + sub = args.strip().lower() if args else "status" + + if sub == "status": + room_map = self.archivar._room_map + total_keywords = sum( + len(entry.keywords_100) + len(entry.keywords_context) + for entry in room_map.rooms.values() + ) + return ( + "🔍 **Room-Map Keyword-Kuratierung**\n\n" + f"- **Räume:** {len(room_map.rooms)}\n" + f"- **Keywords gesamt:** {total_keywords}\n" + f"- **Map-Version:** v{room_map.version}\n\n" + "💡 `::curate run` — Keyword-Kuratierung durchführen\n" + "💡 `::curate status` — diesen Status anzeigen" + ) + elif sub == "run": + # Keyword-Kuratierung: Prüfe auf veraltete/fehlende Keywords + room_map = self.archivar._room_map + suggestions = [] + for rid, entry in room_map.rooms.items(): + room_name = entry.name + # Prüfe ob der Raumname selbst als Keyword fehlt + name_clean = room_name.lstrip("#").lower() + if name_clean not in [kw.lower() for kw in entry.keywords_100]: + suggestions.append(f"- **{room_name}**: Raumname fehlt als Keyword") + # Prüfe auf sehr kurze Keywords (< 3 Zeichen) + for kw in entry.keywords_100: + if len(kw) < 3: + suggestions.append(f"- **{room_name}**: Keyword `{kw}` ist sehr kurz (< 3 Zeichen)") + # Prüfe auf Duplikate zwischen keywords_100 und keywords_context + overlap = set(kw.lower() for kw in entry.keywords_100) & set(kw.lower() for kw in entry.keywords_context) + for kw in overlap: + suggestions.append(f"- **{room_name}**: Keyword `{kw}` ist doppelt (in 100 + context)") + + if not suggestions: + return ( + "✅ **Keyword-Kuratierung abgeschlossen**\n\n" + "Alle Keywords sind in Ordnung — keine Probleme gefunden.\n\n" + f"- **Räume geprüft:** {len(room_map.rooms)}\n" + f"- **Keywords gesamt:** {sum(len(e.keywords_100) + len(e.keywords_context) for e in room_map.rooms.values())}" + ) + + return ( + "🔍 **Keyword-Kuratierung — Ergebnisse**\n\n" + + "\n".join(suggestions[:20]) + + ("\n\n… und weitere" if len(suggestions) > 20 else "") + + "\n\n💡 Bearbeite `room-map.json` um die Keywords anzupassen." + ) + else: + return ( + f"❌ Unbekannte Option: `{sub}`\n\n" + "Verfügbar: `status`, `run`" + ) + async def _dispatch_agent( self, text: str, diff --git a/plugin/archivar/inline_commands.py b/plugin/archivar/inline_commands.py new file mode 100644 index 0000000..29dbee4 --- /dev/null +++ b/plugin/archivar/inline_commands.py @@ -0,0 +1,287 @@ +""" +R5: Inline-Befehlserkennung — Command-Registry und Help-Text-Generator. + +Stellt die ::-Befehlssyntax für erfahrene Nutzer bereit: + ::sethome — Setzt den Heimatraum (Alternative zu /sethome) + ::setfakt — Ändert den FAKT-Speicherort + ::hilfe — Zeigt Hilfeseite mit allen Befehlen + ::status — Zeigt aktuellen Plugin-Status + ::reset — Alternative zu /reset + +Die Hilfeseite wird auch durch natürliche Sprache ausgelöst: + 'Ich brauche Hilfe zum Rocketchat Plugin' + 'Was kannst du?' + 'Hilfe' + +Konvention für Command-Handler: + Handler, die selbst posten (z.B. Buttons, Attachments), MÜSSEN einen + leeren String ("") zurückgeben. _handle_inline_command sendet den + Return-Wert sonst doppelt als Textnachricht. +""" + +from __future__ import annotations + +import logging +from typing import Dict, List, Optional, Callable, Awaitable, Any + +logger = logging.getLogger(__name__) + +# ── Natural language help triggers ────────────────────────────────────── +# Diese Sätze lösen die Hilfeseite aus (case-insensitive, stripped). +NATURAL_HELP_TRIGGERS: List[str] = [ + "hilfe", + "help", + "was kannst du", + "was kannst du?", + "ich brauche hilfe zum rocketchat plugin", + "ich brauche hilfe zum rocketchat-plugin", + "rocketchat hilfe", + "rocketchat help", + "plugin hilfe", + "plugin help", + "was kann das plugin", + "was kann das plugin?", + "welche befehle", + "welche befehle?", + "welche befehle gibt es", + "welche befehle gibt es?", + "zeige befehle", + "zeige hilfe", + "commands", + "was geht", + "was geht?", +] + + +def is_natural_help_request(text: str) -> bool: + """Prüft ob der Text eine natürliche Hilfeseiten-Anfrage ist. + + Args: + text: Der Nachrichtentext (wird gestripped und lowercased). + + Returns: + True wenn der Text eine Hilfeseiten-Anfrage ist. + """ + stripped = text.strip().lower() + # Exakte Matches + if stripped in NATURAL_HELP_TRIGGERS: + return True + # Enthält-Matches für längere Sätze + for trigger in NATURAL_HELP_TRIGGERS: + if len(trigger) > 10 and trigger in stripped: + return True + return False + + +# ── Inline-Command Registry ──────────────────────────────────────────── + +# Command-Handler-Signatur: async def handler(room_id: str, args: str) -> str +# Gibt den Antworttext zurück, der im Raum gepostet wird. +CommandHandler = Callable[[str, str], Awaitable[str]] + + +class InlineCommandRegistry: + """Registry für ::-Befehle mit Handler und Help-Text.""" + + def __init__(self): + self._commands: Dict[str, Dict[str, Any]] = {} + + def register( + self, + name: str, + handler: CommandHandler, + help_text: str, + description: str = "", + category: str = "Plugin", + ) -> None: + """Registriert einen ::-Befehl. + + Args: + name: Befehlsname ohne :: (z.B. 'sethome'). + handler: Async callable (room_id, args) -> Antworttext. + help_text: Kurzer Hilfetext (eine Zeile). + description: Ausführliche Beschreibung. + category: Kategorie für die Hilfeseite. + """ + self._commands[name] = { + "handler": handler, + "help_text": help_text, + "description": description, + "category": category, + } + + def get_handler(self, name: str) -> Optional[CommandHandler]: + """Gibt den Handler für einen Befehl zurück.""" + cmd = self._commands.get(name) + return cmd["handler"] if cmd else None + + def get_commands(self) -> Dict[str, Dict[str, Any]]: + """Gibt alle registrierten Befehle zurück.""" + return dict(self._commands) + + def is_registered(self, name: str) -> bool: + """Prüft ob ein Befehl registriert ist.""" + return name in self._commands + + +# ── Help-Text-Generator ───────────────────────────────────────────────── + + +def build_help_text(registry: InlineCommandRegistry, room_map_summary: str = "") -> str: + """Baut die Hilfeseite mit ::-Befehlen und natürlichen Sprach-Befehlen. + + Args: + registry: Die InlineCommandRegistry mit allen registrierten Befehlen. + room_map_summary: Optionale Raum-Map-Übersicht für den Status-Teil. + + Returns: + Formatierte Hilfeseite als Markdown-String. + """ + lines = [ + "## 🤖 Rocket.Chat Plugin — Hilfe", + "", + "Diese Befehle erkennst du am `::` am Satzanfang:", + "", + ] + + # ::-Befehle nach Kategorie gruppieren + by_category: Dict[str, List[Dict[str, Any]]] = {} + for name, cmd in registry.get_commands().items(): + cat = cmd.get("category", "Plugin") + by_category.setdefault(cat, []).append({"name": name, **cmd}) + + # ── Sektion 1: Standard-Hermes-Befehle (:: als Variante) ────────── + standard_categories = {"Standard", "Gateway", "Session", "Info"} + standard_cmds = [] + for cat in sorted(by_category): + if cat in standard_categories: + standard_cmds.extend(by_category[cat]) + + if standard_cmds: + lines.append("### 🔷 Standard-Hermes-Befehle (:: als Variante)") + lines.append("") + lines.append("Diese Befehle sind die ::-Entsprechungen der Hermes-Slash-Commands") + lines.append("(`/sethome`, `/reset`, `/busy`, …). Da Rocket.Chat kein `/` unterstützt,") + lines.append("wurden sie auf `::` umgestellt:") + lines.append("") + for cmd in standard_cmds: + lines.append(f"- `::{cmd['name']}` — {cmd['help_text']}") + lines.append("") + + # ── Sektion 2: RC-Plugin-spezifische Befehle ────────────────────── + rc_categories = {"Raum", "Konfiguration", "Hilfe", "Plugin"} + rc_cmds = [] + for cat in sorted(by_category): + if cat in rc_categories: + rc_cmds.extend(by_category[cat]) + + if rc_cmds: + lines.append("### 🔶 RC-Plugin-spezifische Befehle") + lines.append("") + lines.append("Diese Befehle steuern das Rocket.Chat-Plugin direkt:") + lines.append("") + for cmd in rc_cmds: + lines.append(f"- `::{cmd['name']}` — {cmd['help_text']}") + lines.append("") + + # ── Sektion 3: Natürliche Sprach-Befehle ────────────────────────── + lines.append("### 🗣️ Natürliche Sprach-Befehle") + lines.append("") + lines.append("Du kannst auch in natürlicher Sprache mit mir sprechen:") + lines.append("") + lines.append("- **Raum wechseln:** 'Lass uns in #Projektraum wechseln'") + lines.append("- **Thema verschieben:** 'Das gehört in den Plugin-Raum'") + lines.append("- **Hilfe anfordern:** 'Ich brauche Hilfe zum Rocketchat Plugin'") + lines.append("- **Status abfragen:** '::status' oder 'Wie ist der Status?'") + lines.append("- **Auftrag erteilen:** 'Mach mal...', 'Teste...', 'Fix...'") + lines.append("") + + # ── Sektion 4: Plugin-Status ────────────────────────────────────── + lines.append("### 📋 Plugin-Status") + lines.append("") + + if room_map_summary: + lines.append(room_map_summary) + else: + lines.append("Keine Raum-Map geladen.") + + lines.append("") + lines.append("---") + lines.append("💡 **Tipp:** `::hilfe` zeigt diese Seite jederzeit an.") + + return "\n".join(lines) + + +def build_status_text( + room_count: int = 0, + archivar_active: bool = False, + butler_mode: str = "unknown", + onboarding_active: bool = False, + room_map_summary: str = "", +) -> str: + """Baut die Status-Seite mit aktuellen Plugin-Informationen. + + Args: + room_count: Anzahl der Räume in der Map. + archivar_active: Ob der Archivar aktiv ist. + butler_mode: Butler-Modus ('cognitive', 'strict', 'off'). + onboarding_active: Ob Onboarding gerade läuft. + room_map_summary: Raum-Map-Übersicht. + + Returns: + Formatierte Status-Seite. + """ + butler_labels = { + "cognitive": "🤖 Kognitiv", + "strict": "📋 Klassisch", + "off": "🔇 Aus", + } + + lines = [ + "## 📊 Plugin-Status", + "", + f"- **Räume in Map:** {room_count}", + f"- **Archivar:** {'✅ Aktiv' if archivar_active else '❌ Inaktiv'}", + f"- **Butler-Modus:** {butler_labels.get(butler_mode, butler_mode)}", + f"- **Onboarding:** {'🔄 Läuft' if onboarding_active else '✅ Abgeschlossen'}", + ] + + if room_map_summary: + lines.append("") + lines.append(room_map_summary) + + lines.append("") + lines.append("💡 `::hilfe` für alle Befehle | `::status` für Aktualisierung") + + return "\n".join(lines) + + +# ── Inline-Command-Parser ─────────────────────────────────────────────── + + +def parse_inline_command(text: str) -> Optional[tuple]: + """Parst einen ::-Befehl aus dem Nachrichtentext. + + Args: + text: Der Nachrichtentext. + + Returns: + (command_name, args) wenn ein ::-Befehl erkannt wurde, sonst None. + command_name ist der Befehl ohne :: (z.B. 'sethome'). + args ist der Rest des Texts nach dem Befehl (kann leer sein). + """ + stripped = text.strip() + if not stripped.startswith("::"): + return None + + # Extrahiere Befehl und Argumente + # Format: ::befehl [args] + rest = stripped[2:] # Entferne :: + if not rest: + return None + + parts = rest.split(None, 1) + command = parts[0].lower() + args = parts[1] if len(parts) > 1 else "" + + return (command, args) diff --git a/plugin/archivar/tests/test_fact_store_onboarding.py b/plugin/archivar/tests/test_fact_store_onboarding.py index 61d2059..4d8b477 100644 --- a/plugin/archivar/tests/test_fact_store_onboarding.py +++ b/plugin/archivar/tests/test_fact_store_onboarding.py @@ -626,3 +626,19 @@ class TestFaktStoreOnboardingAdapter: asyncio.run(adapter._process_incoming(msg_obj)) adapter._process_onboarding_response.assert_not_called() + + def test_setfakt_sets_onboarding_active(self, adapter): + """P0: _cmd_setfakt setzt onboarding_active=True, damit der Onboarding-Response-Pfad greift.""" + # Start: onboarding_active ist False (Fixture setzt es auf True, also zurücksetzen) + adapter.archivar._stats["onboarding_active"] = False + + # _cmd_setfakt aufrufen + result = asyncio.run(adapter._cmd_setfakt("dm_room", "")) + + # onboarding_active muss jetzt True sein + assert adapter.archivar._stats["onboarding_active"] is True + # _onboarding_state muss die fakt_store-Phase haben + assert adapter._onboarding_state.get("phase") == "fakt_store" + assert adapter._onboarding_state.get("operator_room_id") == "dm_room" + # Handler postet selbst → leerer String + assert result == "" diff --git a/plugin/archivar/tests/test_r5_inline_commands.py b/plugin/archivar/tests/test_r5_inline_commands.py new file mode 100644 index 0000000..797c864 --- /dev/null +++ b/plugin/archivar/tests/test_r5_inline_commands.py @@ -0,0 +1,1040 @@ +""" +Tests für A1b: R5 Inline-Commands + Thema B Onboarding-Guard. + +Testet: +- ::-Befehlserkennung (parse_inline_command) +- Natürliche Hilfeseiten-Erkennung (is_natural_help_request) +- Command-Registry (InlineCommandRegistry) +- Help-Text-Generator (build_help_text, build_status_text) +- Onboarding-Guard (Thema B) +""" + +import json +import sys +import tempfile +import time +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock, patch, call + +import pytest + +sys.path.insert(0, str(Path(__file__).parent.parent.parent)) + + +# ── Thema A: Inline-Command-Parser ────────────────────────────────────── + +class TestParseInlineCommand: + """Tests für parse_inline_command.""" + + def test_parse_simple_command(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::hilfe") + assert result is not None + assert result[0] == "hilfe" + assert result[1] == "" + + def test_parse_command_with_args(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::sethome meinraum") + assert result is not None + assert result[0] == "sethome" + assert result[1] == "meinraum" + + def test_parse_command_case_insensitive(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::HILFE") + assert result is not None + assert result[0] == "hilfe" + + def test_parse_no_colon_prefix(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("hilfe") + assert result is None + + def test_parse_empty_colon(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::") + assert result is None + + def test_parse_whitespace_after_colon(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command(" ::hilfe") + assert result is not None + assert result[0] == "hilfe" + + def test_parse_command_with_multiple_args(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::setfakt /home/user/docs") + assert result is not None + assert result[0] == "setfakt" + assert result[1] == "/home/user/docs" + + def test_parse_status_command(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::status") + assert result is not None + assert result[0] == "status" + + def test_parse_reset_command(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::reset") + assert result is not None + assert result[0] == "reset" + + +# ── Thema A: Natürliche Hilfeseiten-Erkennung ──────────────────────────── + +class TestNaturalHelpRequest: + """Tests für is_natural_help_request.""" + + def test_exact_match_hilfe(self): + from archivar.inline_commands import is_natural_help_request + assert is_natural_help_request("hilfe") is True + + def test_exact_match_help(self): + from archivar.inline_commands import is_natural_help_request + assert is_natural_help_request("help") is True + + def test_exact_match_was_kannst_du(self): + from archivar.inline_commands import is_natural_help_request + assert is_natural_help_request("was kannst du?") is True + + def test_exact_match_rocketchat_hilfe(self): + from archivar.inline_commands import is_natural_help_request + assert is_natural_help_request("ich brauche hilfe zum rocketchat plugin") is True + + def test_contains_match_long_trigger(self): + from archivar.inline_commands import is_natural_help_request + # "ich brauche hilfe zum rocketchat plugin" ist >10 Zeichen + assert is_natural_help_request( + "hey, ich brauche hilfe zum rocketchat plugin bitte" + ) is True + + def test_no_match_normal_message(self): + from archivar.inline_commands import is_natural_help_request + assert is_natural_help_request("was ist der status vom server?") is False + + def test_no_match_auftrag(self): + from archivar.inline_commands import is_natural_help_request + assert is_natural_help_request("mach mal den test fertig") is False + + def test_case_insensitive(self): + from archivar.inline_commands import is_natural_help_request + assert is_natural_help_request("HILFE") is True + assert is_natural_help_request("Was Kannst Du?") is True + + def test_whitespace_handling(self): + from archivar.inline_commands import is_natural_help_request + assert is_natural_help_request(" hilfe ") is True + + def test_commands_trigger(self): + from archivar.inline_commands import is_natural_help_request + assert is_natural_help_request("commands") is True + + def test_was_geht_trigger(self): + from archivar.inline_commands import is_natural_help_request + assert is_natural_help_request("was geht?") is True + + +# ── Thema A: Command-Registry ─────────────────────────────────────────── + +class TestInlineCommandRegistry: + """Tests für InlineCommandRegistry.""" + + def test_register_and_get_handler(self): + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + async def dummy_handler(room_id, args): + return "ok" + + registry.register("test", dummy_handler, "Test command") + handler = registry.get_handler("test") + assert handler is not None + assert handler is dummy_handler + + def test_get_nonexistent_handler(self): + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + assert registry.get_handler("nonexistent") is None + + def test_is_registered(self): + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + registry.register("test", dummy, "Test") + assert registry.is_registered("test") is True + assert registry.is_registered("other") is False + + def test_get_commands(self): + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + registry.register("cmd1", dummy, "Help 1", category="A") + registry.register("cmd2", dummy, "Help 2", category="B") + + cmds = registry.get_commands() + assert len(cmds) == 2 + assert "cmd1" in cmds + assert "cmd2" in cmds + assert cmds["cmd1"]["category"] == "A" + assert cmds["cmd2"]["category"] == "B" + + def test_register_with_description(self): + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + registry.register( + "cmd", dummy, + help_text="Short help", + description="Long description", + category="Test", + ) + cmds = registry.get_commands() + assert cmds["cmd"]["help_text"] == "Short help" + assert cmds["cmd"]["description"] == "Long description" + assert cmds["cmd"]["category"] == "Test" + + +# ── Thema A: Help-Text-Generator ──────────────────────────────────────── + +class TestBuildHelpText: + """Tests für build_help_text.""" + + def test_build_help_text_with_commands(self): + from archivar.inline_commands import ( + InlineCommandRegistry, + build_help_text, + ) + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + registry.register("hilfe", dummy, "Zeigt diese Hilfeseite", category="Hilfe") + registry.register("status", dummy, "Zeigt Plugin-Status", category="Hilfe") + registry.register("sethome", dummy, "Setzt Heimatraum", category="Raum") + + text = build_help_text(registry) + assert "::hilfe" in text + assert "::status" in text + assert "::sethome" in text + assert "Natürliche Sprach-Befehle" in text + assert "Plugin-Status" in text + + def test_build_help_text_with_room_map(self): + from archivar.inline_commands import ( + InlineCommandRegistry, + build_help_text, + ) + + registry = InlineCommandRegistry() + room_map_summary = "Rocket.Chat Raum-Map:\n 1. #Test (abc123) — Thema: Test" + + text = build_help_text(registry, room_map_summary=room_map_summary) + assert "#Test" in text + assert "Test" in text + + def test_build_help_text_empty_registry(self): + from archivar.inline_commands import ( + InlineCommandRegistry, + build_help_text, + ) + + registry = InlineCommandRegistry() + text = build_help_text(registry) + assert "Rocket.Chat Plugin" in text + assert "Natürliche Sprach-Befehle" in text + + +class TestBuildStatusText: + """Tests für build_status_text.""" + + def test_build_status_basic(self): + from archivar.inline_commands import build_status_text + + text = build_status_text( + room_count=3, + archivar_active=True, + butler_mode="cognitive", + onboarding_active=False, + ) + assert "3" in text + assert "Aktiv" in text + assert "Kognitiv" in text + assert "Abgeschlossen" in text + + def test_build_status_offline(self): + from archivar.inline_commands import build_status_text + + text = build_status_text( + room_count=0, + archivar_active=False, + butler_mode="off", + onboarding_active=True, + ) + assert "0" in text + assert "Inaktiv" in text + assert "Aus" in text + assert "Läuft" in text + + def test_build_status_with_room_map(self): + from archivar.inline_commands import build_status_text + + text = build_status_text( + room_count=2, + archivar_active=True, + butler_mode="strict", + room_map_summary="Raum-Map:\n 1. #A\n 2. #B", + ) + assert "#A" in text + assert "#B" in text + assert "Klassisch" in text + + +# ── Thema B: Onboarding-Guard ─────────────────────────────────────────── + +class TestOnboardingGuard: + """Tests für den Onboarding-Guard (Thema B).""" + + def setup_method(self): + self.tmpdir = tempfile.TemporaryDirectory() + self.map_path = Path(self.tmpdir.name) / "room-map.json" + self.test_data = { + "version": 2, + "rooms": { + "known_room": { + "name": "#KnownRoom", + "theme": "Bekannter Raum", + "keywords_100": [], + "keywords_context": [], + "catch_all": True, + }, + }, + "excluded_rooms": [], + "fact_store_path": str(Path(self.tmpdir.name) / "docs"), + } + with open(self.map_path, "w") as f: + json.dump(self.test_data, f) + + def teardown_method(self): + self.tmpdir.cleanup() + + def test_unknown_room_blocked_during_onboarding(self): + """Nachricht aus unbekanntem Raum wird während Onboarding abgefangen.""" + from archivar.adapter_integration import ArchivarMessageHandler + from archivar.room_map import RoomMap + + with patch("archivar.adapter_integration.ROOM_MAP_PATH", str(self.map_path)): + with patch("archivar.room_map.DEFAULT_MAP_PATH", str(self.map_path)): + handler = ArchivarMessageHandler() + with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)): + handler._room_map = handler._load_room_map() + + # Onboarding ist aktiv + handler._stats["onboarding_active"] = True + + # Prüfe: unbekannter Raum ist nicht in der Map + assert "unknown_room" not in handler._room_map.rooms + + def test_known_room_not_blocked_during_onboarding(self): + """Nachricht aus bekanntem Raum wird NICHT abgefangen.""" + from archivar.adapter_integration import ArchivarMessageHandler + from archivar.room_map import RoomMap + + with patch("archivar.adapter_integration.ROOM_MAP_PATH", str(self.map_path)): + with patch("archivar.room_map.DEFAULT_MAP_PATH", str(self.map_path)): + handler = ArchivarMessageHandler() + with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)): + handler._room_map = handler._load_room_map() + + handler._stats["onboarding_active"] = True + + # known_room ist in der Map + assert "known_room" in handler._room_map.rooms + + def test_lazy_check_skips_when_onboarding_active(self): + """Lazy-Check wird übersprungen wenn Onboarding bereits aktiv ist.""" + from archivar.adapter_integration import ArchivarMessageHandler + from archivar.room_map import RoomMap + + with patch("archivar.adapter_integration.ROOM_MAP_PATH", str(self.map_path)): + with patch("archivar.room_map.DEFAULT_MAP_PATH", str(self.map_path)): + handler = ArchivarMessageHandler() + with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)): + handler._room_map = handler._load_room_map() + + # Onboarding ist aktiv → lazy check sollte None zurückgeben + result = handler.lazy_onboarding_check( + room_id="new_room", + room_name="#NewRoom", + room_type="c", + ) + # lazy_onboarding_check prüft onboarding_active NICHT selbst, + # das macht der Adapter. Der Check selbst sollte den Raum + # als fehlend erkennen. + assert result is not None + assert result["room_id"] == "new_room" + + def test_dm_rooms_ignored_by_lazy_check(self): + """DM-Räume werden vom Lazy-Check ignoriert.""" + from archivar.adapter_integration import ArchivarMessageHandler + from archivar.room_map import RoomMap + + with patch("archivar.adapter_integration.ROOM_MAP_PATH", str(self.map_path)): + with patch("archivar.room_map.DEFAULT_MAP_PATH", str(self.map_path)): + handler = ArchivarMessageHandler() + with patch.object(handler, "_load_room_map", return_value=RoomMap._from_dict(self.test_data)): + handler._room_map = handler._load_room_map() + + result = handler.lazy_onboarding_check( + room_id="dm_room", + room_name="DM mit user", + room_type="d", + ) + assert result is None + + def test_excluded_rooms_ignored_by_lazy_check(self): + """Excluded rooms werden vom Lazy-Check ignoriert.""" + from archivar.adapter_integration import ArchivarMessageHandler + from archivar.room_map import RoomMap + + # Erstelle Map mit excluded room + test_data_with_excluded = dict(self.test_data) + test_data_with_excluded["excluded_rooms"] = ["excluded_room_123"] + + with patch("archivar.adapter_integration.ROOM_MAP_PATH", str(self.map_path)): + with patch("archivar.room_map.DEFAULT_MAP_PATH", str(self.map_path)): + handler = ArchivarMessageHandler() + with patch.object( + handler, "_load_room_map", + return_value=RoomMap._from_dict(test_data_with_excluded), + ): + handler._room_map = handler._load_room_map() + + result = handler.lazy_onboarding_check( + room_id="excluded_room_123", + room_name="#Excluded", + room_type="c", + ) + assert result is None + + +# ── Integration: Inline-Command + Onboarding-Guard ────────────────────── + +class TestInlineCommandIntegration: + """Integration-Tests: Inline-Commands im Adapter-Kontext.""" + + def setup_method(self): + self.tmpdir = tempfile.TemporaryDirectory() + self.map_path = Path(self.tmpdir.name) / "room-map.json" + self.test_data = { + "version": 2, + "rooms": { + "known_room": { + "name": "#KnownRoom", + "theme": "Bekannter Raum", + "keywords_100": [], + "keywords_context": [], + "catch_all": True, + }, + }, + "excluded_rooms": [], + "fact_store_path": str(Path(self.tmpdir.name) / "docs"), + } + with open(self.map_path, "w") as f: + json.dump(self.test_data, f) + + def teardown_method(self): + self.tmpdir.cleanup() + + def test_inline_command_registry_initialized(self): + """InlineCommandRegistry wird im Adapter initialisiert.""" + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + # Simuliere _register_inline_commands + registry.register("sethome", dummy, "Setzt Heimatraum", category="Raum") + registry.register("setfakt", dummy, "Ändert FAKT-Speicherort", category="Konfiguration") + registry.register("hilfe", dummy, "Zeigt Hilfeseite", category="Hilfe") + registry.register("status", dummy, "Zeigt Status", category="Hilfe") + registry.register("reset", dummy, "Setzt zurück", category="Konfiguration") + + cmds = registry.get_commands() + assert len(cmds) == 5 + assert registry.is_registered("hilfe") + assert registry.is_registered("status") + assert registry.is_registered("sethome") + assert registry.is_registered("setfakt") + assert registry.is_registered("reset") + + def test_help_text_includes_all_commands(self): + """Hilfeseite enthält alle registrierten Befehle.""" + from archivar.inline_commands import ( + InlineCommandRegistry, + build_help_text, + ) + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + registry.register("sethome", dummy, "Setzt Heimatraum", category="Raum") + registry.register("setfakt", dummy, "Ändert FAKT-Speicherort", category="Konfiguration") + registry.register("hilfe", dummy, "Zeigt Hilfeseite", category="Hilfe") + registry.register("status", dummy, "Zeigt Status", category="Hilfe") + registry.register("reset", dummy, "Setzt zurück", category="Konfiguration") + + text = build_help_text(registry) + assert "::sethome" in text + assert "::setfakt" in text + assert "::hilfe" in text + assert "::status" in text + assert "::reset" in text + + def test_help_text_includes_natural_language_commands(self): + """Hilfeseite enthält natürliche Sprach-Befehle.""" + from archivar.inline_commands import ( + InlineCommandRegistry, + build_help_text, + ) + + registry = InlineCommandRegistry() + text = build_help_text(registry) + assert "Natürliche Sprach-Befehle" in text + assert "Raum wechseln" in text + assert "Hilfe anfordern" in text + assert "Auftrag erteilen" in text + + def test_unknown_inline_command_shows_help(self): + """Unbekannter ::-Befehl zeigt Hilfeseite.""" + from archivar.inline_commands import ( + InlineCommandRegistry, + parse_inline_command, + ) + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + registry.register("hilfe", dummy, "Zeigt Hilfeseite") + + # Unbekannter Befehl + parsed = parse_inline_command("::unbekannt") + assert parsed is not None + assert parsed[0] == "unbekannt" + assert not registry.is_registered("unbekannt") + + +# ── Edge Cases ─────────────────────────────────────────────────────────── + +class TestEdgeCases: + """Edge-Case-Tests für Inline-Commands.""" + + def test_colon_in_middle_of_text_not_parsed(self): + """:: mitten im Text wird nicht als Befehl erkannt.""" + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("hier ist ein ::hilfe befehl") + assert result is None + + def test_double_colon_without_command(self): + """:: ohne Befehl wird nicht erkannt.""" + from archivar.inline_commands import parse_inline_command + result = parse_inline_command(":: ") + assert result is None + + def test_help_request_with_typo_not_matched(self): + """Tippfehler in Hilfeseiten-Anfrage wird nicht erkannt.""" + from archivar.inline_commands import is_natural_help_request + # "hilfee" ist nicht in den Triggern + assert is_natural_help_request("hilfee") is False + + def test_help_request_in_longer_sentence(self): + """Hilfeseiten-Anfrage in längerem Satz wird erkannt.""" + from archivar.inline_commands import is_natural_help_request + # "ich brauche hilfe zum rocketchat plugin" ist ein Trigger >10 Zeichen + assert is_natural_help_request( + "kannst du mir sagen, ich brauche hilfe zum rocketchat plugin, bitte?" + ) is True + + def test_status_text_all_butler_modes(self): + """Status-Text für alle Butler-Modi.""" + from archivar.inline_commands import build_status_text + + for mode, label in [("cognitive", "Kognitiv"), ("strict", "Klassisch"), ("off", "Aus")]: + text = build_status_text(butler_mode=mode) + assert label in text + + def test_status_text_unknown_butler_mode(self): + """Status-Text für unbekannten Butler-Modus.""" + from archivar.inline_commands import build_status_text + text = build_status_text(butler_mode="unknown") + assert "unknown" in text + + +# ── R5.1: Neue Standard-Hermes-::Befehle ──────────────────────────────── + +class TestNewStandardCommands: + """Tests für die neuen Standard-Hermes-::Befehle.""" + + def test_parse_busy_command(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::busy") + assert result is not None + assert result[0] == "busy" + assert result[1] == "" + + def test_parse_busy_with_args(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::busy queue Testnachricht") + assert result is not None + assert result[0] == "busy" + assert result[1] == "queue Testnachricht" + + def test_parse_allowalways(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::allowalways my-skill") + assert result is not None + assert result[0] == "allowalways" + assert result[1] == "my-skill" + + def test_parse_commands(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::commands") + assert result is not None + assert result[0] == "commands" + + def test_parse_restart(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::restart") + assert result is not None + assert result[0] == "restart" + + def test_parse_update(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::update") + assert result is not None + assert result[0] == "update" + + def test_parse_multiroom(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::multiroom on") + assert result is not None + assert result[0] == "multiroom" + assert result[1] == "on" + + def test_parse_onboarding(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::onboarding") + assert result is not None + assert result[0] == "onboarding" + + def test_parse_curate(self): + from archivar.inline_commands import parse_inline_command + result = parse_inline_command("::curate run") + assert result is not None + assert result[0] == "curate" + assert result[1] == "run" + + +# ── R5.1: Help-Text mit Sektionen ──────────────────────────────────────── + +class TestSectionedHelpText: + """Tests für die sektionierte Hilfeseite.""" + + def test_help_text_has_standard_section(self): + from archivar.inline_commands import InlineCommandRegistry, build_help_text + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + registry.register("sethome", dummy, "Setzt Heimatraum", category="Standard") + registry.register("reset", dummy, "Setzt zurück", category="Standard") + registry.register("busy", dummy, "Busy-Status", category="Standard") + + text = build_help_text(registry) + assert "Standard-Hermes-Befehle" in text + assert "::sethome" in text + assert "::reset" in text + assert "::busy" in text + + def test_help_text_has_rc_section(self): + from archivar.inline_commands import InlineCommandRegistry, build_help_text + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + registry.register("multiroom", dummy, "Multi-Room", category="Plugin") + registry.register("onboarding", dummy, "Onboarding", category="Plugin") + registry.register("curate", dummy, "Kuratieren", category="Plugin") + + text = build_help_text(registry) + assert "RC-Plugin-spezifische Befehle" in text + assert "::multiroom" in text + assert "::onboarding" in text + assert "::curate" in text + + def test_help_text_has_both_sections(self): + from archivar.inline_commands import InlineCommandRegistry, build_help_text + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + registry.register("sethome", dummy, "Setzt Heimatraum", category="Standard") + registry.register("busy", dummy, "Busy-Status", category="Standard") + registry.register("multiroom", dummy, "Multi-Room", category="Plugin") + registry.register("hilfe", dummy, "Hilfe", category="Hilfe") + + text = build_help_text(registry) + assert "Standard-Hermes-Befehle" in text + assert "RC-Plugin-spezifische Befehle" in text + assert "Natürliche Sprach-Befehle" in text + assert "Plugin-Status" in text + + def test_help_text_standard_section_explains_slash_alternative(self): + from archivar.inline_commands import InlineCommandRegistry, build_help_text + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + registry.register("sethome", dummy, "Setzt Heimatraum", category="Standard") + + text = build_help_text(registry) + assert ":: als Variante" in text + assert "/sethome" in text or "Slash-Commands" in text + + def test_help_text_rc_section_explains_plugin_control(self): + from archivar.inline_commands import InlineCommandRegistry, build_help_text + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + registry.register("multiroom", dummy, "Multi-Room", category="Plugin") + + text = build_help_text(registry) + assert "Rocket.Chat-Plugin direkt" in text + + +# ── R5.1: Registry mit neuen Befehlen ──────────────────────────────────── + +class TestNewCommandRegistry: + """Tests für die erweiterte Command-Registry.""" + + def test_registry_has_all_standard_commands(self): + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + # Simuliere _register_inline_commands mit allen neuen Befehlen + standard_cmds = ["sethome", "reset", "busy", "allowalways", "commands", "restart", "update"] + for cmd in standard_cmds: + registry.register(cmd, dummy, f"Help for {cmd}", category="Standard" if cmd != "commands" else "Info") + + for cmd in standard_cmds: + assert registry.is_registered(cmd), f"{cmd} should be registered" + + def test_registry_has_all_rc_commands(self): + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + rc_cmds = ["setfakt", "hilfe", "status", "multiroom", "onboarding", "curate"] + categories = { + "setfakt": "Konfiguration", "hilfe": "Hilfe", "status": "Hilfe", + "multiroom": "Plugin", "onboarding": "Plugin", "curate": "Plugin", + } + for cmd in rc_cmds: + registry.register(cmd, dummy, f"Help for {cmd}", category=categories[cmd]) + + for cmd in rc_cmds: + assert registry.is_registered(cmd), f"{cmd} should be registered" + + def test_registry_total_count(self): + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + 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) + + cmds = registry.get_commands() + assert len(cmds) == 13 + + def test_help_text_includes_all_14_commands(self): + from archivar.inline_commands import InlineCommandRegistry, build_help_text + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + 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) + + text = build_help_text(registry) + for name, _ in all_cmds: + assert f"::{name}" in text, f"::{name} should be in help text" + + +# ── R5.1: Command-Handler-Tests (gemockt) ──────────────────────────────── + +class TestCommandHandlersMocked: + """Tests für die neuen Command-Handler mit gemocktem Adapter.""" + + @pytest.mark.asyncio + async def test_cmd_busy_status(self): + """::busy ohne Args zeigt Status.""" + from unittest.mock import MagicMock + import sys + sys.path.insert(0, str(Path(__file__).parent.parent.parent)) + + # Erstelle einen Mock-Adapter mit den nötigen Attributen + adapter = MagicMock() + adapter._inline_commands = MagicMock() + adapter._room_map_summary = "" + + # Importiere und binde den Handler + from archivar.inline_commands import InlineCommandRegistry + registry = InlineCommandRegistry() + + async def cmd_busy(room_id, args): + sub = args.strip().lower() if args else "status" + if sub == "status": + return "Busy-Status" + return "ok" + + registry.register("busy", cmd_busy, "Busy-Status", category="Standard") + + handler = registry.get_handler("busy") + assert handler is not None + result = await handler("room1", "") + assert "Busy-Status" in result + + @pytest.mark.asyncio + async def test_cmd_busy_queue(self): + """::busy queue parkt Nachricht.""" + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + + async def cmd_busy(room_id, args): + sub = args.strip().lower() if args else "status" + if sub.startswith("queue "): + return f"Geparkt: {sub[6:]}" + return "ok" + + registry.register("busy", cmd_busy, "Busy-Status", category="Standard") + + handler = registry.get_handler("busy") + assert handler is not None + result = await handler("room1", "queue Testnachricht") + assert "Geparkt" in result + # Der Mock lowercased den Text, also prüfe lowercase + assert "testnachricht" in result.lower() + + @pytest.mark.asyncio + async def test_cmd_allowalways_no_args(self): + """::allowalways ohne Args zeigt Liste.""" + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + + async def cmd_allowalways(room_id, args): + if not args.strip(): + return "Allow-Always-Liste" + return f"Skill {args.strip()} hinzugefügt" + + registry.register("allowalways", cmd_allowalways, "Allow-Always", category="Standard") + + handler = registry.get_handler("allowalways") + assert handler is not None + result = await handler("room1", "") + assert "Allow-Always" in result + + @pytest.mark.asyncio + async def test_cmd_allowalways_with_skill(self): + """::allowalways fügt Skill hinzu.""" + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + + async def cmd_allowalways(room_id, args): + if not args.strip(): + return "Allow-Always-Liste" + return f"Skill {args.strip()} hinzugefügt" + + registry.register("allowalways", cmd_allowalways, "Allow-Always", category="Standard") + + handler = registry.get_handler("allowalways") + assert handler is not None + result = await handler("room1", "my-skill") + assert "my-skill" in result + assert "hinzugefügt" in result + + @pytest.mark.asyncio + async def test_cmd_multiroom_status(self): + """::multiroom status zeigt Status.""" + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + + async def cmd_multiroom(room_id, args): + sub = args.strip().lower() if args else "status" + if sub == "status": + return "Multi-Room-Agent: Aktiviert" + return "ok" + + registry.register("multiroom", cmd_multiroom, "Multi-Room", category="Plugin") + + handler = registry.get_handler("multiroom") + assert handler is not None + result = await handler("room1", "status") + assert "Multi-Room-Agent" in result + + @pytest.mark.asyncio + async def test_cmd_multiroom_unknown_option(self): + """::multiroom mit unbekannter Option zeigt Fehler.""" + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + + async def cmd_multiroom(room_id, args): + sub = args.strip().lower() if args else "status" + if sub in ("on", "off", "status"): + return "ok" + return f"Unbekannte Option: {sub}" + + registry.register("multiroom", cmd_multiroom, "Multi-Room", category="Plugin") + + handler = registry.get_handler("multiroom") + assert handler is not None + result = await handler("room1", "toggle") + assert "Unbekannte" in result + + @pytest.mark.asyncio + async def test_cmd_curate_status(self): + """::curate status zeigt Kuratierungs-Status.""" + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + + async def cmd_curate(room_id, args): + sub = args.strip().lower() if args else "status" + if sub == "status": + return "Keyword-Kuratierung\nRäume: 3\nKeywords gesamt: 42" + return "ok" + + registry.register("curate", cmd_curate, "Kuratieren", category="Plugin") + + handler = registry.get_handler("curate") + assert handler is not None + result = await handler("room1", "status") + assert "Keyword-Kuratierung" in result + assert "Räume:" in result + + @pytest.mark.asyncio + async def test_cmd_curate_run(self): + """::curate run führt Kuratierung durch.""" + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + + async def cmd_curate(room_id, args): + sub = args.strip().lower() if args else "status" + if sub == "run": + return "Keyword-Kuratierung abgeschlossen\nAlle Keywords sind in Ordnung" + return "ok" + + registry.register("curate", cmd_curate, "Kuratieren", category="Plugin") + + handler = registry.get_handler("curate") + assert handler is not None + result = await handler("room1", "run") + assert "abgeschlossen" in result + + @pytest.mark.asyncio + async def test_cmd_commands_shows_help(self): + """::commands zeigt Hilfeseite.""" + from archivar.inline_commands import InlineCommandRegistry, build_help_text + + registry = InlineCommandRegistry() + async def dummy(room_id, args): + return "ok" + + registry.register("commands", dummy, "Listet Befehle", category="Info") + registry.register("hilfe", dummy, "Hilfe", category="Hilfe") + + text = build_help_text(registry) + assert "Rocket.Chat Plugin" in text + assert "::commands" in text + + @pytest.mark.asyncio + async def test_cmd_restart_returns_info(self): + """::restart gibt Info-Text zurück.""" + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + + async def cmd_restart(room_id, args): + return "Gateway-Neustart eingeleitet" + + registry.register("restart", cmd_restart, "Neustart", category="Gateway") + + handler = registry.get_handler("restart") + assert handler is not None + result = await handler("room1", "") + assert "Neustart" in result + + @pytest.mark.asyncio + async def test_cmd_update_returns_info(self): + """::update gibt Update-Info zurück.""" + from archivar.inline_commands import InlineCommandRegistry + + registry = InlineCommandRegistry() + + async def cmd_update(room_id, args): + return "hermes update" + + registry.register("update", cmd_update, "Update", category="Gateway") + + handler = registry.get_handler("update") + assert handler is not None + result = await handler("room1", "") + assert "hermes update" in result