Compare commits
32 Commits
57bebeb029
..
v8.6.1
| Author | SHA1 | Date | |
|---|---|---|---|
| c0ae37f79a | |||
| c942968328 | |||
| b6a9c9d8c3 | |||
| 42cb259bce | |||
| 9098a760dc | |||
| d964d7d5b5 | |||
| 573335cc8d | |||
| 342a1cddbb | |||
| c0c505e73d | |||
| 48471a8024 | |||
| 6825ba9149 | |||
| 6b16381818 | |||
| 7657cd3665 | |||
| 2019630144 | |||
| 131b11d07d | |||
| e72a5adb57 | |||
| a07ca22ca8 | |||
| 9f33fd3ee8 | |||
| c748c71ea9 | |||
| 37d6c10e45 | |||
| ce4789fe30 | |||
| f9e4760f58 | |||
| 42df3edb8b | |||
| 1b6bf3bf28 | |||
| 3d842b745d | |||
| 921d53be0a | |||
| 42e714827f | |||
| 1dc9e7a95f | |||
| afa462c468 | |||
| 07e72fa95c | |||
| 717d099a7a | |||
| fb3b7cfc56 |
@@ -0,0 +1,681 @@
|
||||
RAINER · ARCHITEKTUR-ENTWURF
|
||||
Onboarding Review-Flow — Strukturierter Aenderungs-Dialog
|
||||
Plugin: Hermes Rocket.Chat · HEAD: 9007bd6
|
||||
Reviewer: Rainer (Architekt) · Sprache: Deutsch · 2026-07-20
|
||||
|
||||
========================================================================
|
||||
0. ZUSAMMENFASSUNG
|
||||
========================================================================
|
||||
|
||||
VERDICT: TEILWEISE BEREITS UMGESETZT — KRITISCHE LÜCKE IN SCHRITT 1
|
||||
|
||||
Der Review-Flow existiert seit Commit 9007bd6 (2026-07-19) bereits als
|
||||
3+1-Schritt-Architektur (review_room → review_butler → review_fakt →
|
||||
ACTIVE). Schritte 2-4 liefern strukturierte Aenderungs-Buttons mit
|
||||
echten Werten aus room-map.json. SCHRITT 1 (review_room) hat jedoch
|
||||
einen Architektur-Bruch: "Anpassen" leitet auf den externen ::curate-
|
||||
Befehl um und PAUSIERT das Onboarding. Genau dort passiert Andreas'
|
||||
Bug — der LLM hat danach keinen gefuehrten Flow und raet herum.
|
||||
|
||||
EMPFEHLUNG: Schritt-1-Aendern-Branch durch einen In-Flow-
|
||||
Aenderungs-Dialog ersetzen, der die gleichen strukturierten Buttons
|
||||
nutzt wie Schritte 2-4. Kein Bruch, keine Pause, kein ::curate-
|
||||
Sprung. Geschaetzter Aufwand: 6-10 Stunden fuer Miguel (F8 R8+).
|
||||
|
||||
========================================================================
|
||||
1. IST-ANALYSE — Was der Code heute tut
|
||||
========================================================================
|
||||
|
||||
1.1 Schritt-1-Handler (adapter.py Z.4241-4318, Phase review_room)
|
||||
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ Buttons: ✏️ Anpassen ⏭️ Überspringen │
|
||||
│ Prefix: REVIEW_ROOM │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
|
||||
"Anpassen"-Branch (Z.4288-4312) verhaelt sich aktuell so:
|
||||
a) Postet eine LISTE der Raeume (nur Name + Theme, gekuerzt)
|
||||
b) Verweist auf ::curate als externen Befehl
|
||||
c) Setzt _onboarding_state = {} (Loeschung)
|
||||
d) Setzt onboarding_active = False
|
||||
e) Ruft _onboarding_sm.pause() auf
|
||||
f) User landet OHNE weitere Strukturhilfe im Operator-DM
|
||||
|
||||
Genau das ist die Luecke. Der LLM hat ab dort keine Buttons mehr
|
||||
und raet. Andreas' "Passwort setzen? 2FA? Zugriffsbeschraenkung?"
|
||||
ist die direkte Folge.
|
||||
|
||||
1.2 Schritte 2-4 (referenzielle Konsistenz, NICHT kaputt)
|
||||
|
||||
- Schritt 2 Butler-Mode (Z.4321-4412): "Ändern" zeigt 3 struktur-
|
||||
ierte Optionen (🤖 Kognitiv / 📋 Klassisch / 🔇 Aus) mit klaren
|
||||
Labels. "Beibehalten" advance_intent().
|
||||
- Schritt 3 FAKT-Speicherort (Z.4414-...): "Ändern" leitet auf
|
||||
existierende 4-Optionen-Logik (Standard/Neu/Bestehend/Keine).
|
||||
- Schritt 4 Abschluss: build_help_text() + ACTIVE.
|
||||
|
||||
Diese Phasen sind das Vorbild fuer Schritt 1.
|
||||
|
||||
1.3 Datenquelle room-map.json (v3)
|
||||
|
||||
Pro Raum vorhanden: name, theme, description,
|
||||
keywords_100[], keywords_context[],
|
||||
catch_all
|
||||
Top-Level vorhanden: version, rooms{}, excluded_rooms[],
|
||||
fact_store_path
|
||||
Top-Level via Defaults: butler_mode (Default 'cognitive'),
|
||||
fact_store_strategy (Default 'manual')
|
||||
|
||||
WICHTIG: butler_mode und fact_store_strategy werden in
|
||||
room-map.json v3 NICHT explizit gespeichert sondern nur ueber
|
||||
Defaults in RoomMap-Konstruktor (room_map.py Z.811-822) gefuellt.
|
||||
Im Review-Display MUSS das Default-Verhalten transparent gemacht
|
||||
werden ("aktuell: cognitive (Default)"), sonst sieht der User
|
||||
einen leeren Wert.
|
||||
|
||||
1.4 Schreib-API in room_map.py (bereits vorhanden)
|
||||
|
||||
- set_butler_mode(mode) Z.182
|
||||
- set_fact_store_strategy(strategy) Z.199
|
||||
- add_or_update_room(...) Z.439
|
||||
- add_keyword_context(room_id, keyword) Z.641
|
||||
- set_keyword_last_matched(...) Z.708
|
||||
|
||||
Was FEHLT (fuer Schritt-1-Inline-Aenderung):
|
||||
- set_theme(room_id, theme) — nicht vorhanden
|
||||
- remove_keyword_100(room_id, keyword) — nicht vorhanden
|
||||
- add_keyword_100(room_id, keyword) — nicht vorhanden
|
||||
- remove_room(room_id) — nicht vorhanden
|
||||
- save_after_mutation() — nicht zentralisiert
|
||||
|
||||
Das ist NICHT Miguel's Schuld — die existierende Schreib-API war
|
||||
auf den initialen Onboarding-Flow ausgerichtet, nicht auf
|
||||
inkrementelle Bearbeitung. Diese Luecke muss im selben Schritt
|
||||
geschlossen werden.
|
||||
|
||||
1.5 State-Machine (onboarding_state.py)
|
||||
|
||||
Die SM kennt aktuell nur die 4 Hauptphasen + PAUSED/ERROR. Sie
|
||||
hat KEIN Konzept fuer Sub-Phasen wie review_room_keywords_edit.
|
||||
Der bisherige Phase-String ("review_room") lebt ausschliesslich
|
||||
in self._onboarding_state (Dict, nicht in der SM). Das ist OK —
|
||||
wir bleiben bei der bisherigen Dikt-Struktur und erweitern nur
|
||||
um optionale Sub-Felder, um die SM nicht zu ueberlasten.
|
||||
|
||||
========================================================================
|
||||
2. BEFUND — Architektur-Probleme
|
||||
========================================================================
|
||||
|
||||
B1 KONTEXTVERLUST BEI SCHRITT-1-ANPASSEN [KRITISCH, P0]
|
||||
Aktuell: User klickt "Anpassen" → verliert Onboarding-Kontext
|
||||
(state={}, pause()). LLM muss ohne Strukturhilfe raten.
|
||||
Folgen: Falsche Optionen (Passwort, 2FA), zerstoererisches
|
||||
Herumexperimentieren, Frust-Abbruch.
|
||||
Quelle: Andreas' Session-Log, Commit 9007bd6 hat das nur halb
|
||||
geloest (3 von 4 Schritten mit Buttons).
|
||||
|
||||
B2 LLM-FREITEXT IN REVIEW-PHASE [HOCH, P1]
|
||||
Der else-Fallback in jedem Phase-Handler (z.B. Z.4313-4317)
|
||||
akzeptiert beliebigen Text und fordert nur "Anpassen oder
|
||||
Ueberspringen" an. Ein LLM, der nicht versteht was Onboarding
|
||||
ist, schickt Text der zwar "Anpassen" enthaelt aber semantisch
|
||||
etwas anderes meint. Im aktuellen Schritt-1-Branch wird dieser
|
||||
Text dann an die LLM-Raterunde weitergegeben — exakt Andreas'
|
||||
Szenario.
|
||||
Mitigation: In allen Review-Phasen explizit nur Button-Inputs
|
||||
akzeptieren (REVIEW_*-Prefix), Freitext ignorieren mit klarer
|
||||
Rueckfrage. Schon jetzt ueberwiegend vorhanden — aber die
|
||||
else-Branchen duerfen NICHT in den LLM-Dispatch fallen.
|
||||
|
||||
B3 SCHEMA-INKONSISTENZ ROOM-MAP [MITTEL, P2]
|
||||
room-map.json v3 enthaelt butler_mode/fact_store_strategy NICHT
|
||||
als JSON-Felder, sondern nur als In-Memory-Defaults. Im Review-
|
||||
Display kann so der Eindruck entstehen, der Wert sei "leer"
|
||||
oder "nicht gesetzt", obwohl er in Wahrheit der Default ist.
|
||||
Fix: Beim Rendern Default explizit nennen ("aktuell: cognitive
|
||||
(Default — wird in room-map.json nicht persistiert)").
|
||||
|
||||
B4 SCHREIB-API-LUECKE [MITTEL, P2]
|
||||
set_theme/remove_keyword_100/add_keyword_100/remove_room fehlen
|
||||
in room_map.py. Ohne diese Methoden muss Miguel entweder direkt
|
||||
auf die internen Felder zugreifen (Persistenz-Luecke) oder den
|
||||
Schritt-1-Aenderungs-Dialog nicht voll implementieren.
|
||||
Fix: Vier kleine Public-API-Methoden hinzufuegen, jeweils mit
|
||||
Validation (keyword lowercase, theme non-empty, room_id existent)
|
||||
+ automatischem save().
|
||||
|
||||
B5 FAISS-INDEX-REBUILD [NIEDRIG, P3]
|
||||
Keywords/Theme-Aenderung macht den FAISS-Index stale. Catch-All-
|
||||
Wechsel hat das schon (Z.5310-5317). Keyword-Aenderung braucht
|
||||
denselben Rebuild. Catch-All-Aenderung im Review-Flow braucht
|
||||
es ebenfalls.
|
||||
Fix: Zentraler _persist_room_map() Helper der Index-Rebuild
|
||||
konsistent macht.
|
||||
|
||||
========================================================================
|
||||
3. SOLL-ARCHITEKTUR — Strukturierter Review-Flow
|
||||
========================================================================
|
||||
|
||||
DESIGN-PRINZIP: Jeder Schritt hat genau 4 Buttons.
|
||||
"Anpassen" oeffnet UNTER-Flow mit weiteren Buttons.
|
||||
Kein Freitext, kein LLM-Raten, keine Pause.
|
||||
|
||||
3.1 Phase State-Modell (Erweiterung)
|
||||
|
||||
self._onboarding_state = {
|
||||
"phase": "review_room" | "review_butler" | "review_fakt" | "active",
|
||||
"operator_room_id": str,
|
||||
# NEU ab F8 R8:
|
||||
"sub_phase": Optional[str], # None in Top-Level-Schritten
|
||||
"target_room_id": Optional[str], # nur in Sub-Flows gesetzt
|
||||
"edit_kind": Optional[str], # keywords_100|keywords_context|theme
|
||||
"pending_text_input": bool, # True wenn Textfeld aktiv
|
||||
}
|
||||
|
||||
Die State-Machine (onboarding_state.py) wird NICHT angefasst —
|
||||
Sub-Phasen sind Dispatch-Detail des Adapters, nicht des
|
||||
Persistenz-Layers. Persistenz bleibt auf phase beschraenkt.
|
||||
|
||||
3.2 Schritt 1: Room Map Review (review_room)
|
||||
|
||||
Top-Level-Anzeige (immer beim Start, mit aktuellen Werten):
|
||||
|
||||
📋 Schritt 1 von 4: Room Map Review
|
||||
Aktuell 4 Räume konfiguriert:
|
||||
|
||||
1. #BAT-Team
|
||||
Thema: Bot Agent Team, Trade, BAT...
|
||||
Keywords 100%: bat, trading, krypto, wyckoff, ... (13)
|
||||
Keywords Kontext: bot (1)
|
||||
Catch-All: nein
|
||||
|
||||
2. #Rocketchat-Plugin
|
||||
Thema: Rocketchat, Hermes Gateway, RC...
|
||||
Keywords 100%: rocketchat, rc, websocket, ... (12)
|
||||
Keywords Kontext: plugin, deployment, button, ... (6)
|
||||
Catch-All: nein
|
||||
|
||||
3. #LAN-Dokumentation
|
||||
...
|
||||
|
||||
4. DM mit Andreas (Catch-All)
|
||||
...
|
||||
|
||||
👉 Klicke auf einen Button:
|
||||
|
||||
[Raum auswählen ▼] [Neuen Raum hinzufügen] [Überspringen]
|
||||
|
||||
Detail-UX:
|
||||
- "Raum auswaehlen ▼" oeffnet ein DROPDOWN mit allen 4 Raeumen
|
||||
(Rocket.Chat unterstuetzt Button-Groups mit bis zu N Raeumen).
|
||||
- "Neuen Raum hinzufuegen" oeffnet Sub-Phase add_room mit
|
||||
Feldern: Raum-ID (vorausgefuellt aus Operator-Sicht),
|
||||
Theme (Textfeld), Keywords (Textfeld).
|
||||
- "Ueberspringen" advance_room() → Schritt 2.
|
||||
|
||||
Sub-Phase review_room_edit (nach "Raum auswaehlen"):
|
||||
|
||||
✏️ Bearbeite #LAN-Dokumentation
|
||||
|
||||
Aktuelles Thema: "LAN Dokumentation, Homelab, RZBLN..."
|
||||
Aktuelle Keywords 100%: lan, dokumentation, homelab, ... (18)
|
||||
Aktuelle Keywords Kontext: reverse-proxy, traefik, ... (10)
|
||||
Catch-All: nein
|
||||
|
||||
[Keywords 100% bearbeiten] [Keywords Kontext bearbeiten]
|
||||
[Thema ändern] [Catch-All umschalten]
|
||||
[Raum aus Map entfernen] [↩️ Zurück]
|
||||
|
||||
WICHTIG: KEIN Freitext ausserhalb explizit ausgewaehlter
|
||||
Sub-Phasen. Jeder Sub-Phase-Button oeffnet einen NEUEN strukturierten
|
||||
Dialog mit Inputs.
|
||||
|
||||
3.3 Sub-Phase review_room_keywords_edit
|
||||
|
||||
📝 Keywords 100% für #LAN-Dokumentation
|
||||
|
||||
Aktuell (18):
|
||||
lan, dokumentation, homelab, netzwerk, netzwerkdokumentation,
|
||||
router, switch, subnetz, proxmox, heimnetz, ip-adresse, rzbln,
|
||||
firewall, ddp-client, monitoring, iptables, dhcp, dns
|
||||
|
||||
Hinzufügen: [Textfeld: neues keyword]
|
||||
[➕ Hinzufügen]
|
||||
|
||||
Entfernen: [Pro Keyword ein Button: ✕ lan]
|
||||
[Pro Keyword ein Button: ✕ dokumentation]
|
||||
...
|
||||
|
||||
[↩️ Zurück zur Raum-Bearbeitung]
|
||||
|
||||
Validierung: lowercase, keine Leerzeichen, keine Duplikate,
|
||||
Laenge 2-30 Zeichen. Fehler werden als rote Inline-Antwort
|
||||
gepostet, KEINE automatische Korrektur.
|
||||
|
||||
3.4 Sub-Phase review_room_theme_edit
|
||||
|
||||
📝 Thema für #LAN-Dokumentation
|
||||
|
||||
Aktuell: "LAN Dokumentation, Homelab, RZBLN, Doku —
|
||||
Dokumentation des Heimnetzwerks, Proxmox..."
|
||||
|
||||
Neues Thema: [Textfeld]
|
||||
[💾 Speichern] [↩️ Abbrechen]
|
||||
|
||||
HIER ist Freitext legitim (Theme ist per Definition Freitext).
|
||||
Aber: Es ist ein KLAR abgegrenzter, vom User explizit
|
||||
ausgewaehlter Text-Input, nicht ein offenes "Was moechtest du
|
||||
aendern?"-Raterunde.
|
||||
|
||||
3.5 Sub-Phase review_room_catch_all_toggle
|
||||
|
||||
🔀 Catch-All für #LAN-Dokumentation
|
||||
|
||||
Aktuell: nein. Aktueller Catch-All-Raum: DM mit Andreas.
|
||||
|
||||
[✅ Als neuen Catch-All setzen] [↩️ Abbrechen]
|
||||
|
||||
Bestätigungs-Pattern (analog zu existierender _set_catch_all):
|
||||
- Setzt diesen Raum auf catch_all=true
|
||||
- Setzt ALLE anderen Raeume auf catch_all=false
|
||||
- Persistiert + FAISS-Rebuild
|
||||
- Informiert User ueber den vorherigen Catch-All-Raum
|
||||
|
||||
3.6 Sub-Phase review_room_remove
|
||||
|
||||
⚠️ #LAN-Dokumentation aus Map entfernen?
|
||||
|
||||
Der Raum bleibt in Rocket.Chat bestehen, wird aber vom
|
||||
Hermes-Routing ausgeschlossen. Alle FAKTs des Raums
|
||||
bleiben erhalten.
|
||||
|
||||
[🗑️ Ja, entfernen] [↩️ Abbrechen]
|
||||
|
||||
Implementation: Nutzt existierende excluded_rooms[]-Logik in
|
||||
room-map.json. NICHT loeschen — nur ausschliessen.
|
||||
|
||||
3.7 Schritt 2+3 bleiben strukturell UNVERAENDERT
|
||||
|
||||
Die Schritte review_butler (Z.4321-4412) und review_fakt
|
||||
(Z.4414+) sind bereits korrekt. Einzige Aenderung: Fallback-
|
||||
Pfade (else-Branchen) duerfen NICHT in den LLM-Dispatch fallen.
|
||||
Empfehlung: Helper-Funktion _reject_free_text(operator_room_id)
|
||||
der konsistent "Bitte Button waehlen" postet — DRY statt 3x
|
||||
copy-paste.
|
||||
|
||||
3.8 Schritt 4 Abschluss: KEINE Aenderung.
|
||||
|
||||
build_help_text() + ACTIVE. Existiert.
|
||||
|
||||
========================================================================
|
||||
4. BUTTON-LAYOUT PRO SCHRITT (UEBERSICHT)
|
||||
========================================================================
|
||||
|
||||
Schritt 1 Top-Level: [Raum wählen ▼] [Neuer Raum] [Überspringen]
|
||||
Schritt 1 Raum-Detail: [Kw100] [KwKontext] [Thema] [CatchAll] [Löschen] [↩️]
|
||||
Schritt 1 Kw-Add: [Textfeld] [➕ Hinzufügen] [↩️]
|
||||
Schritt 1 Kw-Remove: [✕ kw1] [✕ kw2] ... [↩️]
|
||||
Schritt 1 Theme: [Textfeld] [💾] [↩️]
|
||||
Schritt 1 CatchAll: [✅ Setzen] [↩️]
|
||||
Schritt 1 Raum entfernen: [🗑️ Ja] [↩️]
|
||||
Schritt 2 Butler: [🤖] [📋] [🔇] (oder bei Beibehalten: [⏭️])
|
||||
Schritt 3 FAKT: [1️⃣ Standard] [2️⃣ Neu] [3️⃣ Bestehend] [4️⃣ Keine] [⏭️]
|
||||
Schritt 4 Abschluss: (nur Anzeige, keine Buttons nötig)
|
||||
|
||||
BUTTON-PREFIXES (fuer eindeutiges Routing):
|
||||
REVIEW_ROOM_EDIT::<room_id>::<kind>
|
||||
REVIEW_ROOM_KW_ADD::<room_id>::<list>
|
||||
REVIEW_ROOM_KW_REMOVE::<room_id>::<keyword>
|
||||
REVIEW_ROOM_THEME_SAVE::<room_id>
|
||||
REVIEW_ROOM_CATCHALL_SET::<room_id>
|
||||
REVIEW_ROOM_REMOVE_CONFIRM::<room_id>
|
||||
REVIEW_ROOM_BACK (zurueck zur Raum-Liste)
|
||||
REVIEW_ROOM_ADD_NEW (in add_room Sub-Phase)
|
||||
BUTLER::<mode> (existiert bereits)
|
||||
FAKT::<strategy> (existiert bereits)
|
||||
|
||||
========================================================================
|
||||
5. DATENFLUSS
|
||||
========================================================================
|
||||
|
||||
5.1 LESE-PFAD (Anzeige)
|
||||
|
||||
room-map.json
|
||||
↓ (load)
|
||||
archivar._room_map (RoomMap-Instanz)
|
||||
↓ (rooms.items(), butler_mode, fact_store_*, fact_store_path)
|
||||
adapter._render_review_step_N(operator_room_id)
|
||||
↓ (formatiert mit Markdown + Buttons)
|
||||
_post_message_with_retry
|
||||
↓
|
||||
Rocket.Chat DM
|
||||
|
||||
Single source of truth: archivar._room_map. KEIN Caching, KEIN
|
||||
Re-Laden aus anderer Quelle. Nach Aenderungen wird reload()
|
||||
aufgerufen um In-Memory-State und JSON konsistent zu halten.
|
||||
|
||||
5.2 SCHREIB-PFAD (Aenderung)
|
||||
|
||||
User klickt Button
|
||||
↓ (Rocket.Chat Action-Event)
|
||||
adapter._on_message() empfaengt REVIEW_ROOM_*::*
|
||||
↓ (parst prefix, kind, room_id)
|
||||
_handle_review_room_edit(room_id, kind, payload)
|
||||
↓
|
||||
room_map.set_theme(...) ┐
|
||||
room_map.add_keyword_100(...) ├─ validiert + mutiert
|
||||
room_map.remove_keyword_100(...)┤
|
||||
room_map.set_catch_all(...) ┘
|
||||
↓
|
||||
RoomMap.save(room_map, ROOM_MAP_PATH) ← IMMER
|
||||
↓
|
||||
archivar._room_map.reload() ← IMMER
|
||||
↓
|
||||
archivar._room_index.build_index() ← bei keyword/catch_all
|
||||
archivar._room_index.save()
|
||||
↓
|
||||
_post_message_with_retry(bestaetigung)
|
||||
↓
|
||||
State zurueck auf Sub-Phase review_room_edit fuer denselben Raum
|
||||
|
||||
5.3 NEUE SCHREIB-METHODEN in room_map.py (B4)
|
||||
|
||||
Verbaler Pseudocode (NICHT als Code, nur als Spezifikation):
|
||||
|
||||
- set_theme(room_id, theme: str) -> None
|
||||
Prueft: room_id in self.rooms, theme.strip() != "".
|
||||
Setzt entry.theme.
|
||||
Ruft self.save() auf.
|
||||
|
||||
- add_keyword_100(room_id, keyword: str) -> bool
|
||||
Normalisiert: keyword.strip().lower().
|
||||
Prueft: Laenge 2-30, keine Leerzeichen, kein Duplikat.
|
||||
Returnt False bei Validierungsfehler.
|
||||
Erweitert entry.keywords_100, ruft self.save().
|
||||
|
||||
- remove_keyword_100(room_id, keyword: str) -> bool
|
||||
Entfernt aus entry.keywords_100.
|
||||
Returnt False wenn nicht vorhanden.
|
||||
Ruft self.save().
|
||||
|
||||
- remove_room(room_id: str) -> None
|
||||
Implementiert als add zu self._excluded_room_ids.
|
||||
NICHT entry loeschen — Ausschluss-Pattern ist rueckgaengig
|
||||
machbar.
|
||||
Ruft self.save().
|
||||
|
||||
Jede Methode: validiert, mutiert, persistiert. Keine Caller-
|
||||
Logik dupliziert.
|
||||
|
||||
========================================================================
|
||||
6. NICHT-REVIEW-FAEHIG (Hard Exclusion)
|
||||
========================================================================
|
||||
|
||||
Diese gehoeren EXPLIZIT NICHT in den Review-Flow. Bei jeder Phase
|
||||
und jedem Sub-Button-Menu MUSS die Plugin-Logik verhindern dass
|
||||
diese Themen vom LLM als Optionen angeboten werden:
|
||||
|
||||
X Rocket.Chat Account: Passwort, 2FA, Login, Sessions
|
||||
X Rocket.Chat Channel: create/delete/archive in Rocket.Chat
|
||||
X Rocket.Chat Permissions: roles, Beschraenkungen
|
||||
X Plugin-Interner Code: aenderungen an adapter.py etc.
|
||||
X Modell-Wechsel: provider/model in config.yaml
|
||||
X Gateway-Neustart: ::restart, ::update, ::busy
|
||||
X Memory/Skill-Management: !memory, !skill
|
||||
X Inline-Command-Erstellung: neue ::-Befehle
|
||||
|
||||
Technische Umsetzung: In den Review-Phase-Handlern wird der
|
||||
else-Fallback (Freitext-Annahme) ENTFERNT. Stattdessen:
|
||||
|
||||
_reject_free_text(operator_room_id) -> postet
|
||||
"Bitte einen der angezeigten Buttons verwenden.
|
||||
Freitext kann in diesem Schritt nicht verarbeitet werden."
|
||||
|
||||
Ausnahme: review_room_theme_edit (Textfeld) und review_room_add_new
|
||||
(Textfeld fuer Theme+Keywords) — dort ist Freitext explizit
|
||||
gefordert und der State-Pending-Flag pending_text_input=True macht
|
||||
es moeglich.
|
||||
|
||||
========================================================================
|
||||
7. IMPLEMENTIERUNGS-SCHAETZUNG FUER MIGUEL
|
||||
========================================================================
|
||||
|
||||
Phase 1 — room_map.py Schreib-API (B4)
|
||||
- set_theme, add_keyword_100, remove_keyword_100, remove_room
|
||||
- 4 kleine Methoden, ~80 Zeilen, inkl. Validation + save()
|
||||
- Tests: test_room_map_write_api.py, ~12 Assertions
|
||||
- Aufwand: 1.5 Stunden
|
||||
|
||||
Phase 2 — Sub-Phase-State-Modell (3.1)
|
||||
- sub_phase, target_room_id, edit_kind, pending_text_input
|
||||
- Konstanten fuer Button-Prefixes (in adapter.py oder neue
|
||||
archivar/onboarding_review.py)
|
||||
- Aufwand: 0.5 Stunden
|
||||
|
||||
Phase 3 — Schritt 1 Top-Level mit Raum-Dropdown (3.2)
|
||||
- _render_review_room_step(operator_room_id) ersetzt den
|
||||
aktuellen Mini-Review-Text
|
||||
- Pro Raum: formatierte Markdown-Zusammenfassung + Button
|
||||
- "Neuer Raum" → add_room Sub-Phase
|
||||
- Aufwand: 3 Stunden
|
||||
|
||||
Phase 4 — Sub-Phase-Handler (3.3-3.6)
|
||||
- review_room_edit: 4 Buttons (Kw/Kontext/Theme/CatchAll/Remove)
|
||||
- review_room_keywords_edit: Add + Remove Buttons
|
||||
- review_room_theme_edit: Textfeld + Save
|
||||
- review_room_catch_all_toggle: Bestaetigung
|
||||
- review_room_remove: Bestaetigung
|
||||
- review_room_add_new: Textfelder fuer Theme + Keywords
|
||||
- 6 Handler, ~300 Zeilen, inkl. Validierung
|
||||
- Aufwand: 4 Stunden
|
||||
|
||||
Phase 5 — Freitext-Reject + Persistenz-Helper (B2, B5)
|
||||
- _reject_free_text() Helper
|
||||
- _persist_room_map_changes() zentralisiert save+reload+index
|
||||
- In allen 3 Review-Phasen else-Branchen ersetzen
|
||||
- Aufwand: 1 Stunde
|
||||
|
||||
Phase 6 — Tests
|
||||
- test_review_room_subphases.py: 8 Szenarien
|
||||
- test_review_room_keywords_edit.py: 5 Szenarien
|
||||
- test_review_room_remove.py: 3 Szenarien
|
||||
- test_review_room_add_new.py: 4 Szenarien
|
||||
- test_room_map_write_api.py (Phase 1)
|
||||
- Bestehende Tests: 75+ muessen weiter gruen bleiben
|
||||
- Aufwand: 3 Stunden
|
||||
|
||||
GESAMT (F8 R8+): ~13 Stunden (1.5 Tage)
|
||||
Davon reiner Code: ~9 Stunden
|
||||
Davon Tests: ~3 Stunden
|
||||
Davon Review-Anpassung: ~1 Stunde
|
||||
|
||||
ABHAENGIGKEITEN: keine externen. Alle benoetigten Module existieren.
|
||||
|
||||
REIHENFOLGE: Phase 1 → 2 → 3 → 4 → 5 → 6 (Tests parallel zu 4-5).
|
||||
|
||||
RISIKO: Niedrig. Aenderungen sind additiv (neue Methoden, neue
|
||||
Sub-Phasen). Bestehende Schritte 2-4 unveraendert. Catch-All-
|
||||
Toggle kann bestehende _set_catch_all() wiederverwenden.
|
||||
|
||||
ROLLBACK: Git revert auf 9007bd6 (gestern). Kein Migrations-
|
||||
Script noetig — room-map.json v3 ist kompatibel.
|
||||
|
||||
========================================================================
|
||||
8. TEST-SZENARIEN
|
||||
========================================================================
|
||||
|
||||
T1 Happy Path — Alle Schritte ueberspringen
|
||||
::onboarding start → Schritt 1 → Ueberspringen → Schritt 2 →
|
||||
Beibehalten → Schritt 3 → Beibehalten → ACTIVE + Hilfeseite.
|
||||
Erwartung: room-map.json unveraendert, onboarding.yaml = ACTIVE.
|
||||
|
||||
T2 Schritt 1: Keywords 100% ergaenzen (Andreas' Use Case)
|
||||
::onboarding start → Schritt 1 → "Raum waehlen" →
|
||||
#LAN-Dokumentation → "Keywords 100% bearbeiten" →
|
||||
[Textfeld: "rzbln-test"] → ➕ Hinzufuegen.
|
||||
Erwartung: room-map.json keywords_100 fuer LAN-Doku enthaelt
|
||||
"rzbln-test". State zurueck auf review_room_edit. FAISS-Index
|
||||
neu gebaut.
|
||||
|
||||
T3 Schritt 1: Theme aendern
|
||||
#LAN-Dokumentation → "Thema aendern" → [Textfeld: neues Thema] →
|
||||
💾 Speichern.
|
||||
Erwartung: room-map.json theme aktualisiert. State zurueck auf
|
||||
review_room_edit. KEIN FAISS-Rebuild noetig (Theme ist nicht im
|
||||
Vektor-Index).
|
||||
|
||||
T4 Schritt 1: Catch-All umschalten
|
||||
#Rocketchat-Plugin → "Catch-All umschalten" → ✅ Setzen.
|
||||
Erwartung: rooms[rc].catch_all=true, alle anderen false. DM mit
|
||||
Andreas catch_all=false. FAISS-Rebuild. State zurueck auf
|
||||
review_room_edit.
|
||||
|
||||
T5 Schritt 1: Raum entfernen
|
||||
#Protonbridge-Plugin → "Raum aus Map entfernen" → 🗑️ Ja.
|
||||
Erwartung: excluded_rooms enthaelt die ID. Raum bleibt in
|
||||
Rocket.Chat. Bei ::onboarding status nicht mehr aufgelistet.
|
||||
|
||||
T6 Schritt 1: Neuen Raum hinzufuegen
|
||||
::onboarding start → "Neuen Raum hinzufuegen" → [Textfeld: ID,
|
||||
Theme, Keywords] → 💾.
|
||||
Erwartung: Neuer Eintrag in rooms{}. Catch-All=false.
|
||||
Bestaetigungs-Post mit neuem Raum-Block.
|
||||
|
||||
T7 Freitext-Schutz
|
||||
Im review_room-State sendet User: "setze das Passwort auf 1234"
|
||||
(NICHT ueber Button).
|
||||
Erwartung: KEINE Aenderung. Antwort: "Bitte einen der
|
||||
angezeigten Buttons verwenden." KEIN LLM-Dispatch.
|
||||
|
||||
T8 Schritt 1: Validation-Fehler
|
||||
Keywords 100% → "X" (1 Zeichen) → ➕ Hinzufuegen.
|
||||
Erwartung: Fehler-Post "Keyword muss 2-30 Zeichen lang sein".
|
||||
KEIN save. KEIN state-change.
|
||||
|
||||
T9 Schritt 1: Doppel-Keyword
|
||||
Keywords 100% → "lan" (existiert bereits) → ➕ Hinzufuegen.
|
||||
Erwartung: Fehler-Post "Keyword existiert bereits". KEIN save.
|
||||
|
||||
T10 Schritt 1: Aberhundert Keywords
|
||||
Raum hat 18 Keywords, User fuegt 5 weitere hinzu. 23 ist OK
|
||||
(kein hartes Limit im Code). Wird im UI lediglich als lange
|
||||
Liste angezeigt. Erwartung: keine Performance-Probleme
|
||||
(Markdown-Liste < 30 Eintraege ist trivial).
|
||||
|
||||
T11 Persistenz-Round-Trip
|
||||
Aenderung an room-map.json → Plugin-Reload → ::onboarding
|
||||
start → Schritt 1 zeigt neuen Wert.
|
||||
Erwartung: Aenderung ist sichtbar.
|
||||
|
||||
T12 State-Machine-Konsistenz
|
||||
Mitten in Sub-Phase review_room_keywords_edit → ::onboarding
|
||||
abort. Erwartung: onboarding.yaml = NONE, KEIN Datenverlust.
|
||||
|
||||
T13 Catch-All-Konflikt
|
||||
Versuch zwei Raeume gleichzeitig als Catch-All zu setzen.
|
||||
Erwartung: nur der JETZT geklickte Raum ist Catch-All, der
|
||||
andere wird auf false gesetzt (idempotente Semantik).
|
||||
|
||||
T14 Schema-Version-Mismatch
|
||||
room-map.json v3 → Code v4 erwartet Felder.
|
||||
Erwartung: Klare Fehlermeldung, KEIN silent data loss.
|
||||
|
||||
T15 Re-Onboarding nach ACTIVE
|
||||
Onboarding ACTIVE → ::onboarding start (Re-Onboarding).
|
||||
Erwartung: Springt direkt in review_room (Skip-all-Logik
|
||||
funktioniert). State Machine: ACTIVE → AWAITING_ROOM.
|
||||
|
||||
========================================================================
|
||||
9. ARCHITEKTUR-EMPFEHLUNGEN (ZUSAETZLICH)
|
||||
========================================================================
|
||||
|
||||
R1 BUTTON-PREFIX-NAMESPACE
|
||||
Alle Review-Button-Prefixes unter einem Namensraum konsolidieren.
|
||||
Statt REVIEW_ROOM, REVIEW_BUTLER, REVIEW_FAKT (vermischt mit
|
||||
existierenden BUTLER/FAKT) → einheitlich REVIEW_ROOM_*,
|
||||
REVIEW_BUTLER_*, REVIEW_FAKT_*. Reduziert Routing-Konflikte.
|
||||
|
||||
R2 STATE-DIKT vs. STATE-MACHINE
|
||||
Die aktuelle Loesung (Dict in adapter._onboarding_state +
|
||||
SM nur fuer 4 Top-Level-Phasen) ist pragmatisch. Empfehlung:
|
||||
Sub-Phase-Logik NUR im Adapter, SM bleibt unveraendert.
|
||||
Sub-Phasen sind Dispatch-Detail, nicht Persistenz-relevanter
|
||||
State. Persistenz nur bei Top-Level-Phasen-Wechsel.
|
||||
|
||||
R3 REVIEW-AUDIT-LOG
|
||||
Jede Review-Aenderung in einem separaten Log
|
||||
(~/.hermes/data/onboarding-review.log) mit Timestamp + Aktion
|
||||
+ room_id + Diff. Erleichtert Post-Mortem bei
|
||||
"wer hat wann was geaendert".
|
||||
|
||||
R4 IDEMPOTENZ
|
||||
Alle Review-Button-Handler muessen idempotent sein. Klick auf
|
||||
"Beibehalten" bei bereits ACTIVE State darf KEINEN Re-Complete
|
||||
triggern. Schutz: state.phase-pruefung VOR Handler-Action.
|
||||
|
||||
R5 MAX KEYWORDS PRO RAUM
|
||||
Kein hartes Limit, aber UI-Hinweis ab >30 Keywords
|
||||
("Viele Keywords koennen Routing verlangsamen"). Kein Block,
|
||||
nur Warnung.
|
||||
|
||||
R6 THEMA-FELD-LAENGE
|
||||
Aktuell room-map.json v3 erlaubt beliebig lange Themes.
|
||||
Empfehlung: UI-Warnung ab >500 Zeichen, aber KEIN Block.
|
||||
|
||||
========================================================================
|
||||
10. OFFENE PUNKTE
|
||||
========================================================================
|
||||
|
||||
O1 Wo wird der Review-Text gerendert? Optionen:
|
||||
a) Inline in adapter.py (status quo, ~300 Zeilen mehr).
|
||||
b) Neue Datei plugin/archivar/onboarding_review.py als
|
||||
Renderer-Modul (~200 Zeilen + adapter-Aufrufe).
|
||||
Empfehlung: (b) — Separation of Concerns, testbar isoliert.
|
||||
|
||||
O2 "Neuen Raum hinzufuegen" — wie weiss der Adapter welche
|
||||
room_id gemeint ist? Optionen:
|
||||
a) User postet die ID manuell (Fehleranfaellig).
|
||||
b) Adapter listet verfuegbare Rocket.Chat Raeume die NICHT in
|
||||
room-map.json sind, User klickt. Sauber.
|
||||
Empfehlung: (b). Erfordert einen REST-Call rooms.list?count=100
|
||||
in Rocket.Chat. Kosten gering, nur bei Klick auf den Button.
|
||||
|
||||
O3 Catch-All-Toggle — gibt es UX-Konflikt mit Schritt 1 in der
|
||||
existierenden Onboarding-Reihenfolge? Nein — Catch-All wird
|
||||
im initialen Onboarding separat in einem eigenen Schritt
|
||||
abgefragt. Im Review-Flow ist die Toggle-Operation optional.
|
||||
|
||||
O4 Soll review_room_edit auch den RAUM-NAMEN editierbar machen?
|
||||
NEIN — Raum-Name kommt aus Rocket.Chat, nicht aus Plugin-
|
||||
Konfiguration. Wuerde nur Verwirrung stiften.
|
||||
|
||||
========================================================================
|
||||
11. FREIGABE-EMPFEHLUNG
|
||||
========================================================================
|
||||
|
||||
KONZEPT: APPROVED — der Entwurf loest Andreas' Bug strukturell.
|
||||
Erweiterung von F8 UX (Commit 9007bd6) um Sub-Phasen
|
||||
in Schritt 1, ohne Schritte 2-4 zu beruehren.
|
||||
|
||||
CODE: Noch nicht implementiert. Geplante Schritte 1-6 in
|
||||
Abschnitt 7 mit ~13h Aufwand fuer Miguel.
|
||||
|
||||
PRIO: P0 — Andreas' Abbruch-Szenario ist real, jeder weitere
|
||||
Re-Onboarding ohne Fix produziert denselben Bug.
|
||||
|
||||
ABHAENGIGKEITEN: F8 State Machine (commit e7b10cd) ✓
|
||||
F8 UX Review-Flow (commit 9007bd6) ✓
|
||||
butler_mode + fact_store_strategy (Fix C v7) ✓
|
||||
onboarding.py + onboarding_state.py ✓
|
||||
|
||||
ROLLBACK-STRATEGIE: Git revert auf 9007bd6. Kein Daten-Migration
|
||||
noetig. room-map.json v3 ist rueckwaertskompatibel.
|
||||
|
||||
VOR MIGUEL-START BITTE KLAEREN:
|
||||
- O1: Renderer in adapter.py oder onboarding_review.py?
|
||||
- O2: Wie wird die room_id fuer "Neuer Raum" ausgewaehlt?
|
||||
(REST-Liste oder manuelle Eingabe)
|
||||
|
||||
========================================================================
|
||||
RAINER · Architektur-Review · Ende
|
||||
========================================================================
|
||||
+30
@@ -115,3 +115,33 @@ export CONTEXT_LENGTH=131072
|
||||
- **Idempotenz**: `install.sh` kann mehrfach ausgeführt werden. Bestehende Dateien werden gesichert (`.bak.<timestamp>`), `room-map.json` mit Inhalt wird nicht überschrieben.
|
||||
- **Python 3.13**: pipx installiert hermes-agent zwingend mit Python 3.13 (`--python python3.13`). Ein abweichendes Python in der pipx-venv wird automatisch erkannt und korrigiert.
|
||||
- **OLLAMA_KEEP_ALIVE=-1**: Das lokale Ollama-Modell (qwen2.5:7b für Archivar) wird nie entladen und bleibt dauerhaft im RAM (~5GB). Der Multi-Room-Agent benötigt ein warmes Modell für ruckelfreies Routing zwischen Räumen. Wer RAM sparen will, setzt `OLLAMA_KEEP_ALIVE=30m` (oder einen anderen Wert) als env-Variable vor `install.sh`. Der Wert wird sowohl in `.env` als auch als systemd drop-in für den Ollama-Dienst gesetzt.
|
||||
|
||||
## Moderatorenrechte im Multi-Room-Modus
|
||||
|
||||
Wenn der Agent im Multi-Room-Modus läuft, verschiebt er Nachrichten zwischen Räumen. Damit das sauber funktioniert, braucht der Bot Moderatorenrechte in den beteiligten Räumen.
|
||||
|
||||
Ohne Moderatorenrechte kann der Agent die Originalnachricht nach dem Verschieben nicht löschen — sie bleibt dann im Ursprungsraum sichtbar. In Direktnachrichten (DM) kann der Agent Nachrichten grundsätzlich nicht löschen, da Bots in DMs keine Moderatorenrechte erhalten.
|
||||
|
||||
Empfehlung: Gib dem Bot Moderatorenrechte in allen Themenräumen.
|
||||
|
||||
## Keyword-Empfehlungen für Raum-Konfiguration
|
||||
|
||||
Die Keyword-basierte Raumzuordnung (`keywords_100` und `keywords_context` in der `room-map.json`) funktioniert am besten mit **eindeutigen, spezifischen** Keywords. Mehrdeutige Kurzformen führen zu falschen Routing-Vorschlägen.
|
||||
|
||||
### 'rc' ist mehrdeutig — nicht als Keyword verwenden
|
||||
|
||||
Das Keyword `rc` ist problematisch, weil es in verschiedenen Kontexten unterschiedliche Bedeutungen hat:
|
||||
|
||||
- **Rocket.Chat** (Plugin-Kontext) — `rc` als Abkürzung für Rocket.Chat
|
||||
- **Remote Controller** (Hobby-Kontext) — `rc` als Abkürzung für DJI-Drohnen-Fernsteuerung
|
||||
|
||||
Wenn `rc` als Keyword für den Rocket.Chat-Plugin-Raum gesetzt ist, werden Nachrichten über Drohnen-Fernsteuerungen fälschlicherweise in den Plugin-Raum geroutet.
|
||||
|
||||
**Empfehlung:** Statt `rc` spezifischere Keywords verwenden:
|
||||
|
||||
- `rocket.chat`, `rocketchat` (eindeutig)
|
||||
- `plugin`, `adapter` (Plugin-Kontext)
|
||||
- `websocket`, `ddp` (technische Protokolle)
|
||||
- `gateway`, `hermes` (Agent-Kontext)
|
||||
|
||||
**Onboarding-Hinweis:** Beim Einrichten neuer Räume im Onboarding darauf achten, dass Keywords eindeutig und nicht mit anderen Domänen überlappend sind. Kurze Abkürzungen (`rc`, `api`, `db`) sind fast immer mehrdeutig — lieber ausschreiben oder mit Kontext-Präfix versehen (`rc-chat`, `rc-plugin`).
|
||||
@@ -0,0 +1,282 @@
|
||||
# REVIEW P0/P1/UX — 16 Sammelpunkte
|
||||
|
||||
**Plugin:** Hermes_rocket.chat_Plugin
|
||||
**HEAD:** 1505737
|
||||
**Datum:** 2026-07-20
|
||||
**Verfasser:** Rainer (Architektur-Review, keine Code-Änderungen)
|
||||
|
||||
---
|
||||
|
||||
## P0-1: Sub-Phase Dispatch broken
|
||||
|
||||
### Befund
|
||||
Bei Klick auf `REVIEW_ROOM_EDIT::<rid>::edit` (Renderer `onboarding_review.py` Z.207, Prefix-Bau) fällt die Button-Payload in den **freien LLM-Archivar-Dispatch**. Der Agent antwortet mit `Raum-Namen ändern? Thema? 2FA? Passwort?`.
|
||||
|
||||
**Beweiskette:**
|
||||
|
||||
1. Button-Bau `_build_custom_buttons` in `__init__.py` Z.61-87 erzeugt `msg_payload = f"{prefix}::{display}"`. Bei `prefix="REVIEW_ROOM_EDIT::rid::edit"` und `display="✏️ MeinRaum"` ist die finale Payload **4-Segment**: `REVIEW_ROOM_EDIT::rid::edit::✏️ MeinRaum`. Dispatcher `dispatch_review_button` in `onboarding_review.py` Z.684-703 parst aber `parts = payload.split("::")` und greift `parts[1]`, `parts[2]` → das passt *trotzdem* für `kind == "edit"`.
|
||||
|
||||
2. **Root Cause:** Der `is_onboarding`-Bypass in `adapter.py` Z.1793-1805 listet die Phasen `butler_mode`, `catch_all_change`, `fakt_store` auf — **aber NICHT** `review_room`, `review_butler`, `review_fakt`. Folge: bei `phase == "review_room"` evaluiert `is_onboarding` zu `False` → die Nachricht geht durch zur Archivar-Klassifikation → LLM interpretiert die Button-Payload als freie Frage.
|
||||
|
||||
3. Dispatch-Logik `dispatch_review_button` selbst ist **funktional korrekt** und wird in `adapter.py` Z.436}| innerhalb der `phase == "review_room"`-Verzweigung aufgerufen — die Verzweigung wird nur nie erreicht.
|
||||
|
||||
### Bewertung
|
||||
- Severity: **P0 / Blocker** — kompletter Review-Flow Schritt 1 (Raum-Map-Anpassung) unbenutzbar.
|
||||
- Test-Coverage: `test_fact_store_onboarding.py` testet `FAKT::`-Prefix im `is_onboarding`-Check (Z.437-612), aber **kein** Test für `REVIEW_ROOM_EDIT::` / `REVIEW_ROOM_KW_ADD::` / `REVIEW_ROOM_THEME_SAVE::`-Prefix. Regression-Schutz fehlt.
|
||||
- Architektur: sauber, nur eine Stelle (L. 1793) ist unvollständig.
|
||||
|
||||
### Empfehlung (verbal)
|
||||
Den `is_onboarding`-Ausdruck in `adapter.py` Z.1793 um drei zusätzliche Phasen-Checks erweitern: `self._onboarding_state.get("phase") == "review_room"` / `== "review_butler"` / `== "review_fakt"`. Da `onboarding_active` bereits zuverlässig auf `True` bleibt (gesetzt in `_start_onboarding_review` Z.5328), reicht die Phase-Erkennung. Optional zusätzlich `stripped.startswith("REVIEW_ROOM")` und `stripped.startswith("REVIEW_BUTLER")`/`startswith("REVIEW_FAKT")` als Belt-and-Braces, da diese Prefixes ausschließlich im Review-Flow vorkommen. Danach landet die Nachricht in `_process_onboarding_response(text, room_id)` (Z.1807), dort in `state.get("phase") == "review_room"`-Zweig (Z.4271), und der vorhandene `dispatch_review_button`-Aufruf (Z.4365) feuert korrekt.
|
||||
|
||||
**Test:** Ergänzen in `test_fact_store_onboarding.py` oder neuem `test_review_room_dispatch.py`:
|
||||
- Szenario: Mock-Adapter mit `phase="review_room"`, `pending_text_input=False`. Eingehender Text `REVIEW_ROOM_EDIT::r1::edit::✏️ Raum1`. Erwartung: `is_onboarding=True`, `_process_onboarding_response` wird aufgerufen.
|
||||
- Szenario 2: Phase `review_room`, Text `REVIEW_ROOM_KW_ADD::r1::🔑 Kw100`. Erwartung: `sub_phase=keywords_edit`, `pending_text_input=True`.
|
||||
|
||||
---
|
||||
|
||||
## P0-2: Keywords neu/ändern/löschen fehlen als Button-Optionen
|
||||
|
||||
### Befund
|
||||
Andreas fordert für `Keywords 100% bearbeiten` drei strukturierte Aktionen: **Keyword hinzufügen** (Freitext erlaubt), **Keyword entfernen** (X-Buttons pro Keyword), **Zurück**.
|
||||
|
||||
**Aktueller Stand:** `render_review_room_keywords_edit` in `onboarding_review.py` Z.325-392 zeigt:
|
||||
- Aktuelle Keywords mit `❌ <kw>`-Button pro Keyword (Z.362-366) → **„entfernen" funktioniert**
|
||||
- Hinweis „Antworte mit einem neuen Keyword" (Z.376) → **„hinzufügen" geht nur über Freitext**
|
||||
- `↩️ Zurück`-Button (Z.379-383) → **„zurück" funktioniert**
|
||||
|
||||
Dispatch `dispatch_review_button` Z.706-718 (für `REVIEW_ROOM_KW_ADD::`) und Z.721-741 (für `REVIEW_ROOM_KW_REMOVE::`) ist vorhanden.
|
||||
|
||||
### Bewertung
|
||||
- **Teilweise schon implementiert.** Die Funktion ist da, sie fällt nur wegen P0-1 nicht auf — nach P0-1-Fix ist P0-2 zu großen Teilen automatisch gelöst.
|
||||
- Was fehlt: **expliziter „Keyword hinzufügen"-Button** statt nur Hinweistext. Der Renderer hat aktuell keinen separaten Button, der in den `pending_text_input=True`-Modus schaltet. Stattdessen wird `pending_text_input=True` sofort beim Aufruf der Sub-Phase gesetzt (Z.716) — der User wird also ungefragt in den Freitext-Modus gezwungen. UX-Schwachpunkt.
|
||||
|
||||
### Empfehlung (verbal)
|
||||
Im `render_review_room_keywords_edit` (Z.325) den Hinweistext Z.376-377 durch einen expliziten Button ersetzen — Label `➕ Hinzufügen` (oder `1️⃣` falls mehr Aktionen dazu kommen), Prefix `REVIEW_ROOM_KW_ADD::<rid>` mit einer speziellen Sub-Action (z.B. `::add_input`), die nur `pending_text_input=True` setzt, ohne den Renderer zu verlassen. Der „Zurück"-Button bleibt. Die jetzige `REVIEW_ROOM_KW_ADD::`-Variante kann diesen „add_input"-Trigger übernehmen, oder ein neuer `REVIEW_ROOM_KW_ADD_INPUT::` wird eingeführt. Variante 2 ist sauberer. Test in `test_review_room_subphases.py`: nach Klick auf „Hinzufügen" soll `pending_text_input=True` sein und ein Textfeld-Hinweis erscheinen.
|
||||
|
||||
---
|
||||
|
||||
## P0-3: ::onboarding abort killt nicht den laufenden Agent-Task
|
||||
|
||||
### Befund
|
||||
`::onboarding abort` in `adapter.py` Z.3251-3265 setzt nur State zurück:
|
||||
- `self._onboarding_state = {}`
|
||||
- `self.archivar._stats["onboarding_active"] = False`
|
||||
- `self.archivar._state.clear_onboarding_state()`
|
||||
- `sm.abort()` (State-Machine)
|
||||
- `release_onboarding_lock` für `missing_rooms`
|
||||
|
||||
**Was nicht passiert:** Der laufende LLM-Iterations-Loop (Archivar-Klassifikation + Archivar-Antwortgenerierung, der 7/90 / 9 min lang weiterläuft) wird **nicht abgebrochen**. `adapter.py` hält keine Referenz auf den `handle_message`-Task; der Loop läuft im Hermes-Core-Drain-Task, der via `contextvars.copy_context()` + `await ctx.run(self.handle_message, event)` (Z.2674/2685) gestartet wird.
|
||||
|
||||
### Bewertung
|
||||
- Severity: **P0** — User-Erwartung „Agent hört auf zu grübeln" wird verletzt.
|
||||
- **Core-Architektur-Problem:** Der Agent-Loop läuft im Hermes Core, nicht im Plugin. Das Plugin hat nur `ctx.run` als Black-Box — kein Task-Handle.
|
||||
- Lokale Plugin-Mitigation möglich, vollständige Core-Lösung nicht.
|
||||
|
||||
### Empfehlung (verbal)
|
||||
**Zwei Schichten:**
|
||||
|
||||
1. **Sofortmaßnahme (Plugin):** In `::onboarding abort` (Z.3251) zusätzlich eine **Cancellation-Marker-Datei** schreiben, z.B. `~/.hermes/.onboarding_aborted`. Die `is_onboarding`-Erkennung (Z.1793) prüft zusätzlich auf das Vorhandensein dieser Datei — falls vorhanden, wird die nächste eingehende Message des Operators abgefangen und der `archivar.handle_message` wird via `archivar._state.set_onboarding_state({})` (oder besser: ein neuer `archivar.cancel_inflight()`) zum Stoppen aufgefordert. **Wichtig:** den Marker nach Verarbeitung löschen, sonst permanente Sperre.
|
||||
|
||||
2. **Saubere Lösung (Core, nicht im Plugin-Scope):** Hermes Core bräuchte einen „abandon current generation"-API-Aufruf, der im Core den laufenden `asyncio.Task` cancelled. Dafür muss der Core `contextvars`-Snapshot so erweitern, dass er einen `asyncio.Event` (oder `CancellationToken`) registriert, den das Plugin via REST/Callback triggern kann. **Dies ist außerhalb des Plugin-Scopes** — Andreas muss Miguel darauf hinweisen, einen Core-PR zu erstellen.
|
||||
|
||||
**Pragmatischer Kompromiss:** Im Plugin-Adapter einen `archivar.cancel_inflight()`-Hook definieren, der das interne `_llm_semaphore` (gesehen in `router.py` Z.1844) released und einen `archivar._abort_event = asyncio.Event()` setzt. Den Hook im Router an `asyncio.wait_for`-Stellen prüfen. Das ist die **tiefste sinnvolle Plugin-Ebene**.
|
||||
|
||||
**Test:** Mock-Szenario: `archivar` simuliert 5s laufenden Task (`await asyncio.sleep(5)`). `::onboarding abort` aufrufen nach 1s. Erwartung: Task wird innerhalb 100ms gecancelt, `CancelledError` wird gefangen und geloggt, KEINE Archivar-Antwort wird mehr in den Raum gepostet.
|
||||
|
||||
---
|
||||
|
||||
## P1-4: Response formatting failed bei längeren Antworten
|
||||
|
||||
### Befund
|
||||
Bei längeren LLM-Antworten (>~4000 Zeichen) wird die Nachricht mit `'(Response formatting failed, plain text:)'` eingeleitet und mitten im Satz abgeschnitten. Token-Budget (9.9%), Request-Count (27) und Modell (`qwen2.5:7b` nur als Archivar) sind nicht die Ursache.
|
||||
|
||||
**Vermuteter Pfad:** `__init__.py` Z.127 setzt `max_message_length=4000`. Das ist nur eine **Konfiguration an Hermes Core**, kein Plugin-Code. `post_message` in `adapter.py` Z.190-209 sendet `text` roh an `chat.postMessage` REST-Endpoint — **ohne Längenprüfung, ohne Chunking**. Wenn der LLM-Output >4000 Zeichen ist, kappt Rocket.Chat serverseitig (oder der Renderer schneidet Markdown-Block-Boundaries mitten in der Mitte).
|
||||
|
||||
Die `'(Response formatting failed, plain text:)'`-Phrase ist **nicht im Plugin-Code** — sie kommt aus dem Hermes Core (Renderer/Formatter-Pipeline). Das Plugin sieht sie nur als fertigen Text.
|
||||
|
||||
### Bewertung
|
||||
- Severity: **P1** — funktional, aber Datenverlust. Andreas hat recht: „Antwort mitten im Fluss unterbrochen".
|
||||
- **Nicht durch Plugin behebar, wenn Renderer im Core liegt.** Aber: Plugin **kann** die Symptome mildern, indem es serverseitiges Chunking **vor** dem Senden macht.
|
||||
|
||||
### Empfehlung (verbal)
|
||||
**Im Plugin** (in `RocketChatAdapter.post_message`, `adapter.py` Z.190-209, und im async-Wrapper `_post_message_with_retry` Z.880-906):
|
||||
|
||||
1. **Pre-Flight-Längenprüfung:** Wenn `len(text) > 4000`, vor dem Senden aufteilen. Split-Strategie: an `\n\n`-Boundary, max 3500 Zeichen pro Chunk, Suffix `(Teil X/N)` an den Header jedes Chunks anhängen. Implementierung als Helper-Funktion `_chunk_text(text, max_len=3500)` in `adapter.py`.
|
||||
|
||||
2. **Async-Chunk-Posting:** `post_message` um `chunks: list[str]` erweitern; falls `len(chunks) > 1`, sequenziell mit kleiner Pause (0.3s) posten, um Rocket.Chat-Rate-Limits nicht zu triggern.
|
||||
|
||||
3. **Zusätzlich:** In der Core-Plattform-Konfiguration `max_message_length=4000` reduzieren auf `2000`, damit der Core-Renderer kleinere Häppchen an das Plugin liefert. Konfigurationsänderung in `__init__.py` Z.127.
|
||||
|
||||
**Test:** Mock-Szenario: 6000-Zeichen-Text posten. Erwartung: 2:.x getrennte Messages à ≤3500 Zeichen, jedes mit `(1/2)`-Suffix. Rocket.Chat-Server-Response simulieren (kein 4xx). Boundary-Test: Split darf nicht mitten in einem Markdown-Codeblock erfolgen.
|
||||
|
||||
**Hinweis an Andreas:** Die `'Response formatting failed, plain text:'`-Phrase ist Core-seitig, das Plugin bekommt den bereits formatierten Text. Wenn die Formatierung selbst kaputt ist, ist es ein Core-Bug — bitte `hermes agent` direkt loggen lassen.
|
||||
|
||||
---
|
||||
|
||||
## P1-5: ::multiroom off/on soll .env selbst schreiben
|
||||
|
||||
### Befund
|
||||
`::_cmd_multiroom` in `adapter.py` Z.3088-3126, Subcommand `off` (Z.3114-3121) und `on` (Z.3106-3113) geben beide nur Text-Anweisungen zurück:
|
||||
- `off`: „Setze `MULTIROOM_AGENT=false` in der `.env`-Datei und starte den Gateway-Dienst neu"
|
||||
- `on`: analog für `true`
|
||||
|
||||
### Bewertung
|
||||
- Severity: **P1** — UX, „zu schwer für Mode-Wechsel" wie Andreas sagt.
|
||||
- **Lösbar im Plugin** wenn .env-Pfad und Schreibstrategie klar sind.
|
||||
- **Aber:** Der Adapter läuft im **gleichen Prozess wie der Gateway**. `systemctl restart hermes-gateway` aus dem Gateway-Prozess heraus killt sich selbst. Andreas nennt das explizit als „Gateway-Blocker".
|
||||
|
||||
### Empfehlung (verbal)
|
||||
**Zweistufig mit Bestätigungs-Button** (genau wie `::multiroom on` es heute schon andeutet):
|
||||
|
||||
1. **Stufe 1** in `::_cmd_multiroom` (Z.3114-3121): Statt sofort Hinweistext zurückgeben, eine **Bestätigungs-Nachricht mit Buttons** senden:
|
||||
- `✅ Ja, .env schreiben` (Prefix `MULTIROOM_OFF_CONFIRM`)
|
||||
- `↩️ Abbrechen` (Prefix `MULTIROOM_OFF_CANCEL`)
|
||||
- Hinweistext: „Ich schreibe `MULTIROOM_AGENT=false` in `~/.hermes/.env`. Du musst danach `hermes gateway restart` ausführen. ⚠️ Diese Aktion kann nicht rückgängig gemacht werden ohne manuellen Eingriff."
|
||||
|
||||
2. **Stufe 2** in `MULTIROOM_OFF_CONFIRM`-Handler:
|
||||
- `.env`-Pfad ermitteln: aus `os.getenv('HERMES_ENV_FILE')` (falls gesetzt) oder Default `~/.hermes/.env` (aus `pathlib.Path.home() / '.hermes' / '.env'`).
|
||||
- **Existenzprüfung:** wenn Datei nicht existiert, Anlegen mit `MULTIROOM_AGENT=false\n` + `chmod 600`.
|
||||
- **Existiert die Datei:** Zeile finden mit Regex `^MULTIROOM_AGENT=.*`; ersetzen; **wenn Zeile nicht gefunden**, ans Dateiende anhängen.
|
||||
- **Backup:** vor dem Schreiben `.env.bak.<timestamp>` anlegen (Pattern wie install.sh bereits nutzt — siehe F6 R7).
|
||||
- **Validierung:** Datei reread, prüfen dass `MULTIROOM_AGENT=false` jetzt drinsteht.
|
||||
- **Antwort:** „✅ `MULTIROOM_AGENT=false` in `.env` geschrieben. ⚠️ Bitte `hermes gateway restart` manuell ausführen — ich kann den Gateway nicht von innen neu starten (würde mich selbst killen)."
|
||||
|
||||
3. **Selbe Stufen für `on` analog.**
|
||||
|
||||
**Test:** Mit tmpdir als .env-Pfad: Datei existiert nicht → Anlegen + Inhalt prüfen. Datei existiert mit `MULTIROOM_AGENT=true` → ersetzen, alter Wert weg, Backup existiert. Datei existiert ohne Zeile → append. Datei read-only → graceful error message, kein crash.
|
||||
|
||||
**Edge-Case:** Plugin läuft im Hermes-Gateway-Prozess, .env wird **von Hermes beim Start** geladen — _MULTIROOM() (Z.38) liest Env-Var. Nach .env-Schreiben muss der Prozess neu starten, um den neuen Wert zu sehen. **Klar kommunizieren** im Bestätigungs-Text.
|
||||
|
||||
---
|
||||
|
||||
## P1-6: Approval-Befehle als :: Varianten
|
||||
|
||||
### Befund
|
||||
Hermes Core generiert bei `Dangerous command requires approval`-Meldungen Slash-Commands `/approve` / `/deny` im Text der Anfrage-Nachricht. Rocket.Chat unterstützt keine `/`-Präfix-Commands (siehe `inline_commands.py` Z.166-176, wo der ganze `::` statt `/`-Mechanismus etabliert ist). User kann die Anfrage nicht bestätigen.
|
||||
|
||||
**Plugin-seitige Code-Suche:** Kein Treffer für `approve` / `deny` / `Dangerous command` in `plugin/`. Die Texte sind hermes-core-generiert.
|
||||
|
||||
### Bewertung
|
||||
- Severity: **P1** — funktionaler Blocker für gefährliche Kommandos im RC-Plugin.
|
||||
- **Lösbar im Plugin** via **Text-Rewrite-Layer**.
|
||||
|
||||
### Empfehlung (verbal)
|
||||
**Im Adapter** (`_process_incoming` in `adapter.py`, dort wo eingehender User-Text gelesen wird, Z.1496):
|
||||
|
||||
1. **Text-Scan:** Wenn `text.strip().lower()` matched gegen `^/approve\b`, `^/deny\b`, `^/approve\s+session\b`, `^/approve\s+always\b` (case-insensitive), in `::`-Variante umschreiben: `text = re.sub(r'^/approve\b', '::approve', text, flags=re.IGNORECASE)` etc. **Wichtig:** vor jeglichem weiteren Dispatch anwenden, also direkt in der Eingangs-Pipeline.
|
||||
|
||||
2. **Neue ::-Commands registrieren** in `_register_inline_commands` (`adapter.py` um Z.2721 ff.):
|
||||
- `::approve` → Handler `_cmd_approve(room_id, args)`: leitet weiter an Hermes-Core-Approval-API. Core-Interface: vermutlich `ctx.approve_pending(once=True)` (genauer API-Aufruf in Hermes Core zu klären). **Hinweis:** Die Approval-Hooks leben in Core, das Plugin reicht nur durch.
|
||||
- `::approve session` → `ctx.approve_pending(session=True)`
|
||||
- `::approve always` → `ctx.approve_pending(always=True)`
|
||||
- `::deny` → `ctx.deny_pending()`
|
||||
|
||||
3. **Outgoing-Message-Rewrite:** Im `post_message`-Wrapper (`_post_message_with_retry` Z.880) ebenfalls scannen: wenn der **zu sendende Text** `/approve` oder `/deny` enthält (kommt vom Core-Renderer), durch `::approve` / `::deny` ersetzen, **bevor** er an Rocket.Chat geht. So sieht der User die `::`-Form, auch wenn der Core-Generator noch `/` benutzt.
|
||||
|
||||
4. **Help-Text erweitern** in `build_help_text` (`inline_commands.py` Z.134): Neue Kategorie `„Sicherheit"` mit Einträgen `::approve` / `::approve session` / `::approve always` / `::deny`.
|
||||
|
||||
**Test:** Mock-Szenario: User sendet Text `/approve yes`. Nach `_process_incoming` ist `text == "::approve yes"`. Test 2: Core-Output-Text „Type `/approve` to confirm" — nach Post-Wrapper-Rewrite sieht der User im Raum „Type `::approve` to confirm". Test 3: `::approve` als registrierter Command erscheint in `::hilfe`-Output.
|
||||
|
||||
**Out-of-Scope-Hinweis:** Wenn Hermes Core eigene `/approve`-Buttons (Action-Buttons) generiert, ist die URL-Form (`postMessage` mit `actions`) zu bevorzugen — das Plugin sollte die Buttons dann **nicht** in Text-Form umschreiben, sondern als native RC-Buttons weiterleiten. Aktuell ist die Code-Analyse unklar, welche Form Core liefert — Andreas/Miguel klären vor Implementation.
|
||||
|
||||
---
|
||||
|
||||
## UX-7: Button-Nummern + kurze Texte
|
||||
|
||||
### Befund
|
||||
Rocket.Chat-Desktop kürzt Button-Labels auf ~7-11 Zeichen (siehe `__init__.py` Z.64). Im Plugin-Code existieren bereits `EMOJI_NUMBERS` in `adapter.py` Z.3795: `["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]`. Pattern wird **aber nur an einer Stelle** konsequent genutzt (Auto-Onboarding Z.3819-3827).
|
||||
|
||||
**Review-Flow Buttons** (in `onboarding_review.py`) verwenden Emoji-Präfixe aber keine Nummern:
|
||||
- Z.207-212: `f"✏️ {entry.name}"` — kann lang werden, je nach Raum-Name
|
||||
- Z.282: `„🔑 Kw100 bearbeiten"`
|
||||
- Z.287: `„📝 KwKontext bearbeiten"`
|
||||
- Z.292: `„🏷️ Theme bearbeiten"`
|
||||
- Z.297: `„🎯 Catch-All umschalten"`
|
||||
- Z.302: `„🗑️ Raum entfernen"`
|
||||
- Z.307: `„↩️ Zurück"`
|
||||
|
||||
Bei mehreren Räumen wären nummerierte Buttons sinnvoll.
|
||||
|
||||
### Bewertung
|
||||
- Severity: **UX** — niedrig, aber konsistent.
|
||||
- Pattern ist etabliert, muss nur durchgezogen werden.
|
||||
|
||||
### Empfehlung (verbal)
|
||||
**Zentrale Helper-Funktion** in `plugin/__init__.py` (oder neue `plugin/button_helpers.py`) hinzufügen:
|
||||
|
||||
1. `EMOJI_NUMBERS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]` aus `adapter.py` Z.3795 **in den Helper verschieben** und exportieren. In `adapter.py` referenzieren.
|
||||
|
||||
2. `numbered_button_labels(items: list[str], emoji_first: bool = True) -> list[str]`: Nimmt eine Liste semantischer Labels, gibt Liste `["1️⃣ Kw100", "2️⃣ KwKontext", "3️⃣ Theme", ...]` zurück. Bei langen Items Kürzung auf 8-9 Zeichen + Emoji + Nummern.
|
||||
|
||||
3. **In `onboarding_review.py` anwenden:**
|
||||
- Z.207-212: Pro Raum `f"{i+1}️⃣ {entry.name[:8]}"` statt `f"✏️ {entry.name}"`. Header zeigt zusätzlich vollen Namen in Text-Block.
|
||||
- Z.281-310: Sub-Phase-Buttons durchnummerieren — `1️⃣ Kw100`, `2️⃣ KwKontext`, `3️⃣ Theme`, `4️⃣ CatchAll`, `5️⃣ Entfernen`, `↩️ Zurück`.
|
||||
- Z.362-366: Keyword-X-Buttons — Nummern sind hier kontraproduktiv (dynamisch wachsende Liste), aber Prefix `❌` + kurzes Keyword (max 6 Zeichen mit Ellipsis) reicht.
|
||||
|
||||
4. **In `adapter.py` Z.4429-4431, Z.4486-4489:** Die `["✏️ Ändern", "⏭️ Beibehalten"]`-Buttons in Butler/FAKT-Review durch `["1️⃣ Ändern", "2️⃣ Beibehalten"]` ersetzen.
|
||||
|
||||
5. **In `adapter.py` Z.4211, Z.4223, Z.4235:** Die FAKT-Speicherort-Options (4 Stück) bereits mit `1️⃣/2️⃣/3️⃣/4️⃣` gematcht (Z.4211, 4223, 4235 matchen `"1️⃣"`, `"2️⃣"`, etc.) — das ist konsistent, gut.
|
||||
|
||||
**Test:** In `test_review_room_subphases.py` für jeden Renderer prüfen, dass die Button-Texte ≤11 Zeichen sind, mit Emoji beginnen, und (wo anwendbar) eine leading Emoji-Nummer tragen. Test in `test_r5_inline_commands.py` für die Help-Text-Generierung: `::hilfe` listet nummerierte Befehle mit gleicher Konsistenz.
|
||||
|
||||
---
|
||||
|
||||
## UX-8: Agent halluziniert bei Fragen zu :: Befehlen
|
||||
|
||||
### Befund
|
||||
User fragt „Was macht `::curate`?" → Agent halluziniert Erklärung (Duplikate-Erkennung, ja/nein-Optionen, `auto_apply`-Setting). Realität: `::curate` existiert möglicherweise gar nicht oder hat andere Semantik.
|
||||
|
||||
`is_natural_help_request` in `inline_commands.py` Z.56-73 triggert auf bestimmte Phrasen (z.B. „was kannst du", „hilfe"), aber **nicht** auf das Pattern „Was macht `::XYZ`?" oder „Was ist `::XYZ`?".
|
||||
|
||||
### Bewertung
|
||||
- Severity: **UX** — Vertrauensverlust bei Operator.
|
||||
- **Lösbar im Plugin** durch zusätzliche Trigger in `is_natural_help_request` und einen **Help-Lookup-Handler** der `::XYZ`-Namen auflöst.
|
||||
|
||||
### Empfehlung (verbal)
|
||||
**Im Plugin** (`inline_commands.py`):
|
||||
|
||||
1. **Neue Trigger in `NATURAL_HELP_TRIGGERS`** (Z.31-53): Hinzufügen:
|
||||
- „was macht" (exakt, lowercased)
|
||||
- „was ist" (exakt)
|
||||
- „erkläre"
|
||||
- „erklären"
|
||||
- „hilfe zu" (enthält-Match für „hilfe zu ::xyz")
|
||||
- „dokumentation"
|
||||
|
||||
2. **Neue Funktion `extract_command_question(text) -> Optional[str]`** in `inline_commands.py`:
|
||||
- Matched Regex `r"(?:was macht|was ist|erkläre?)\s+::([a-z_]+)"` (case-insensitive).
|
||||
- Gibt den Command-Namen zurück (z.B. `"curate"`) oder `None`.
|
||||
|
||||
3. **Neue Helper-Funktion `build_command_help(registry, command_name) -> str`**:
|
||||
- Wenn `registry.is_registered(command_name)` → formatierten Help-Block zurückgeben: `## ::{name}\n\n{description}\n\n{help_text}\n\n{falls subcommands: subcommands-Liste}`.
|
||||
- Wenn **nicht** registriert → „❌ `::{name}` ist kein bekannter Befehl. Verfügbare Befehle: {comma-separated list aus registry.get_commands().keys()}.".
|
||||
|
||||
4. **Integration in `_process_incoming` / Inline-Command-Pfad** (`adapter.py` dort wo `is_natural_help_request` aufgerufen wird):
|
||||
- Vor `is_natural_help_request(text)`: prüfe `cmd_name = extract_command_question(text)`. Wenn nicht None, leite an `build_command_help(registry, cmd_name)` und poste das Ergebnis. **Skip** den LLM-Dispatch.
|
||||
- Wenn `is_natural_help_request(text)` True → poste `build_help_text(registry, room_map_summary)`.
|
||||
|
||||
5. **Reihenfolge wichtig:** `extract_command_question` **vor** dem LLM-Dispatch ausführen, **bevor** `archivar.handle_message` aufgerufen wird. Sonst sieht der Archivar die Frage zuerst und halluziniert.
|
||||
|
||||
**Test:**
|
||||
- Szenario: User-Text „Was macht `::sethome`?". Erwartung: Adapter postet `## ::sethome\n\nSetzt den Heimatraum...` OHNE LLM-Aufruf. Test 2: „Was macht `::curate`?" (nicht registriert). Erwartung: Adapter postet „❌ `::curate` ist kein bekannter Befehl" + Liste. Test 3: User-Text „Was ist 2+2?" (kein `::` enthalten). Erwartung: normale LLM-Verarbeitung, kein Help-Lookup.
|
||||
|
||||
**Edge-Case:** Was, wenn `::curate` doch existiert, aber in einer anderen Plugin-Registry? Aktuell nur die lokale `self._inline_commands` wird konsultiert. Multi-Plugin-Awareness ist out-of-scope — falls nötig, später via Hermes-Core-Plugin-Manager-API.
|
||||
|
||||
---
|
||||
|
||||
## Zusammenfassung
|
||||
|
||||
| ID | Severity | Datei(en) | Fix-Aufwand |
|
||||
|----|----------|-----------|-------------|
|
||||
| P0-1 | P0 | adapter.py Z.1793-1805 | 5 min, +2 Tests |
|
||||
| P0-2 | P0 (gelöst mit P0-1) | onboarding_review.py Z.325-392 | 15 min, +1 Test |
|
||||
| P0-3 | P0 | adapter.py Z.3251-3265 + archivar intern | 30 min Plugin + Core-PR |
|
||||
| P1-4 | P1 | adapter.py Z.190-209, Z.880-906 | 20 min, +2 Tests |
|
||||
| P1-5 | P1 | adapter.py Z.3088-3126 | 40 min, +3 Tests |
|
||||
| P1-6 | P1 | adapter.py (input-Filter + post_message-Filter) | 30 min, +3 Tests |
|
||||
| UX-7 | UX | onboarding_review.py, adapter.py, __init__.py | 25 min, +2 Tests |
|
||||
| UX-8 | UX | inline_commands.py, adapter.py (Trigger) | 20 min, +3 Tests |
|
||||
|
||||
**Empfohlene Reihenfolge:** P0-1 → P0-2 (fällt mit) → P0-3 → P1-4 → P1-5 → P1-6 → UX-7 → UX-8.
|
||||
|
||||
**Hinweis an Andreas:** Für P0-3 brauchen wir Klarheit über die Hermes-Core-Approval-/Cancellation-API. Für P1-4 ist die Core-Seite ('Response formatting failed, plain text:'-Quelle) zu untersuchen — falls Core-bug, ist `hermes agent` direkt zu konsultieren. Alle anderen Fixes sind im Plugin-Scope umsetzbar.
|
||||
@@ -0,0 +1,609 @@
|
||||
# Archivar — Funktionsbeschreibung v8.5
|
||||
|
||||
> **Version:** v8.5
|
||||
> **Datum:** 21.07.2026
|
||||
> **HEAD:** `afa462c` (Commit: *fix: Per-Room Pending Question Resolver — Zombie-State bei stay_once/confirm_move/generell_hier behoben, pending-Set Konsolidierung bei Raumwechsel*)
|
||||
> **Repo:** `~/projekte/Hermes_rocket.chat_Plugin`
|
||||
> **Zielgruppe:** Entwickler UND Anwender
|
||||
> **Sprache:** Deutsch
|
||||
|
||||
---
|
||||
|
||||
## 1. Überblick
|
||||
|
||||
### 1.1 Was ist der Archivar?
|
||||
|
||||
Der **Archivar** ist ein **thematischer Raum-Router** für den Hermes Rocket.Chat-Plugin im Multi-Room-Modus. Er beantwortet genau eine Frage: **„In welchen Themenraum gehört diese Nachricht?"** — nicht *„Ist das eine Frage, Smalltalk oder ein Auftrag?"*.
|
||||
|
||||
Im Gegensatz zu klassischen Intent-Klassifikatoren klassifiziert der Archivar nicht in **Kategorien**, sondern direkt in **Zielräume**. Jeder Raum in der `room-map.json` ist thematisch definiert; der Archivar wählt den passenden Raum anhand von Keywords, Embeddings und (wenn nötig) einem LLM.
|
||||
|
||||
### 1.2 Welches Problem löst er?
|
||||
|
||||
In einem Multi-Room-Setup posten Nutzer in verschiedenen Kanälen, und der Agent soll **kontextuell korrekt antworten** — auch wenn der Nutzer im falschen Raum postet. Beispiele:
|
||||
|
||||
- Eine Rocket.Chat-Plugin-Frage landet im `#Allgemein`-Raum → Archivar schlägt Move-Request nach `#Rocketchat-Plugin` vor.
|
||||
- Eine Direktnachricht enthält 100% Plugin-Keywords → Archivar erlaubt Move-Request auch in DMs.
|
||||
- Eine Hintergrund-Frage ohne klares Thema → Catch-All-Raum, kein Herumraten.
|
||||
|
||||
### 1.3 Architektur-Prinzip: Das Drei-Rollen-Team
|
||||
|
||||
Der Archivar ist **kein alleiniger Entscheider**, sondern Teil eines Drei-Rollen-Teams:
|
||||
|
||||
| Rolle | Aufgabe | Entscheidet über |
|
||||
|--------------|-------------------------------------------------------------------------|-----------------------------|
|
||||
| **Archivar** | Routing: Welcher Raum? | **Wo** die Antwort erscheint |
|
||||
| **Agent** | Generierung: Was ist die Antwort? | **Was** geantwortet wird |
|
||||
| **Butler** | Genehmigung: Soll tatsächlich geroutet werden? | **Ob** der Move erfolgt |
|
||||
|
||||
Der Agent schreibt den Inhalt, der Archivar bestimmt den Raum, der Butler (in Form eines nativen Rocket.Chat Action-Buttons) fragt den Nutzer, bevor irgendetwas verschoben wird. **Keine Aktion erfolgt stillschweigend.**
|
||||
|
||||
---
|
||||
|
||||
## 2. Routing-Pipeline
|
||||
|
||||
Die Routing-Pipeline besteht aus **vier aufeinanderfolgenden Stufen**, geordnet nach absteigender Konfidenz. Jede Stufe produziert ein `RoutingDecision`-Objekt; sobald eine Stufe eine eindeutige Entscheidung trifft, wird die Pipeline beendet.
|
||||
|
||||
### 2.1 Stufe 1 — `keyword_100` (Score 1.00, Auto-Route)
|
||||
|
||||
- **Methode:** Morphologisches Matching (Stemming, Fuzzy) auf `keywords_100` der `RoomMap`
|
||||
- **Treffer:** Mindestens ein 100%-Keyword eines Raumes matcht im Text
|
||||
- **Aktion:** **Auto-Route** — keine Butler-Rückfrage, Nachricht wird direkt in den Zielraum geroutet
|
||||
- **Catch-All-Räume** werden in dieser Stufe nicht berücksichtigt (Catch-All ist nicht für Keyword-Match-Routing gedacht)
|
||||
|
||||
### 2.2 Stufe 2 — `context_keyword` (Score 0.95, Butler Move-Request)
|
||||
|
||||
- **Methode:** Exaktes Matching (case-insensitive) auf `keywords_context`
|
||||
- **Treffer:** Mindestens ein Kontext-Keyword eines Raumes matcht
|
||||
- **Aktion:** **Move-Request-Button** an den Nutzer mit drei Optionen:
|
||||
- `1️⃣ Rüber` → `confirm_move` (Message wird in Zielraum kopiert)
|
||||
- `2️⃣ Generell hier` → `stay_here` (dauerhaft im aktuellen Raum bleiben, lernt)
|
||||
- `3️⃣ Nur diesmal` → `stay_once` (nur diese eine Nachricht, kein Lernen)
|
||||
- **Wichtig:** Stufe 2 prüft zuerst den **Ursprungsraum** (Origin-Priorität) — wenn der aktuelle Raum ein passendes Kontext-Keyword hat, schlägt der Archivar *diesen* Raum vor, nicht einen anderen.
|
||||
|
||||
### 2.3 Stufe 3 — `red_flag` (Score 0.80, Agent entscheidet)
|
||||
|
||||
- **Methode:** Wenn nach Stufe 1+2 mehrere plausible Räume existieren und der Archivar unsicher ist, wird der **Agent** als 6. Entscheidungsträger befragt
|
||||
- **Aktion:** Archivar sendet dem Agenten den `RED_FLAG_PROMPT` mit Raumliste; der Agent antwortet mit `ROOM: <raumname>` in der ersten Zeile
|
||||
- **Timeout:** `RED_FLAG_TIMEOUT` (Default 30s) → STAY-Fallback (Antwort bleibt im Ursprungsraum)
|
||||
- **Feature-Flag:** `ARCHIVAR_RED_FLAG` (Default: AN)
|
||||
|
||||
### 2.4 Stufe 4 — `fallback` (Catch-All, DM)
|
||||
|
||||
- **Methode:** Kein Match in irgendeiner vorherigen Stufe
|
||||
- **Aktion:** Nachricht geht an den **Catch-All-Raum** (in `room-map.json` mit `catch_all: true` markiert)
|
||||
- **Wichtig:** Genau **ein** Catch-All-Raum ist erlaubt — Validierung scheitert sonst beim Start
|
||||
- **DMs:** Bei Direktnachrichten ohne 100%-Keyword-Match bleibt die Nachricht im DM; LLM antwortet direkt dort
|
||||
|
||||
```
|
||||
┌────────────────────────────────────────────────────────────┐
|
||||
│ Eingehende Nachricht │
|
||||
└────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌───────────────────────┐
|
||||
│ Stufe 1: keyword_100 │ → Auto-Route (1.00)
|
||||
└───────────────────────┘
|
||||
│ kein Treffer
|
||||
▼
|
||||
┌───────────────────────┐
|
||||
│ Stufe 2: context_kw │ → Move-Request (0.95)
|
||||
└───────────────────────┘
|
||||
│ kein Treffer / Butler lehnt ab
|
||||
▼
|
||||
┌───────────────────────┐
|
||||
│ Stufe 3: red_flag │ → Agent entscheidet (0.80)
|
||||
└───────────────────────┘
|
||||
│ unsicher / Timeout
|
||||
▼
|
||||
┌───────────────────────┐
|
||||
│ Stufe 4: fallback │ → Catch-All-Raum
|
||||
└───────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Butler-Modus
|
||||
|
||||
Der Butler-Modus steuert, **wann** ein Move-Request gezeigt wird. Drei Werte:
|
||||
|
||||
| Modus | Verhalten | Use-Case |
|
||||
|---------------|----------------------------------------------------------------------------|-----------------------------------------------|
|
||||
| `cognitive` | Kontext-Keywords → Move-Request, 100%-Keywords → Auto-Route (Default) | Ausgewogen, mit Lernchance |
|
||||
| `strict` | Move-Request bei JEDEM thematischen Treffer (100% UND Kontext) | Maximale Kontrolle, keine Auto-Routes |
|
||||
| `off` | Kein Move-Request, Agent antwortet im aktuellen Raum | Wenn der Nutzer ohne Routing arbeiten will |
|
||||
|
||||
**Hinweis:** Die Werte heißen im Code `cognitive`/`strict`/`off` (nicht `relaxed` — diese Bezeichnung existiert nicht im Code).
|
||||
|
||||
### 3.1 Move-Request-Buttons
|
||||
|
||||
Jeder Move-Request zeigt **drei nummerierte Buttons** in einer Reihe:
|
||||
|
||||
| Button | Aktion | Lerneffekt |
|
||||
|-------------------------|-----------------|-----------------------------------------------|
|
||||
| `1️⃣ Rüber` | `confirm_move` | Routing wird einmalig ausgeführt |
|
||||
| `2️⃣ Generell hier` | `stay_here` | Sticky-Eintrag im aktuellen Raum (persistent)|
|
||||
| `3️⃣ Nur diesmal` | `stay_once` | Einmaliges Bleiben, kein Lerneffekt |
|
||||
|
||||
Button-Texte müssen **Emoji+Text** sein (Desktop-Truncation bei ~7 Zeichen), keine Underscores.
|
||||
|
||||
---
|
||||
|
||||
## 4. Pending Question Resolver (Ansatz D)
|
||||
|
||||
**Status:** v8.5 — neu implementiert in `afa462c`.
|
||||
|
||||
### 4.1 Problem (vorher)
|
||||
|
||||
Der Adapter führte ein `_rooms_with_pending_questions: Set[str]` (Menge von Raum-IDs), in dem Räume mit offenen Move-Request-Fragen markiert waren. Drei konkrete Bugs:
|
||||
|
||||
- **Bug 1:** Button-Klicks aus anderen Räumen konsolidierten den pending-Set nicht.
|
||||
- **Bug 2:** `stay_once` entfernte den Raum nicht aus dem Set → **Zombie-State** (Raum blieb markiert, Archivar wurde dauerhaft übersprungen).
|
||||
- **Bug 3:** Keine Tests für diese Edge-Cases.
|
||||
|
||||
### 4.2 Lösung (Ansatz D)
|
||||
|
||||
- **Per-Room-Tracking:** `_rooms_with_pending_questions: Set[room_id]` bleibt — pro Raum-ID, nicht global.
|
||||
- **Button-Klicks konsolidieren den pending-Set:** Jeder erfolgreiche Klick auf `confirm_move` / `stay_here` / `stay_once` **discarded sowohl `origin_room` als auch `room_id`** aus dem Set (sofern vorhanden).
|
||||
- **Zombie-State behoben:** `stay_once` removed jetzt zuverlässig — kein Zurückbleiben.
|
||||
- **Tests:** 3 RED-Tests in `test_d_pending_resolver.py`, später GRÜN.
|
||||
|
||||
### 4.3 Auswirkung
|
||||
|
||||
Move-Request-Buttons und Sticky-Sessions funktionieren jetzt zuverlässig über Raumwechsel hinweg. Ein Nutzer kann in Raum A einen Move-Request auslösen, in Raum B auf `1️⃣ Rüber` klicken — beide Räume werden sauber aus dem pending-Set entfernt.
|
||||
|
||||
---
|
||||
|
||||
## 5. Onboarding (F8)
|
||||
|
||||
### 5.1 State Machine
|
||||
|
||||
Das Onboarding durchläuft eine persistente State-Machine (`onboarding_state.py`), gespeichert in `~/.hermes/hermes-agent/data/onboarding.yaml`:
|
||||
|
||||
```
|
||||
┌──────────┐ start ┌─────────────────┐
|
||||
│ NONE │ ─────────→ │ AWAITING_ROOM │ (Schritt 1)
|
||||
└──────────┘ └─────────────────┘
|
||||
↑ │ set name
|
||||
│ abort/reset ▼
|
||||
│ ┌─────────────────────┐
|
||||
│ │ AWAITING_INTENT │ (Schritt 2)
|
||||
│ └─────────────────────┘
|
||||
│ │ keywords setzen
|
||||
│ ▼
|
||||
│ ┌─────────────────────┐
|
||||
│ │ AWAITING_TEST │ (Schritt 3)
|
||||
│ └─────────────────────┘
|
||||
│ │ test bestanden
|
||||
│ ▼
|
||||
│ ┌─────────────────────┐
|
||||
└──────────────── │ ACTIVE │ (Schritt 4)
|
||||
└─────────────────────┘
|
||||
```
|
||||
|
||||
Zusätzlich existieren zwei Sonderzustände:
|
||||
|
||||
- `PAUSED` — aus jedem Active-State erreichbar, vom Nutzer oder System initiiert
|
||||
- `ERROR` — Recovery-Zustand, wartet auf `::onboarding resume`
|
||||
|
||||
**Restart-Verhalten:**
|
||||
- Datei fehlt → `NONE` (Standard-Routing)
|
||||
- `state=ACTIVE` → produktiver Pfad, kein Onboarding mehr
|
||||
- `state=AWAITING_*/PAUSED` → passiv fortsetzen beim ersten User-Input
|
||||
- `state=ERROR` → User informieren, auf `::onboarding resume` warten
|
||||
- `schema_version` mismatch → Migration oder Reset mit Warnung
|
||||
|
||||
### 5.2 Sechs ::onboarding-Befehle
|
||||
|
||||
| Befehl | Wirkung |
|
||||
|---------------------------|--------------------------------------------------------------|
|
||||
| `::onboarding start` | Startet das Onboarding (nur aus `NONE` oder `PAUSED`) |
|
||||
| `::onboarding reset` | Verwirft aktuellen Zustand, zurück zu `NONE` |
|
||||
| `::onboarding abort` | Bricht das laufende Interview ab |
|
||||
| `::onboarding status` | Zeigt aktuellen State, Schritt, fehlende Räume |
|
||||
| `::onboarding skip` | Überspringt den aktuellen Raum (markiert als `skipped`) |
|
||||
| `::onboarding help` | Zeigt Onboarding-Hilfeseite |
|
||||
|
||||
### 5.3 Strukturierter Review-Flow (F8 Hauptfeature)
|
||||
|
||||
Statt einer freien LLM-Raterunde (die halluzinieren kann) durchläuft der Review-Flow **sechs strukturierte Sub-Phasen** mit Buttons — **keine LLM-Bewertung** der Raum-Map:
|
||||
|
||||
1. **Keywords 100%** bearbeiten (`add` / `remove`)
|
||||
2. **Kontext-Keywords** bearbeiten (`add` / `remove`)
|
||||
3. **Theme** bearbeiten
|
||||
4. **Catch-All** umschalten (genau einer pro Map)
|
||||
5. **Raum entfernen**
|
||||
6. **Neuer Raum** (REST-Liste der verfügbaren Räume)
|
||||
|
||||
**Button-Pattern (verbindlich):**
|
||||
- Maximal 3 Buttons pro Reihe
|
||||
- Nummern erscheinen im Text UND im Button-Label (`1️⃣`, `2️⃣`, `3️⃣`)
|
||||
- Sonderschaltflächen (Zurück / Skip / Neu) in einer **separaten Reihe** darunter
|
||||
|
||||
**Freitext-Schutz:** `_reject_free_text()` lehnt Freitext-Eingaben in Sub-Phasen ab und fordert zur Button-Wahl auf. So können keine versehentlichen Tippfehler in die `room-map.json` gelangen.
|
||||
|
||||
### 5.4 Schreib-API für Room-Map
|
||||
|
||||
Aus `room_map.py` (`RoomMap`-Methoden):
|
||||
|
||||
| Methode | Wirkung |
|
||||
|--------------------------------------------------|-----------------------------------------------|
|
||||
| `add_keyword_100(room_id, keyword)` | Fügt 100%-Keyword hinzu |
|
||||
| `remove_keyword_100(room_id, keyword)` | Entfernt 100%-Keyword |
|
||||
| `add_keyword_context(room_id, keyword)` | Fügt Kontext-Keyword hinzu |
|
||||
| `remove_keyword_context(room_id, keyword)` | Entfernt Kontext-Keyword |
|
||||
| `set_theme(room_id, theme)` | Setzt das Raum-Thema |
|
||||
| `remove_room(room_id)` | Schließt Raum aus (Ausschluss-Pattern) |
|
||||
|
||||
Whitespace-Validierung: Keywords mit internen Leerzeichen werden abgelehnt (`if ' ' in kw: return False`); ein strikterer Check (`any(c.isspace())`) wäre robuster gegenüber Tabs/Newlines — derzeit kein Blocker, aber **Smell** in der Archivar-Architektur.
|
||||
|
||||
---
|
||||
|
||||
## 6. Inline-Befehle (`::`-Syntax)
|
||||
|
||||
Rocket.Chat unterstützt kein `/`-Prefix; deshalb verwendet das Plugin `::` als alternatives Command-Präfix. Registriert in `adapter.py` (`self._inline_commands.register(...)`).
|
||||
|
||||
### 6.1 Standard-Hermes-Befehle
|
||||
|
||||
| Befehl | Wirkung |
|
||||
|--------------|---------------------------------------------------------------|
|
||||
| `::hilfe` | Zeigt Hilfeseite mit allen Befehlen und Plugin-Status |
|
||||
| `::sethome` | Setzt den Heimatraum (Alternative zu `/sethome`) |
|
||||
| `::restart` | State-Cleanup + SIGTERM (systemd-linger startet neu) |
|
||||
| `::multiroom on/off/status` | Multi-Room-Modus schreiben + `::restart` anbieten |
|
||||
|
||||
### 6.2 RC-Plugin-spezifische Befehle
|
||||
|
||||
| Befehl | Wirkung |
|
||||
|---------------------------------|----------------------------------------------------------------|
|
||||
| `::onboarding` | Sub-Commands: start / reset / abort / status / skip / help |
|
||||
| `::setbutler` | Ändert den Butler-Modus (`cognitive` / `strict` / `off`) |
|
||||
| `::setfakt` | FAKT-Speicherort wählen (4-Optionen-Dialog) |
|
||||
| `::curate` | Wissenssammlung kuratieren (R10) |
|
||||
| `::approve [session\|always]` | Dangerous-Command-Genehmigung (einmalig / Session / permanent) |
|
||||
| `::deny` | Lehnt einen gefährlichen Befehl ab |
|
||||
|
||||
### 6.3 Command-Help bei `::`-Fragen
|
||||
|
||||
**Problem:** Auf die Frage „Was macht `::curate`?" würde der LLM halluzinieren (kein Trainings-Wissen über das Plugin).
|
||||
|
||||
**Lösung:** `extract_command_question(text)` in `inline_commands.py` erkennt Fragen über `::`-Befehle **vor** dem LLM-Dispatch:
|
||||
|
||||
- Patterns: `was macht ::`, `was ist ::`, `wie geht ::`, `erkläre ::`, `hilfe zu ::`, …
|
||||
- Extrahiert den Befehlsnamen
|
||||
- `build_command_help(registry, name)` baut einen formatierten Hilfetext aus dem registrierten `help_text` + `description` + `subcommands`
|
||||
|
||||
**Ergebnis:** Exakte, vom Code autorisierte Hilfe statt LLM-Halluzination.
|
||||
|
||||
---
|
||||
|
||||
## 7. Message Splitting
|
||||
|
||||
### 7.1 Verhalten
|
||||
|
||||
Lange Nachrichten werden **proaktiv** aufgeteilt, bevor sie an die Rocket.Chat-API gehen:
|
||||
|
||||
- **Schwelle:** > 3000 Zeichen
|
||||
- **Aufteilung:** An Absatzgrenzen (`\n\n`) — keine mid-word-Splits
|
||||
- **Marker:** `(1/4)`, `(2/4)`, `(3/4)`, `(4/4)` werden jeder Teilstück vorangestellt
|
||||
|
||||
### 7.2 Implementierung
|
||||
|
||||
In `sentence_markers.py` / `adapter.py` integriert. Die Logik respektiert Markdown-Struktur (Code-Blöcke, Listen) — die Aufteilung erfolgt **zwischen** Blöcken, nicht innerhalb.
|
||||
|
||||
---
|
||||
|
||||
## 8. Datei-Upload
|
||||
|
||||
### 8.1 Tool-Definition
|
||||
|
||||
`rocketchat_upload` ist eines von **sieben REST-Tools** in `plugin/tools.py`:
|
||||
|
||||
| Tool | Funktion |
|
||||
|------------------------|-------------------------------------------------------------|
|
||||
| `rocketchat_rooms` | Räume: list, create, archive, delete, invite, kick, history |
|
||||
| `rocketchat_users` | User: list, get, search |
|
||||
| `rocketchat_dm` | Direktnachrichten: open, send |
|
||||
| `rocketchat_send` | Senden mit Buttons |
|
||||
| `rocketchat_upload` | **Upload** — multipart/form-data |
|
||||
| `rocketchat_download` | Datei herunterladen |
|
||||
| `rocketchat_files` | Dateien im Raum auflisten |
|
||||
|
||||
### 8.2 Upload-Implementierung
|
||||
|
||||
`upload_file(room_id, file_path, message="", description="")` in `tools.py`:
|
||||
|
||||
1. Datei lesen und als multipart/form-data kodieren
|
||||
2. POST an `${base_url}/api/v1/rooms.media/${room_id}`
|
||||
3. Optional: `chat.postMessage` mit Beschreibung
|
||||
4. Rückgabe: JSON-Response von Rocket.Chat (inkl. `file_id`)
|
||||
|
||||
### 8.3 Agent-Workflow
|
||||
|
||||
Der Agent kann:
|
||||
1. Mit `execute_code` eine Datei erstellen (Python-Script, Report, etc.)
|
||||
2. Mit `rocketchat_upload` die Datei in einen Raum hochladen
|
||||
3. Die Antwort im Raum erscheint mit nativer Datei-Vorschau
|
||||
|
||||
---
|
||||
|
||||
## 9. Room-Map
|
||||
|
||||
### 9.1 Struktur
|
||||
|
||||
`~/.hermes/hermes-agent/data/room-map.json` ist die **Single Source of Truth** für:
|
||||
|
||||
- Raum-ID und -Name
|
||||
- Theme (ein Satz)
|
||||
- Description (ca. 200 Wörter, für LLM-Kontext)
|
||||
- `keywords_100` (Auto-Route-Anker)
|
||||
- `keywords_context` (Butler-Match)
|
||||
- `catch_all` (Flag)
|
||||
- `butler_mode` (cognitive / strict / off)
|
||||
- `fact_store_path`, `fact_store_strategy`, `fact_store_created_at`
|
||||
|
||||
### 9.2 Validierung (beim Start)
|
||||
|
||||
`RoomMap.validate(subscribed_ids)` prüft:
|
||||
- **Fatal:** Genau 0 oder >1 Catch-All-Räume → `RoomMapValidationError`
|
||||
- **Fatal:** Catch-All in `excluded_rooms` → `RoomMapValidationError`
|
||||
- **Warning:** Catch-All oder Räume nicht in Subscription-Liste
|
||||
|
||||
### 9.3 Suchstrategie (Reihenfolge)
|
||||
|
||||
`find_room_by_keywords(text, origin_room_id=None)`:
|
||||
|
||||
1. **100%-Keywords (alle Räume außer Catch-All):** Morphologisches Matching → bester Raum gewinnt
|
||||
2. **Origin-Priorität (Kontext):** Wenn `origin_room_id` selbst ein Kontext-Keyword hat → dieser Raum (nicht ein anderer)
|
||||
3. **Globaler Kontext-Scan:** Bester Kontext-Score über alle Räume
|
||||
4. **Catch-All erlaubt:** In Stufe 2+3 dürfen Catch-All-Räume als Butler-Ziel dienen
|
||||
|
||||
`min_score` (Default 1, gesenkt in v8.4.6 von 2 auf 1) — ein einzelnes Kontext-Keyword reicht für einen Butler-Vorschlag.
|
||||
|
||||
### 9.4 FAISS Phase-1
|
||||
|
||||
`RoomIndexManager` (in `room_index.py`) baut einen FAISS-Index über Raum-Themes und -Descriptions:
|
||||
|
||||
- **Embeddings:** nomic-embed-text (lokal via Ollama, 768-dim)
|
||||
- **Top-K:** 3 Treffer (`FAISS_TOP_K`)
|
||||
- **Auto-Route-Schwelle:** `FAISS_AUTO_ROUTE = 0.85` → direkt routen, kein LLM
|
||||
- **Min-Score:** `FAISS_MIN_SCORE = 0.50` → unter dieser Schwelle: Fallback auf LLM-Router
|
||||
- **Konflikt-Diff:** `FAISS_CONFLICT_DIFF = 0.05` → bei knappem Top-1/Top-2 entscheidet der Booster
|
||||
|
||||
**Drei-Schichten-Logik:** `FAISS → KeywordBooster → LLM`
|
||||
|
||||
### 9.5 KeywordBooster
|
||||
|
||||
`KeywordBooster.boost(text, scores)`:
|
||||
|
||||
- Eindeutiges Keyword (nur in 1 Raum) → +0.10 Boost für diesen Raum
|
||||
- Mehrere eindeutige Keywords → zusätzlich +0.05 pro weiterem Keyword
|
||||
- Konfliktlösung: bei Top-1/Top-2-Diff < 0.05 → +0.05 für Raum mit mehr eindeutigen Treffern
|
||||
|
||||
Speichert Match-Timestamps für **Demotion-Tracking** (lernendes System: Keywords, die lange nicht matchen, werden abgewertet).
|
||||
|
||||
---
|
||||
|
||||
## 10. Installation
|
||||
|
||||
### 10.1 Frisches Debian → fertiger Bot
|
||||
|
||||
`install.sh` automatisiert die komplette Installation in **9 Schritten** (Details in `INSTALL.md`):
|
||||
|
||||
1. System-Dependencies (Python 3.13, pipx, git, curl, Ollama)
|
||||
2. Hermes Agent (pipx, snowballstemmer, requirements.txt)
|
||||
3. Plugin aus Gitea (SSH-Key erforderlich: `~/.ssh/gitea_hermes_key`)
|
||||
4. `config.yaml` (provider=ollama-cloud, model=nemotron-3-super)
|
||||
5. `.env` (alle Maschinen-spezifischen Secrets)
|
||||
6. `room-map.json` (leere Version 5 — Onboarding füllt sie)
|
||||
7. `SOUL.md` (Standard, ohne „Bestätigung vor Bearbeitung")
|
||||
8. systemd user service (Autostart via `enable`)
|
||||
9. Verifikation aller Pitfalls
|
||||
|
||||
### 10.2 Update-Modus
|
||||
|
||||
`install.sh --update-only` führt nur `git pull` + Kopieren der Plugin-Dateien aus — **skip secrets** und **--no-restart** werden automatisch gesetzt. Ideal für Hotfixes.
|
||||
|
||||
### 10.3 Pflicht-Environment-Variablen (Secrets)
|
||||
|
||||
| Variable | Zweck |
|
||||
|-------------------------|-----------------------------------------------|
|
||||
| `OLLAMA_CLOUD_API_KEY` | API-Key für ollama-cloud |
|
||||
| `ROCKETCHAT_PASSWORD` | Passwort des Bot-Accounts |
|
||||
| `ROCKETCHAT_USER_ID` | User-ID des Bots auf dem RC-Server |
|
||||
|
||||
### 10.4 Optionale Variablen (mit Defaults)
|
||||
|
||||
| Variable | Default | Bemerkung |
|
||||
|-------------------------------|--------------------------------------|-------------------------------------------------|
|
||||
| `MODEL_NAME` | `nemotron-3-super` | **NICHT** `nemotron-3-super-120b` verwenden |
|
||||
| `MULTIROOM_AGENT` | `true` | Archivar aktiv |
|
||||
| `OLLAMA_KEEP_ALIVE` | `-1` | Modell nie entladen (warm, ~5GB RAM) |
|
||||
| `ROCKETCHAT_BASE_URL` | `https://rocketchat.thomander.de` | **Ohne** `https://`-Prefix! |
|
||||
| `ROCKETCHAT_HOME_CHANNEL` | leer | Onboarding fragt nach |
|
||||
| `ARCHIVAR_RED_FLAG` | `true` | Agent als 6. Entscheidungsträger |
|
||||
| `ARCHIVAR_ROUTING_TELEMETRY` | `true` | Konfidenz-Logging |
|
||||
| `ARCHIVAR_STRATEGY_AUTO_DETECT` | `false` | Feature-Flag für Phase-2 Auto-Detection |
|
||||
|
||||
### 10.5 Moderatorenrechte (KRITISCH)
|
||||
|
||||
**Empfehlung** in `INSTALL.md` und `::hilfe`:
|
||||
|
||||
> Gib dem Bot Moderatorenrechte in allen Themenräumen.
|
||||
|
||||
Ohne Moderatorenrechte:
|
||||
- Kann der Agent die Originalnachricht nach dem Verschieben **nicht löschen** → bleibt im Ursprungsraum sichtbar
|
||||
- In DMs: grundsätzlich keine Moderatorenrechte möglich → Löschen dort nie möglich
|
||||
|
||||
---
|
||||
|
||||
## 11. Sicherheitsfeatures
|
||||
|
||||
### 11.1 Dangerous-Command-Approval
|
||||
|
||||
`::approve` und `::deny` realisieren einen **Two-Step-Flow** für gefährliche Operationen:
|
||||
|
||||
1. Nutzer tippt z.B. `::restart` → Bot antwortet „Bitte bestätigen mit `::approve`"
|
||||
2. Nutzer tippt `::approve [session|always]` → Aktion wird ausgeführt
|
||||
3. `::deny` → Aktion wird abgebrochen
|
||||
|
||||
**Sub-Commands:**
|
||||
- `::approve` (ohne Args) — einmalige Genehmigung
|
||||
- `::approve session` — für die aktuelle Session
|
||||
- `::approve always` — dauerhaft (für wiederkehrende Routinen)
|
||||
|
||||
### 11.2 Halluzination-Schutz bei `::`-Fragen
|
||||
|
||||
Siehe Abschnitt 6.3. `extract_command_question(text)` löst Hilfe **vor** dem LLM aus → keine Halluzination über eigene Befehle.
|
||||
|
||||
### 11.3 Freitext-Schutz im Onboarding
|
||||
|
||||
`_reject_free_text()` in `onboarding_review.py` lehnt Freitext in Sub-Phasen ab. Verhindert, dass Tippfehler oder LLM-Halluzinationen in `room-map.json` landen.
|
||||
|
||||
### 11.4 Button-Dispatch vor Text-Input
|
||||
|
||||
**P0-Invariante** (F6 R15): Der Button-Dispatch (`startswith("REVIEW_ROOM")`) wird im Adapter **vor** dem `pending_text_input`-Block geprüft. Sonst würde der Text-Input-Pfad Buttons schlucken, bevor sie verarbeitet werden.
|
||||
|
||||
**Beweis:** Ersetzt man den Button-Check durch `if False:`, schlagen Tests fehl (MockArchivar._room_map fehlt → AttributeError, dann Assertion-Failure).
|
||||
|
||||
### 11.5 Path-Traversal-Schutz im FAKT-Setup
|
||||
|
||||
`validate_fact_store_path()` in `onboarding.py` blockiert:
|
||||
- Relative Pfade ohne `/` oder `~`
|
||||
- `..`-Traversal
|
||||
- System-Verzeichnisse (`/etc`, `/var`, `/usr`, `/boot`, `/sys`, `/proc`)
|
||||
|
||||
---
|
||||
|
||||
## 12. Konfiguration
|
||||
|
||||
### 12.1 `~/.hermes/config.yaml`
|
||||
|
||||
```yaml
|
||||
provider: ollama-cloud
|
||||
model: nemotron-3-super
|
||||
auxiliary_provider: ollama-cloud
|
||||
```
|
||||
|
||||
### 12.2 `~/.hermes/.env`
|
||||
|
||||
Alle Maschinen-spezifischen Werte (Secrets + Base-URLs). Wird **nicht** zwischen Maschinen kopiert (Identitätskonflikt).
|
||||
|
||||
### 12.3 `~/.hermes/hermes-agent/data/room-map.json`
|
||||
|
||||
Wird durch das Onboarding gefüllt. Vorher leer (Version 5, Onboarding-ready).
|
||||
|
||||
### 12.4 `~/.hermes/SOUL.md`
|
||||
|
||||
Standardmäßige Agent-Persönlichkeit. **Ohne** den Satz „Bestätigung vor Bearbeitung" — das würde mit dem Dangerous-Command-Approval-Flow kollidieren.
|
||||
|
||||
### 12.5 Feature-Flags (`config.py`)
|
||||
|
||||
Alle Schwellen und Schalter sind in `plugin/archivar/config.py` zentralisiert:
|
||||
|
||||
- `FAISS_AUTO_ROUTE` (0.85)
|
||||
- `FAISS_MIN_SCORE` (0.50)
|
||||
- `FAISS_TOP_K` (3)
|
||||
- `FAISS_CONFLICT_DIFF` (0.05)
|
||||
- `RED_FLAG_TIMEOUT` (30.0s)
|
||||
- `SENTENCE_MARKER_LLM_THRESHOLD` (0.7)
|
||||
- `MOVE_REQUEST_TEMPLATE` (Button-Texte)
|
||||
|
||||
---
|
||||
|
||||
## 13. Test-Status
|
||||
|
||||
### 13.1 Aktueller Stand (HEAD `afa462c`)
|
||||
|
||||
- **1180+ passed tests** im gesamten Test-Suite
|
||||
- **6 neue Tests** in `test_d_pending_resolver.py` für Ansatz D (3 RED → GRÜN, weitere Regressionstests)
|
||||
- **Integration-Tests** für Button-Dispatch (`test_f6_adapter_dispatch.py`)
|
||||
- **TDD-Workflow** dokumentiert: 4 Tests zuerst ROT, dann GRÜN
|
||||
|
||||
### 13.2 Wichtige Test-Module
|
||||
|
||||
| Test-Modul | Coverage |
|
||||
|-----------------------------------------------|-----------------------------------------------------------|
|
||||
| `test_d_pending_resolver.py` | Ansatz D: Per-Room-Set, Button-Konsolidierung, kein Zombie |
|
||||
| `test_f6_adapter_dispatch.py` | Button-vor-Text-Input-Reihenfolge |
|
||||
| `test_f8_onboarding_start_fix.py` | `::onboarding start` State-Machine-Integration |
|
||||
| `test_f9_bugfix_round.py` | Inline-Commands, Approve/Deny-Subcommands |
|
||||
| `test_review_room_subphases.py` | Onboarding-Sub-Phasen, Kw100 + KwKontext-Editing |
|
||||
| `test_room_map_write_api.py` | Room-Map Schreib-API |
|
||||
| `test_butler_mode.py` | Butler-Mode-Verhalten (cognitive/strict/off) |
|
||||
| `test_v8_5_dm_routing.py` | DM-Routing-Differenzierung |
|
||||
| `test_p1_button_click_fix.py` | Button-Click-State-Cleanup |
|
||||
|
||||
### 13.3 Pre-Existing Fails (unverändert seit F6 R10)
|
||||
|
||||
Zwei Tests schlagen fehl wegen `gateway`-Import-Problem (Hermes-Core, nicht Plugin-seitig). Bekannt, dokumentiert, nicht in Scope der Archivar-Reviews.
|
||||
|
||||
---
|
||||
|
||||
## 14. Bekannte Smells & Architektur-Hinweise
|
||||
|
||||
Aus den laufenden Archivar-Reviews:
|
||||
|
||||
1. **edit_kind if/else (String-Dispatch)** in `adapter.py` Z.4493-4530 — bei Wachstum (3+ edit_kinds) auf Registry/Tabelle umstellen.
|
||||
2. **Whitespace-Check** `' ' in kw` lässt Tabs/Newlines in Keyword-Mitte durch — `any(c.isspace())` wäre strikter. Kein Blocker, aber **Smell**.
|
||||
3. **Zwei pre-existing Test-Fails** (Gateway-Import) — extern, nicht im Archivar-Scope.
|
||||
4. **state_snapshot** im return-Dict von `handle_review_room_message` ist **toter Code** (wird nicht gelesen).
|
||||
5. **Konfigurations-Duplikation** zwischen `ARCHIVAR_*_ROOM`-Env-Vars (deprecated) und `room-map.json` — Migration noch in Arbeit, beide Pfade funktionieren parallel.
|
||||
|
||||
---
|
||||
|
||||
## 15. Datei-Inventar (Plugin-Archivar)
|
||||
|
||||
| Datei | Zweck |
|
||||
|----------------------------------------|----------------------------------------------------------------------|
|
||||
| `plugin/archivar/config.py` | Konfiguration, Schwellen, Feature-Flags, Prompts |
|
||||
| `plugin/archivar/archivar_state.py` | Persistenz (rooms, keyword_weights, sticky, overrides, never_route) |
|
||||
| `plugin/archivar/room_map.py` | Room-Map laden, validieren, suchen, Schreib-API |
|
||||
| `plugin/archivar/router.py` | Bidirektionaler Router (4-Stufen-Pipeline) |
|
||||
| `plugin/archivar/classifier.py` | Intent-Classifier (Embedding-Vorfilter) |
|
||||
| `plugin/archivar/keyword_matcher.py` | Morphologisches + exaktes Matching |
|
||||
| `plugin/archivar/sentence_markers.py` | Satzeinleitungs-Erkennung (V7-3/4) |
|
||||
| `plugin/archivar/room_index.py` | FAISS-Index-Manager (Phase-1) |
|
||||
| `plugin/archivar/booster.py` | KeywordBooster (FAISS-Score-Verfeinerung) |
|
||||
| `plugin/archivar/onboarding.py` | FAKT-Speicherort, Lock-Mechanismus, Greeting |
|
||||
| `plugin/archivar/onboarding_state.py` | State-Machine für Onboarding |
|
||||
| `plugin/archivar/onboarding_review.py` | Review-Flow (6 Sub-Phasen, Freitext-Schutz) |
|
||||
| `plugin/archivar/inline_commands.py` | `::`-Befehlsregistry, Help-Generator, Halluzination-Schutz |
|
||||
| `plugin/archivar/adapter_integration.py` | Archivar ↔ Adapter-Bridge (Move-Request-Resolution) |
|
||||
| `plugin/archivar/doc_store.py` | FAKT → Obsidian-Vault-Integration |
|
||||
| `plugin/archivar/routing_telemetry.py` | Konfidenz-Logging (Feature-Flag: default AN) |
|
||||
| `plugin/archivar/routing_counter.py` | Routing-Counter (Statistik) |
|
||||
| `plugin/archivar/seed_data.py` | Initiale Room-Map-Defaults |
|
||||
|
||||
---
|
||||
|
||||
## 16. Glossar
|
||||
|
||||
| Begriff | Bedeutung |
|
||||
|-------------------------|---------------------------------------------------------------------------------|
|
||||
| **Archivar** | Thematischer Raum-Router (diese Komponente) |
|
||||
| **Butler** | Genehmigungs-Flow via Action-Button |
|
||||
| **Catch-All** | Ein ausgezeichneter Raum, der alle nicht zuordenbaren Nachrichten aufnimmt |
|
||||
| **DM** | Direct Message (Direktnachricht) |
|
||||
| **100%-Keyword** | Morphologisch gematchtes Schlüsselwort → Auto-Route |
|
||||
| **Kontext-Keyword** | Exakt gematchtes Schlüsselwort → Butler Move-Request |
|
||||
| **Move-Request** | Bestätigungs-Button vor dem Routing |
|
||||
| **Sticky** | Persistenter „Bleibe in diesem Raum"-Marker |
|
||||
| **Zombie-State** | pending-Set-Eintrag, der nach Button-Klick nicht entfernt wurde (jetzt behoben) |
|
||||
| **FAISS** | Facebook AI Similarity Search — Vektor-Index für Embedding-basierte Suche |
|
||||
| **DDP** | Distributed Data Protocol (Meteor/Rocket.Chat WebSocket-Protokoll) |
|
||||
| **systemd-linger** | User-Service ohne Logout-Stop (Auto-Restart nach SIGTERM) |
|
||||
|
||||
---
|
||||
|
||||
## 17. Quellen & Referenzen
|
||||
|
||||
- **Repo:** `~/projekte/Hermes_rocket.chat_Plugin`
|
||||
- **HEAD:** `afa462c468bbc4a3368b8739a9b867356f31aa11` (21.07.2026 19:42 +0200)
|
||||
- **Letzter Commit:** „fix: Per-Room Pending Question Resolver — Zombie-State bei stay_once/confirm_move/generell_hier behoben, pending-Set Konsolidierung bei Raumwechsel"
|
||||
- **Verwandte Docs:** `docs/archivar-architektur.md`, `docs/BUTTON_GUIDE.md`, `docs/deployment-runbook.md`, `docs/architecture/*`
|
||||
- **INSTALL.md:** Voraussetzungen, Env-Variablen, Pitfalls
|
||||
|
||||
---
|
||||
|
||||
*Erstellt von Rainer (Architekt/Reviewer) — 21.07.2026*
|
||||
*Basiert auf Code-Inspektion bei HEAD `afa462c`. Keine Code-Blöcke, nur Architektur-Beschreibung.*
|
||||
+222
-13
@@ -45,6 +45,8 @@ UPDATE_ONLY=false
|
||||
FORCE=false
|
||||
SKIP_SYSTEM_DEPS=false
|
||||
SKIP_OLLAMA_MODELS=false
|
||||
NO_RESTART=false
|
||||
FRESH_ONBOARDING=false
|
||||
|
||||
# Farben (nur wenn Terminal)
|
||||
if [ -t 1 ]; then
|
||||
@@ -184,6 +186,13 @@ find_pipx_venv() {
|
||||
return 0
|
||||
fi
|
||||
fi
|
||||
# Fallback: Eigener venv unter ~/.hermes/hermes-agent/venv/ (kein pipx)
|
||||
# .101 und neuere Installationen nutzen diesen Pfad.
|
||||
hermes_venv="$HOME/.hermes/hermes-agent/venv"
|
||||
if [ -d "$hermes_venv" ] && [ -x "$hermes_venv/bin/python" ]; then
|
||||
echo "$hermes_venv"
|
||||
return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
@@ -366,6 +375,13 @@ deploy_plugin() {
|
||||
local src="$script_dir/plugin"
|
||||
[ -d "$src" ] || die "plugin/-Verzeichnis fehlt in $script_dir"
|
||||
|
||||
# Ziel-Pfad ermitteln: pipx-venv → site-packages, eigener venv → ~/.hermes/hermes-agent/plugins/
|
||||
local dst
|
||||
if [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
|
||||
# Eigener venv (kein pipx): Plugin direkt unter ~/.hermes/hermes-agent/plugins/
|
||||
dst="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
|
||||
else
|
||||
# pipx-venv: Plugin unter site-packages/plugins/platforms/rocketchat/
|
||||
local site_packages
|
||||
if ! $DRY_RUN; then
|
||||
site_packages="$(find_site_packages "$PIPX_VENV")"
|
||||
@@ -373,9 +389,9 @@ deploy_plugin() {
|
||||
else
|
||||
site_packages="<PIPX_VENV>/lib/python3.13/site-packages"
|
||||
fi
|
||||
dst="$site_packages/plugins/platforms/rocketchat"
|
||||
fi
|
||||
|
||||
# P3: korrekter Pfad — plugins/platforms/rocketchat/
|
||||
local dst="$site_packages/plugins/platforms/rocketchat"
|
||||
log "Plugin-Ziel (P3): $dst"
|
||||
if ! $DRY_RUN; then
|
||||
mkdir -p "$dst"
|
||||
@@ -389,13 +405,15 @@ deploy_plugin() {
|
||||
done < <(find "$src" -name "*.py" -type f ! -path '*/__pycache__/*')
|
||||
ok "Syntax-Check bestanden"
|
||||
|
||||
# Rekursives Kopieren, __pycache__/*.pyc ausschließen
|
||||
# Rekursives Kopieren, __pycache__/*.pyc + Stray ~/ ausschließen
|
||||
# Erkenntnis 3: Stray-Verzeichnis ~/ im Dev-Repo ausschließen
|
||||
# Erkenntnis 4: find+cp statt tar (zuverlässigere Excludes)
|
||||
while read -r f; do
|
||||
rel="${f#$src/}"
|
||||
target="$dst/$rel"
|
||||
mkdir -p "$(dirname "$target")"
|
||||
cp "$f" "$target"
|
||||
done < <(find "$src" -type f ! -path '*/__pycache__/*' ! -name '*.pyc')
|
||||
done < <(find "$src" -type f ! -path '*/__pycache__/*' ! -name '*.pyc' ! -path '*/~/*')
|
||||
|
||||
# pycache aufräumen
|
||||
find "$dst" -name '__pycache__' -type d -exec rm -rf {} + 2>/dev/null || true
|
||||
@@ -407,7 +425,7 @@ deploy_plugin() {
|
||||
count=$(find "$dst" -type f ! -path '*/__pycache__/*' | wc -l)
|
||||
ok "$count Plugin-Dateien deployed"
|
||||
else
|
||||
printf '%s[dry]%s cp -r %s/* -> %s/\n' "$C_YELLOW" "$C_RESET" "$src" "$dst"
|
||||
printf '%s[dry]%s cp -r %s/* -> %s/\\n' "$C_YELLOW" "$C_RESET" "$src" "$dst"
|
||||
fi
|
||||
|
||||
# Archivar-Symlink: archivar muss als top-level Modul importierbar sein.
|
||||
@@ -839,9 +857,14 @@ verify_installation() {
|
||||
fi
|
||||
|
||||
# Plugin-Dateien
|
||||
local plugin_dir
|
||||
if [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
|
||||
plugin_dir="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
|
||||
else
|
||||
local sp
|
||||
sp="$(find_site_packages "$PIPX_VENV")"
|
||||
local plugin_dir="$sp/plugins/platforms/rocketchat"
|
||||
plugin_dir="$sp/plugins/platforms/rocketchat"
|
||||
fi
|
||||
if [ -f "$plugin_dir/__init__.py" ] && [ -f "$plugin_dir/adapter.py" ]; then
|
||||
ok "Plugin-Dateien vorhanden: $plugin_dir (P3)"
|
||||
else
|
||||
@@ -909,6 +932,48 @@ verify_installation() {
|
||||
err "FAIL: room-map.json fehlt"; fail=1
|
||||
fi
|
||||
|
||||
# Erkenntnis 5: Post-Deployment-Verifikation — Gateway-Log auf "No adapter" prüfen
|
||||
# gateway_state.json kann veralteten "connected" Status zeigen.
|
||||
# journalctl ist die zuverlässige Quelle.
|
||||
if command -v journalctl >/dev/null 2>&1; then
|
||||
local no_adapter
|
||||
no_adapter="$(journalctl --user -u hermes-gateway --since '2 minutes ago' 2>/dev/null | grep -c 'No adapter' || echo "0")"
|
||||
if [ "${no_adapter:-0}" -gt 0 ]; then
|
||||
err "FAIL: Gateway-Log zeigt 'No adapter' — Plugin nicht geladen (Erkenntnis 5)"
|
||||
fail=1
|
||||
else
|
||||
ok "Gateway-Log: kein 'No adapter' (Erkenntnis 5)"
|
||||
fi
|
||||
else
|
||||
warn "journalctl nicht verfügbar — 'No adapter'-Check übersprungen"
|
||||
fi
|
||||
|
||||
# Erkenntnis 7: register()-Test — prüft ob das Plugin tatsächlich geladen werden kann
|
||||
if [ -f "$plugin_dir/__init__.py" ]; then
|
||||
log "register()-Test (Erkenntnis 7)..."
|
||||
if "$VENV_PY" -c "
|
||||
import sys, os
|
||||
os.chdir(os.path.expanduser('$HOME/.hermes/hermes-agent'))
|
||||
sys.path.insert(0, '.')
|
||||
import importlib.util
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
'hermes_plugins.rocketchat_platform',
|
||||
'$plugin_dir/__init__.py'
|
||||
)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
class MockCtx:
|
||||
def register_platform(self, **kw): print(f'OK: {kw.get(\"name\")}')
|
||||
def register_tool(self, *a, **kw): pass
|
||||
mod.register(MockCtx())
|
||||
" 2>/dev/null; then
|
||||
ok "register()-Test bestanden (Erkenntnis 7)"
|
||||
else
|
||||
err "FAIL: register()-Test fehlgeschlagen — Plugin kann nicht geladen werden (Erkenntnis 7)"
|
||||
fail=1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ $fail -eq 0 ]; then
|
||||
banner "Installation erfolgreich"
|
||||
echo "Alle 9 Punkte und 11 Pitfalls abgedeckt."
|
||||
@@ -953,7 +1018,9 @@ 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.)
|
||||
--fresh-onboarding room-map.json + archivar_state.json löschen (frisches Onboarding)
|
||||
--skip-system-deps apt-Install überspringen (für Container/CI)
|
||||
--skip-ollama-models ollama pull überspringen
|
||||
|
||||
@@ -1002,6 +1069,8 @@ 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 ;;
|
||||
--fresh-onboarding) FRESH_ONBOARDING=true; shift ;;
|
||||
--*) err "Unbekannte Option: $1"; print_help; exit 1 ;;
|
||||
*) err "Unbekanntes Argument: $1"; exit 1 ;;
|
||||
esac
|
||||
@@ -1039,7 +1108,7 @@ check_gitea_ssh_key() {
|
||||
if ! $DRY_RUN; then
|
||||
if ssh -i "$key" -p "${GITEA_PORT}" -o StrictHostKeyChecking=yes \
|
||||
-o BatchMode=yes -o ConnectTimeout=10 \
|
||||
"git@${GITEA_HOST}" 2>&1 | grep -q 'Welcome'; then
|
||||
"git@${GITEA_HOST}" 2>&1 | grep -qiE 'Welcome|successfully authenticated|Hi there'; then
|
||||
ok "Gitea SSH-Verbindung OK (P11)"
|
||||
else
|
||||
err "FAIL: Gitea SSH-Verbindungstest fehlgeschlagen (P11)"
|
||||
@@ -1076,8 +1145,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,22 +1234,155 @@ 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)"
|
||||
# V8.6: Update-Only — Plugin-Code aktualisieren (git pull) + deployen
|
||||
# + __pycache__-Cleanup + Service-Restart + Post-Deploy-Verifikation.
|
||||
# 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)" \
|
||||
|| die "pipx-venv nicht gefunden — vorher Normal-Install ausführen"
|
||||
VENV_PY="$PIPX_VENV/bin/python"
|
||||
|
||||
# Ziel-Pfad ermitteln
|
||||
if [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
|
||||
_update_dst="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
|
||||
else
|
||||
_update_site_packages="$(find_site_packages "$PIPX_VENV")"
|
||||
[ -n "$_update_site_packages" ] || die "site-packages-Pfad konnte nicht ermittelt werden"
|
||||
_update_dst="$_update_site_packages/plugins/platforms/rocketchat"
|
||||
fi
|
||||
|
||||
# ── Schritt 1: __pycache__ VOR dem Kopieren löschen ──
|
||||
log "Lösche __pycache__ im Ziel VOR Deployment..."
|
||||
if ! $DRY_RUN; then
|
||||
find "$_update_dst" -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
|
||||
find "$_update_dst" -name '*.pyc' -delete 2>/dev/null || true
|
||||
ok "__pycache__ vor Deployment gelöscht"
|
||||
else
|
||||
printf '%s[dry]%s find %s -type d -name __pycache__ -exec rm -rf {} +\n' "$C_YELLOW" "$C_RESET" "$_update_dst"
|
||||
fi
|
||||
|
||||
# ── Schritt 2: Plugin deployen ──
|
||||
deploy_plugin
|
||||
|
||||
# ── Schritt 3: __pycache__ NACH dem Kopieren NOCHMAL löschen ──
|
||||
log "Lösche __pycache__ im Ziel NACH Deployment..."
|
||||
if ! $DRY_RUN; then
|
||||
find "$_update_dst" -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
|
||||
find "$_update_dst" -name '*.pyc' -delete 2>/dev/null || true
|
||||
ok "__pycache__ nach Deployment gelöscht"
|
||||
else
|
||||
printf '%s[dry]%s find %s -type d -name __pycache__ -exec rm -rf {} +\n' "$C_YELLOW" "$C_RESET" "$_update_dst"
|
||||
fi
|
||||
|
||||
# ── Schritt 4: Gateway-Dienst neu starten ──
|
||||
if ! $DRY_RUN; 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
|
||||
|
||||
if $NO_RESTART; then
|
||||
ok "Gateway-Neustart übersprungen (--no-restart)"
|
||||
else
|
||||
log "Starte Gateway neu..."
|
||||
systemctl --user restart hermes-gateway 2>/dev/null || true
|
||||
ok "Gateway neugestartet"
|
||||
|
||||
# Warte bis active (max 30s)
|
||||
_update_wait=0
|
||||
while ! systemctl --user is-active hermes-gateway >/dev/null 2>&1 && [ $_update_wait -lt 30 ]; do
|
||||
sleep 1
|
||||
_update_wait=$((_update_wait + 1))
|
||||
done
|
||||
if systemctl --user is-active hermes-gateway >/dev/null 2>&1; then
|
||||
ok "Gateway neugestartet und aktiv (nach ${_update_wait}s)"
|
||||
else
|
||||
err "Gateway nach 30s nicht aktiv — prüfe: journalctl --user -u hermes-gateway -n 20"
|
||||
fi
|
||||
fi
|
||||
else
|
||||
printf '%s[dry]%s systemctl --user restart hermes-gateway\n' "$C_YELLOW" "$C_RESET"
|
||||
fi
|
||||
|
||||
# ── Schritt 5: Post-Deployment-Verifikation ──
|
||||
if ! $DRY_RUN && ! $NO_RESTART; then
|
||||
banner "Post-Deployment-Verifikation"
|
||||
_update_verify_fail=0
|
||||
|
||||
if command -v journalctl >/dev/null 2>&1; then
|
||||
# Präziser Zeitstempel für journalctl --since (statt relativem Zeitfenster)
|
||||
_verify_since="$(date '+%Y-%m-%d %H:%M:%S')"
|
||||
# Warte 12s: Gateway braucht ~5-7s für PresenceEngine, ~8-10s für Archivar/Connected
|
||||
sleep 12
|
||||
|
||||
# Retry-Schleife: bis zu 3 Versuche im Abstand von 5s
|
||||
for _check_attempt in 1 2 3; do
|
||||
_all_ok=true
|
||||
|
||||
# Prüfe auf PresenceEngine/presence
|
||||
_update_presence_hits="$(journalctl --user -u hermes-gateway --since "$_verify_since" --no-pager 2>/dev/null | grep -c -i 'PresenceEngine\|presence' || true)"
|
||||
if [ "${_update_presence_hits:-0}" -gt 0 ]; then
|
||||
ok "PresenceEngine im Log gefunden ($_update_presence_hits Treffer)"
|
||||
else
|
||||
err "FAIL: PresenceEngine NICHT im Gateway-Log (Versuch $_check_attempt/3) — Plugin-Code wurde möglicherweise nicht geladen (stale __pycache__?)"
|
||||
_all_ok=false
|
||||
fi
|
||||
|
||||
# Prüfe auf 'Archivar initialisiert'
|
||||
_update_archivar_hits="$(journalctl --user -u hermes-gateway --since "$_verify_since" --no-pager 2>/dev/null | grep -c 'Archivar initialisiert' || true)"
|
||||
if [ "${_update_archivar_hits:-0}" -gt 0 ]; then
|
||||
ok "'Archivar initialisiert' im Log gefunden ($_update_archivar_hits Treffer)"
|
||||
else
|
||||
err "FAIL: 'Archivar initialisiert' NICHT im Gateway-Log (Versuch $_check_attempt/3)"
|
||||
_all_ok=false
|
||||
fi
|
||||
|
||||
# Prüfe auf 'Connected to'
|
||||
_update_connected_hits="$(journalctl --user -u hermes-gateway --since "$_verify_since" --no-pager 2>/dev/null | grep -c 'Connected to' || true)"
|
||||
if [ "${_update_connected_hits:-0}" -gt 0 ]; then
|
||||
ok "'Connected to' im Log gefunden ($_update_connected_hits Treffer)"
|
||||
else
|
||||
err "FAIL: 'Connected to' NICHT im Gateway-Log (Versuch $_check_attempt/3) — Gateway hat keine Verbindung"
|
||||
_all_ok=false
|
||||
fi
|
||||
|
||||
if $_all_ok; then
|
||||
ok "Post-Deployment-Verifikation: ALLE CHECKS BESTANDEN (Versuch $_check_attempt/3)"
|
||||
break
|
||||
fi
|
||||
|
||||
if [ "$_check_attempt" -lt 3 ]; then
|
||||
warn "Warte 5s vor nächstem Verifikations-Versuch..."
|
||||
sleep 5
|
||||
else
|
||||
_update_verify_fail=1
|
||||
fi
|
||||
done
|
||||
else
|
||||
warn "journalctl nicht verfügbar — Post-Deployment-Verifikation übersprungen"
|
||||
fi
|
||||
|
||||
if [ $_update_verify_fail -ne 0 ]; then
|
||||
die "Post-Deployment-Verifikation FEHLGESCHLAGEN — siehe Fehler oben. Prüfe: journalctl --user -u hermes-gateway -n 50"
|
||||
fi
|
||||
elif $DRY_RUN; then
|
||||
printf '%s[dry]%s Post-Deployment-Verifikation (journalctl Checks)\n' "$C_YELLOW" "$C_RESET"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
fi
|
||||
|
||||
@@ -1223,6 +1425,13 @@ write_config_yaml
|
||||
write_env_file
|
||||
|
||||
# 6. room-map.json (leer)
|
||||
# Erkenntnis 6: --fresh-onboarding löscht room-map.json + archivar_state.json
|
||||
if $FRESH_ONBOARDING && ! $DRY_RUN; then
|
||||
banner "Fresh Onboarding (Erkenntnis 6)"
|
||||
local data_dir="$HOME/.hermes/hermes-agent/data"
|
||||
rm -f "$data_dir/room-map.json" "$data_dir/archivar_state.json" 2>/dev/null || true
|
||||
ok "room-map.json + archivar_state.json gelöscht — frisches Onboarding"
|
||||
fi
|
||||
write_room_map
|
||||
|
||||
# 7. SOUL.md
|
||||
|
||||
+774
-201
File diff suppressed because it is too large
Load Diff
@@ -133,6 +133,7 @@ class ArchivarMessageHandler:
|
||||
"""
|
||||
self._send_callback = send_callback
|
||||
self._button_send_callback = button_send_callback
|
||||
self._presence_engine = None # P2-2: via set_presence_engine() gesetzt
|
||||
self._enable_llm = LLM_CONFIG["enabled"]
|
||||
|
||||
# Create LLM client if enabled and not provided
|
||||
@@ -549,6 +550,8 @@ class ArchivarMessageHandler:
|
||||
|
||||
Button-Garantie: REST-Pfad first, Text-Fallback nur bei Fehler.
|
||||
|
||||
P2-2: Setzt PresenceEngine auf away (gelb) während der Klärung läuft.
|
||||
|
||||
Args:
|
||||
room_id: Zielraum-ID
|
||||
text: Originalnachricht
|
||||
@@ -557,6 +560,11 @@ class ArchivarMessageHandler:
|
||||
Returns:
|
||||
True wenn erfolgreich gesendet, False bei Fehler
|
||||
"""
|
||||
# P2-2: PresenceEngine — Klärung pending → away (gelb)
|
||||
_pe = getattr(self, '_presence_engine', None)
|
||||
if _pe is not None:
|
||||
_pe.set_clarification_pending(room_id)
|
||||
_pe.update_presence()
|
||||
try:
|
||||
# Hole Button-Template
|
||||
template = BUTTON_TEMPLATES.get("clarify_intent", {})
|
||||
@@ -608,6 +616,11 @@ class ArchivarMessageHandler:
|
||||
self._stats["errors"] += 1
|
||||
self._stats["last_error"] = str(e)
|
||||
return False
|
||||
finally:
|
||||
# P2-2: Cleanup — Klärung abgeschlossen (egal ob Erfolg/Fehler)
|
||||
if _pe is not None:
|
||||
_pe.clear_clarification_pending(room_id)
|
||||
_pe.update_presence()
|
||||
|
||||
async def _send_move_request(self, room_id: str, text: str, decision: RoutingDecision) -> bool:
|
||||
"""Sende einen Move-Request-Button (Butler-Prinzip).
|
||||
@@ -1164,6 +1177,14 @@ class ArchivarMessageHandler:
|
||||
self._button_send_callback = callback
|
||||
logger.debug("Button send callback registered")
|
||||
|
||||
def set_presence_engine(self, engine) -> None:
|
||||
"""P2-2: Setze PresenceEngine-Referenz für Klärungsflow-Status.
|
||||
|
||||
Args:
|
||||
engine: PresenceEngine-Instanz oder None.
|
||||
"""
|
||||
self._presence_engine = engine
|
||||
|
||||
def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None:
|
||||
"""Set the bot's current subscribed room IDs for routing validation.
|
||||
|
||||
@@ -1223,14 +1244,23 @@ class ArchivarMessageHandler:
|
||||
strategie_topics = {"absprache", "planung", "strategie", "entscheidung"}
|
||||
return topic.lower().strip() in strategie_topics
|
||||
|
||||
def _get_nachklaerung_buttons(self) -> dict:
|
||||
def _get_nachklaerung_buttons(self, keywords: Optional[list] = None) -> dict:
|
||||
"""Gibt die Nachklärungs-Buttons für A2 zurück.
|
||||
|
||||
Args:
|
||||
keywords: Optionale Liste von Keywords des Zielraums,
|
||||
die als lesbarer Text in die Nachricht eingebaut werden.
|
||||
|
||||
Returns:
|
||||
Button-Template mit Strategie-Optionen.
|
||||
"""
|
||||
text = "Ist es eines dieser Themen?"
|
||||
if keywords:
|
||||
kw_list = ", ".join(keywords)
|
||||
text = f"Ist es eines dieser Themen?\nKeywords: {kw_list}"
|
||||
|
||||
return {
|
||||
"text": "Ist es eines dieser Themen?",
|
||||
"text": text,
|
||||
"actions": [
|
||||
{"text": "🤝 Absprache", "type": "absprache"},
|
||||
{"text": "📋 Planung", "type": "planung"},
|
||||
|
||||
@@ -211,12 +211,19 @@ class InlineCommandRegistry:
|
||||
# ── Help-Text-Generator ─────────────────────────────────────────────────
|
||||
|
||||
|
||||
def build_help_text(registry: InlineCommandRegistry, room_map_summary: str = "") -> str:
|
||||
def build_help_text(
|
||||
registry: InlineCommandRegistry,
|
||||
room_map_summary: str = "",
|
||||
presence_enabled: Optional[bool] = None,
|
||||
current_status: str = "online",
|
||||
) -> 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.
|
||||
presence_enabled: Ob die PresenceEngine aktiv ist (None = nicht verfügbar).
|
||||
current_status: Aktueller Presence-Status ('online', 'away', 'busy').
|
||||
|
||||
Returns:
|
||||
Formatierte Hilfeseite als Markdown-String.
|
||||
@@ -290,6 +297,26 @@ def build_help_text(registry: InlineCommandRegistry, room_map_summary: str = "")
|
||||
lines.append("### 📋 Plugin-Status")
|
||||
lines.append("")
|
||||
|
||||
# P1-4: Status-Farben (Flughafen-Prinzip) — nur wenn PresenceEngine aktiv
|
||||
if presence_enabled:
|
||||
status_emoji = {
|
||||
"online": "🟢 online (idle, verfügbar)",
|
||||
"away": "🟡 away (Hintergrund-Task aktiv, Heartbeat pulsiert)",
|
||||
"busy": "🔴 busy (verarbeitet Nachricht)",
|
||||
}
|
||||
lines.append("### 🚦 Status-Farben")
|
||||
lines.append("")
|
||||
lines.append(
|
||||
"Der Bot zeigt seinen Status nach dem **Flughafen-Prinzip** an: "
|
||||
"wie eine Ampel signalisiert er, ob er bereit (grün), beschäftigt "
|
||||
"(rot) oder im Hintergrund aktiv (gelb) ist."
|
||||
)
|
||||
lines.append("")
|
||||
for status, label in status_emoji.items():
|
||||
marker = " ← aktuell" if status == current_status else ""
|
||||
lines.append(f"- {label}{marker}")
|
||||
lines.append("")
|
||||
|
||||
if room_map_summary:
|
||||
lines.append(room_map_summary)
|
||||
else:
|
||||
@@ -298,6 +325,12 @@ def build_help_text(registry: InlineCommandRegistry, room_map_summary: str = "")
|
||||
lines.append("")
|
||||
lines.append("---")
|
||||
lines.append("💡 **Tipp:** `::hilfe` zeigt diese Seite jederzeit an.")
|
||||
lines.append("")
|
||||
lines.append(
|
||||
"**Moderatorenrechte:** Im Multi-Room-Modus verschiebt der Agent "
|
||||
"Nachrichten. Damit das sauber funktioniert, sollte der Bot "
|
||||
"Moderatorenrechte in den Themenräumen haben."
|
||||
)
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
@@ -308,6 +341,9 @@ def build_status_text(
|
||||
butler_mode: str = "unknown",
|
||||
onboarding_active: bool = False,
|
||||
room_map_summary: str = "",
|
||||
presence_enabled: Optional[bool] = None,
|
||||
current_status: str = "online",
|
||||
pulse_active: bool = False,
|
||||
) -> str:
|
||||
"""Baut die Status-Seite mit aktuellen Plugin-Informationen.
|
||||
|
||||
@@ -317,6 +353,9 @@ def build_status_text(
|
||||
butler_mode: Butler-Modus ('cognitive', 'strict', 'off').
|
||||
onboarding_active: Ob Onboarding gerade läuft.
|
||||
room_map_summary: Raum-Map-Übersicht.
|
||||
presence_enabled: Ob die PresenceEngine aktiv ist (None = nicht anzeigen).
|
||||
current_status: Aktueller Presence-Status ('online', 'away', 'busy').
|
||||
pulse_active: Ob der PulseController gerade pulsiert.
|
||||
|
||||
Returns:
|
||||
Formatierte Status-Seite.
|
||||
@@ -336,6 +375,21 @@ def build_status_text(
|
||||
f"- **Onboarding:** {'🔄 Läuft' if onboarding_active else '✅ Abgeschlossen'}",
|
||||
]
|
||||
|
||||
# P1-4: PresenceEngine-Info (nur wenn presence_enabled explizit gesetzt)
|
||||
if presence_enabled is not None:
|
||||
status_labels = {
|
||||
"online": "🟢 online (idle, verfügbar)",
|
||||
"away": "🟡 away (Hintergrund-Task aktiv)",
|
||||
"busy": "🔴 busy (verarbeitet Nachricht)",
|
||||
}
|
||||
pulse_label = "💓 aktiv" if pulse_active else "⏸️ inaktiv"
|
||||
if presence_enabled:
|
||||
lines.append(f"- **PresenceEngine:** ✅ Aktiv")
|
||||
lines.append(f"- **Aktueller Status:** {status_labels.get(current_status, current_status)}")
|
||||
lines.append(f"- **Pulse:** {pulse_label}")
|
||||
else:
|
||||
lines.append(f"- **PresenceEngine:** ❌ Inaktiv")
|
||||
|
||||
if room_map_summary:
|
||||
lines.append("")
|
||||
lines.append(room_map_summary)
|
||||
|
||||
@@ -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):
|
||||
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
|
||||
|
||||
@@ -979,3 +969,178 @@ def dispatch_review_button(
|
||||
return False, "", [] # Adapter erkennt SKIP und leitet weiter
|
||||
|
||||
return False, "", []
|
||||
|
||||
|
||||
# ── Integration: Adapter-Dispatch-Pfad (F6) ──────────────────────────────
|
||||
|
||||
|
||||
def handle_review_room_message(
|
||||
text: str,
|
||||
state: Dict[str, Any],
|
||||
room_map,
|
||||
archivar,
|
||||
_build_custom_buttons,
|
||||
send_callback,
|
||||
) -> Dict[str, Any]:
|
||||
"""Adapter-Dispatch-Pfad für review_room-Phase (F6: extrahiert aus adapter.py).
|
||||
|
||||
Implementiert die P0-Reihenfolge: Button-Dispatch VOR Text-Input.
|
||||
Diese Funktion ist die testbare Extraktion des adapter.py Codes
|
||||
(Zeilen 4491-4677), damit Integration-Tests den echten Dispatch-Pfad
|
||||
abdecken können, ohne den gesamten Adapter mocken zu müssen.
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext (single_line gestrippt).
|
||||
state: Das _onboarding_state-Dict (wird in-place modifiziert).
|
||||
room_map: Die RoomMap-Instanz.
|
||||
archivar: Die ArchivarMessageHandler-Instanz.
|
||||
_build_custom_buttons: Callback zum Bauen von Rocket.Chat-Buttons.
|
||||
send_callback: Async-Callback zum Senden von Nachrichten.
|
||||
|
||||
Returns:
|
||||
Dict mit:
|
||||
- 'action': 'button_dispatched' | 'text_input_processed' |
|
||||
'skip_to_step2' | 'rejected' | 'noop'
|
||||
- 'handled': bool
|
||||
- 'response_text': str | None
|
||||
- 'response_attachments': list | None
|
||||
- 'state_snapshot': dict (Kopie des State NACH Verarbeitung)
|
||||
"""
|
||||
single_line = text.strip()
|
||||
|
||||
# ── Button-Dispatch (P0: MUSS VOR Text-Input laufen) ──────────
|
||||
# Button-Klicks mit :: Prefix (REVIEW_ROOM_EDIT::rid::edit etc.)
|
||||
# müssen IMMER als Button behandelt werden, auch wenn
|
||||
# pending_text_input=True ist. Sonst wird z.B. der "Zurück"-Button
|
||||
# als Freitext-Keyword interpretiert.
|
||||
if single_line.startswith("REVIEW_ROOM"):
|
||||
handled, response_text, response_attachments = dispatch_review_button(
|
||||
single_line,
|
||||
state,
|
||||
room_map,
|
||||
archivar,
|
||||
_build_custom_buttons,
|
||||
send_callback,
|
||||
)
|
||||
|
||||
if handled:
|
||||
return {
|
||||
"action": "button_dispatched",
|
||||
"handled": True,
|
||||
"response_text": response_text,
|
||||
"response_attachments": response_attachments,
|
||||
"state_snapshot": dict(state),
|
||||
}
|
||||
|
||||
# ── Sub-Phase: Text-Input (pending_text_input=True) ──────────
|
||||
# Nur erreicht, wenn die Nachricht KEIN Button-Klick war.
|
||||
if state.get("pending_text_input"):
|
||||
sub_phase = state.get("sub_phase", "")
|
||||
target_room_id = state.get("target_room_id", "")
|
||||
edit_kind = state.get("edit_kind", "keywords_100")
|
||||
|
||||
if sub_phase == SUB_PHASE_KEYWORDS_EDIT and target_room_id:
|
||||
# Keyword hinzufügen — edit_kind bestimmt die Ziel-Liste
|
||||
if edit_kind == "keywords_context":
|
||||
result = room_map.add_keyword_context(
|
||||
target_room_id, single_line
|
||||
)
|
||||
else:
|
||||
result = room_map.add_keyword_100(
|
||||
target_room_id, single_line
|
||||
)
|
||||
if result:
|
||||
_persist_room_map_changes(archivar, rebuild_faiss=True)
|
||||
response_text = (
|
||||
f"✅ Keyword `{single_line.strip().lower()}` hinzugefügt."
|
||||
)
|
||||
else:
|
||||
response_text = (
|
||||
f"❌ Keyword `{single_line}` ungültig. "
|
||||
"Muss 2-30 Zeichen lang sein, keine Leerzeichen, kein Duplikat."
|
||||
)
|
||||
# Zurück zur keywords_edit Ansicht
|
||||
kw_text, kw_attachments = render_review_room_keywords_edit(
|
||||
room_map, target_room_id,
|
||||
_build_custom_buttons,
|
||||
edit_kind=edit_kind,
|
||||
)
|
||||
return {
|
||||
"action": "text_input_processed",
|
||||
"handled": True,
|
||||
"response_text": response_text,
|
||||
"response_attachments": kw_attachments,
|
||||
"state_snapshot": dict(state),
|
||||
}
|
||||
|
||||
elif sub_phase == SUB_PHASE_THEME_EDIT and target_room_id:
|
||||
# Theme speichern
|
||||
try:
|
||||
room_map.set_theme(target_room_id, single_line)
|
||||
_persist_room_map_changes(archivar, rebuild_faiss=False)
|
||||
response_text = (
|
||||
f"✅ Theme aktualisiert: _{single_line.strip()}_"
|
||||
)
|
||||
except (ValueError, KeyError) as e:
|
||||
response_text = f"❌ {e}"
|
||||
# Zurück zur edit-Ansicht
|
||||
edit_text, edit_attachments = render_review_room_edit(
|
||||
room_map, target_room_id,
|
||||
_build_custom_buttons,
|
||||
)
|
||||
state["sub_phase"] = SUB_PHASE_EDIT
|
||||
state["edit_kind"] = "edit"
|
||||
state["pending_text_input"] = False
|
||||
return {
|
||||
"action": "text_input_processed",
|
||||
"handled": True,
|
||||
"response_text": response_text,
|
||||
"response_attachments": edit_attachments,
|
||||
"state_snapshot": dict(state),
|
||||
}
|
||||
|
||||
elif sub_phase == SUB_PHASE_ADD_NEW:
|
||||
return {
|
||||
"action": "text_input_processed",
|
||||
"handled": True,
|
||||
"response_text": (
|
||||
"📋 Bitte klicke auf einen Raum aus der Liste oder 'Zurück'."
|
||||
),
|
||||
"response_attachments": None,
|
||||
"state_snapshot": dict(state),
|
||||
}
|
||||
|
||||
else:
|
||||
# Unbekannte Sub-Phase mit pending_text_input → reject
|
||||
return {
|
||||
"action": "rejected",
|
||||
"handled": True,
|
||||
"response_text": (
|
||||
"❌ Bitte einen der angezeigten Buttons verwenden. "
|
||||
"Freitext kann in diesem Schritt nicht verarbeitet werden."
|
||||
),
|
||||
"response_attachments": None,
|
||||
"state_snapshot": dict(state),
|
||||
}
|
||||
|
||||
# REVIEW_ROOM_SKIP → handled=False → weiter zu Schritt 2
|
||||
if single_line == REVIEW_ROOM_SKIP or "Überspringen" in single_line:
|
||||
return {
|
||||
"action": "skip_to_step2",
|
||||
"handled": False,
|
||||
"response_text": None,
|
||||
"response_attachments": None,
|
||||
"state_snapshot": dict(state),
|
||||
}
|
||||
|
||||
# ── Freitext-Reject (B2) ────────────────────────────────────
|
||||
return {
|
||||
"action": "rejected",
|
||||
"handled": True,
|
||||
"response_text": (
|
||||
"❌ Bitte einen der angezeigten Buttons verwenden. "
|
||||
"Freitext kann in diesem Schritt nicht verarbeitet werden."
|
||||
),
|
||||
"response_attachments": None,
|
||||
"state_snapshot": dict(state),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,969 @@
|
||||
"""
|
||||
V8.6: PresenceEngine — Rocket.Chat User-Status automatisch setzen.
|
||||
|
||||
Phase 1: Basis-PresenceEngine mit Status-Modell, Coalesce-Timer, Caching.
|
||||
Phase 2: Heartbeat-Pulsieren (Flughafen-Prinzip) für Background-Tasks.
|
||||
|
||||
Zero external dependencies — stdlib only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from typing import Optional, Dict, Callable
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
# Ensure presence_engine logs are visible in journalctl by adding a stderr handler
|
||||
if not logger.handlers:
|
||||
_pe_handler = logging.StreamHandler()
|
||||
_pe_handler.setLevel(logging.INFO)
|
||||
_pe_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
|
||||
logger.addHandler(_pe_handler)
|
||||
logger.propagate = False # Don't double-log to root
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Pure Function: _format_presence_message
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
def _format_presence_message(
|
||||
status: str,
|
||||
room_name: str = "",
|
||||
error: str = "",
|
||||
background_count: int = 0,
|
||||
) -> str:
|
||||
"""Format a presence status message as a pure function.
|
||||
|
||||
Args:
|
||||
status: One of 'online', 'busy', 'away_onboarding', 'away_move_request',
|
||||
'away_error', 'heartbeat'.
|
||||
room_name: Room name for busy/move_request messages.
|
||||
error: Error description for away_error.
|
||||
background_count: Number of background tasks for heartbeat.
|
||||
|
||||
Returns:
|
||||
Formatted message string (empty string for online/idle).
|
||||
"""
|
||||
if status == "online":
|
||||
return ""
|
||||
elif status == "busy":
|
||||
return f"Verarbeitet in {room_name}" if room_name else "Verarbeitet"
|
||||
elif status == "away_onboarding":
|
||||
return "Onboarding läuft"
|
||||
elif status == "away_move_request":
|
||||
return f"Wartet auf Bestätigung in {room_name}" if room_name else "Wartet auf Bestätigung"
|
||||
elif status == "away_clarification":
|
||||
return "Klärung läuft — wartet auf Antwort"
|
||||
elif status == "away_error":
|
||||
return f"⚠️ Fehler: {error}" if error else "⚠️ Fehler"
|
||||
elif status == "heartbeat":
|
||||
return f"wartet — {background_count} Aufträge im Hintergrund"
|
||||
else:
|
||||
return ""
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# PresenceEngine
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class PresenceEngine:
|
||||
"""Manages Rocket.Chat user presence status with coalescing and heartbeat.
|
||||
|
||||
Thread-safe: uses threading.Lock for all counter operations.
|
||||
Coalesce-Timer: prevents flickering by delaying status updates by 2s.
|
||||
Heartbeat: pulses online↔away when background_tasks > 0 and agent is idle.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
rest=None,
|
||||
enabled: bool = True,
|
||||
coalesce_ms: int = 2000,
|
||||
pulse_interval: float = 1.5,
|
||||
gateway_state_path: str = "",
|
||||
_clamp_pulse: bool = True,
|
||||
):
|
||||
"""Initialize the PresenceEngine.
|
||||
|
||||
Args:
|
||||
rest: RocketChatREST instance for API calls.
|
||||
enabled: Whether presence updates are enabled.
|
||||
coalesce_ms: Coalesce delay in milliseconds (default 2000).
|
||||
pulse_interval: PulseController interval in seconds (0.5-30, default 1.5).
|
||||
gateway_state_path: Path to gateway_state.json. Defaults to
|
||||
ROCKETCHAT_GATEWAY_STATE_PATH env var or ~/.hermes/gateway_state.json.
|
||||
_clamp_pulse: If True, clamp pulse_interval to 0.5-30. Set False for testing.
|
||||
"""
|
||||
self._rest = rest
|
||||
self._enabled = enabled
|
||||
|
||||
# Coalesce
|
||||
self._coalesce_ms = coalesce_ms
|
||||
self._coalesce_timer: Optional[threading.Timer] = None
|
||||
self._coalesce_lock = threading.Lock()
|
||||
|
||||
# Pending state
|
||||
self._pending_status: Optional[str] = None
|
||||
self._pending_message: str = ""
|
||||
|
||||
# Caching
|
||||
self._last_sent_status: Optional[str] = None
|
||||
self._last_sent_message: str = ""
|
||||
|
||||
# Active tasks counter (threading.Lock, NOT asyncio.Lock)
|
||||
self._active_tasks: int = 0
|
||||
self._active_tasks_lock = threading.Lock()
|
||||
|
||||
# Sentinels for special states
|
||||
self._onboarding_active: bool = False
|
||||
self._move_request_pending: Dict[str, str] = {} # room_id → room_name
|
||||
self._error_state: Optional[str] = None
|
||||
|
||||
# P2-2: Klärungsflow — Butler wartet auf Antwort (gelb/away)
|
||||
self._clarification_pending: set = set() # Set[str] of room_ids
|
||||
|
||||
# Current room name for busy messages
|
||||
self._current_room_name: str = ""
|
||||
|
||||
# Background tasks counter (for display + PulseController coordination)
|
||||
self._background_tasks: int = 0
|
||||
self._background_tasks_lock = threading.Lock()
|
||||
|
||||
# P0-1: PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s)
|
||||
self._pulse_controller = PulseController(
|
||||
pulse_interval=pulse_interval,
|
||||
_clamp_pulse=_clamp_pulse,
|
||||
)
|
||||
|
||||
# P0-1: DetectionTimer — erkennt Hintergrund-Agenten, steuert PulseController
|
||||
self._detection_timer = DetectionTimer(
|
||||
gateway_state_path=gateway_state_path,
|
||||
detection_interval=10.0,
|
||||
on_change=self._on_detection_change,
|
||||
)
|
||||
|
||||
# Start detection if enabled
|
||||
if self._enabled:
|
||||
self._detection_timer.start()
|
||||
|
||||
# ── Public API ───────────────────────────────────────────────────────
|
||||
|
||||
def is_enabled(self) -> bool:
|
||||
"""Check if presence updates are enabled."""
|
||||
return self._enabled
|
||||
|
||||
def enable(self) -> None:
|
||||
"""Enable presence updates. Starts DetectionTimer."""
|
||||
self._enabled = True
|
||||
self._detection_timer.start()
|
||||
logger.info("[presence] PresenceEngine enabled")
|
||||
|
||||
def disable(self) -> None:
|
||||
"""Disable presence updates. Stops PulseController and DetectionTimer."""
|
||||
self._enabled = False
|
||||
self._pulse_controller.stop()
|
||||
self._detection_timer.stop()
|
||||
logger.info("[presence] PresenceEngine disabled")
|
||||
|
||||
def increment_active_tasks(self) -> int:
|
||||
"""Increment the active tasks counter. Thread-safe.
|
||||
|
||||
Returns:
|
||||
New counter value.
|
||||
"""
|
||||
with self._active_tasks_lock:
|
||||
self._active_tasks += 1
|
||||
return self._active_tasks
|
||||
|
||||
def decrement_active_tasks(self) -> int:
|
||||
"""Decrement the active tasks counter. Thread-safe.
|
||||
|
||||
Returns:
|
||||
New counter value.
|
||||
"""
|
||||
with self._active_tasks_lock:
|
||||
if self._active_tasks > 0:
|
||||
self._active_tasks -= 1
|
||||
count = self._active_tasks
|
||||
# FIX: Resume pulse when all active tasks complete.
|
||||
# on_agent_busy() pauses the pulse, but resume() was never called
|
||||
# in production — the pulse stayed paused forever.
|
||||
if count == 0:
|
||||
self._pulse_controller.resume()
|
||||
logger.info("[presence] active_tasks=0 → pulse resumed")
|
||||
return count
|
||||
|
||||
def set_onboarding_active(self, active: bool) -> None:
|
||||
"""Set the onboarding sentinel."""
|
||||
self._onboarding_active = active
|
||||
|
||||
def set_move_request_pending(self, room_id: str, room_name: str) -> None:
|
||||
"""Set a move request as pending."""
|
||||
self._move_request_pending[room_id] = room_name
|
||||
|
||||
def clear_move_request(self, room_id: str) -> None:
|
||||
"""Clear a move request."""
|
||||
self._move_request_pending.pop(room_id, None)
|
||||
|
||||
def set_clarification_pending(self, room_id: str) -> None:
|
||||
"""P2-2: Markiere Raum als wartend auf Klärungsantwort."""
|
||||
self._clarification_pending.add(room_id)
|
||||
|
||||
def clear_clarification_pending(self, room_id: str) -> None:
|
||||
"""P2-2: Klärung für Raum abgeschlossen."""
|
||||
self._clarification_pending.discard(room_id)
|
||||
|
||||
def set_error_state(self, error: Optional[str]) -> None:
|
||||
"""Set or clear the error state."""
|
||||
self._error_state = error
|
||||
|
||||
def set_current_room(self, room_name: str) -> None:
|
||||
"""Set the current room name for busy messages."""
|
||||
self._current_room_name = room_name
|
||||
|
||||
def increment_background_tasks(self) -> int:
|
||||
"""Increment background tasks counter. Thread-safe.
|
||||
|
||||
Returns:
|
||||
New counter value.
|
||||
"""
|
||||
with self._background_tasks_lock:
|
||||
self._background_tasks += 1
|
||||
count = self._background_tasks
|
||||
self._pulse_controller.set_background_count(count)
|
||||
return count
|
||||
|
||||
def decrement_background_tasks(self) -> int:
|
||||
"""Decrement background tasks counter. Thread-safe.
|
||||
|
||||
Returns:
|
||||
New counter value.
|
||||
"""
|
||||
with self._background_tasks_lock:
|
||||
if self._background_tasks > 0:
|
||||
self._background_tasks -= 1
|
||||
count = self._background_tasks
|
||||
self._pulse_controller.set_background_count(count)
|
||||
if count == 0:
|
||||
self._pulse_controller.stop()
|
||||
return count
|
||||
|
||||
# ── Internal: Presence Setting ───────────────────────────────────────
|
||||
|
||||
def _set_presence(self, status: str, message: str) -> None:
|
||||
"""Schedule a presence update with coalescing.
|
||||
|
||||
The update is delayed by coalesce_ms to prevent flickering.
|
||||
If called again before the timer fires, the timer is reset.
|
||||
|
||||
Args:
|
||||
status: Rocket.Chat status ('online', 'away', 'busy').
|
||||
message: Custom status message.
|
||||
"""
|
||||
if not self._enabled:
|
||||
return
|
||||
|
||||
# EC-5: Cancel pending pulse when higher-priority status fires.
|
||||
# Only cancel for non-online statuses — "online" is the pulse's own
|
||||
# target and cancelling it would prevent the pulse from working.
|
||||
if status != "online":
|
||||
self.cancel_pending()
|
||||
|
||||
with self._coalesce_lock:
|
||||
self._pending_status = status
|
||||
self._pending_message = message
|
||||
|
||||
# Cancel existing timer
|
||||
if self._coalesce_timer is not None:
|
||||
self._coalesce_timer.cancel()
|
||||
self._coalesce_timer = None
|
||||
|
||||
# Start new timer
|
||||
delay = self._coalesce_ms / 1000.0
|
||||
self._coalesce_timer = threading.Timer(delay, self._flush_presence)
|
||||
self._coalesce_timer.daemon = True
|
||||
self._coalesce_timer.start()
|
||||
|
||||
def _flush_presence(self) -> None:
|
||||
"""Flush the pending presence update immediately.
|
||||
|
||||
Skips the REST call if the (status, message) pair is identical
|
||||
to the last sent one (caching).
|
||||
"""
|
||||
with self._coalesce_lock:
|
||||
status = self._pending_status
|
||||
message = self._pending_message
|
||||
self._pending_status = None
|
||||
self._pending_message = ""
|
||||
self._coalesce_timer = None
|
||||
|
||||
if status is None:
|
||||
return
|
||||
|
||||
# Caching: skip if identical to last sent
|
||||
if status == self._last_sent_status and message == self._last_sent_message:
|
||||
return
|
||||
|
||||
if not self._enabled:
|
||||
return
|
||||
|
||||
# Send via REST API
|
||||
self._send_rest(status, message)
|
||||
|
||||
# Update cache
|
||||
self._last_sent_status = status
|
||||
self._last_sent_message = message
|
||||
|
||||
def _send_rest(self, status: str, message: str) -> None:
|
||||
"""Send the presence update via REST API.
|
||||
|
||||
POST /api/v1/users.setStatus with {"status": "...", "message": "..."}
|
||||
Called in a background thread (via Timer), non-blocking.
|
||||
|
||||
Args:
|
||||
status: Rocket.Chat status ('online', 'away', 'busy').
|
||||
message: Custom status message.
|
||||
"""
|
||||
if self._rest is None:
|
||||
return
|
||||
if not self._rest.auth_token:
|
||||
return
|
||||
|
||||
try:
|
||||
data = {"status": status}
|
||||
if message:
|
||||
data["message"] = message
|
||||
|
||||
self._rest._request("POST", "/api/v1/users.setStatus",
|
||||
headers={
|
||||
"X-Auth-Token": self._rest.auth_token,
|
||||
"X-User-Id": self._rest.user_id,
|
||||
},
|
||||
data=data)
|
||||
logger.info(
|
||||
"[presence] Status set: status=%s, message=%s",
|
||||
status, message[:50] if message else "",
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("[presence] Failed to set status: %s", e)
|
||||
|
||||
# ── DetectionTimer Callback ──────────────────────────────────────────
|
||||
|
||||
def _on_detection_change(self, is_active: bool) -> None:
|
||||
"""Callback from DetectionTimer: start/stop PulseController.
|
||||
|
||||
When background agents are detected (is_active=True), start pulsing.
|
||||
When no background agents (is_active=False), stop pulsing.
|
||||
"""
|
||||
if not self._enabled:
|
||||
return
|
||||
if is_active:
|
||||
if not self._pulse_controller.is_running():
|
||||
self._pulse_controller.start()
|
||||
logger.info("[presence] PulseController gestartet (Hintergrund-Agenten erkannt)")
|
||||
else:
|
||||
if self._pulse_controller.is_running():
|
||||
self._pulse_controller.stop()
|
||||
logger.info("[presence] PulseController gestoppt (keine Hintergrund-Agenten)")
|
||||
|
||||
# ── Convenience: Determine and set appropriate presence ──────────────
|
||||
|
||||
def update_presence(self) -> None:
|
||||
"""Determine the appropriate presence state and schedule an update.
|
||||
|
||||
Priority (highest first):
|
||||
1. Error state → away + error message
|
||||
2. Onboarding active → away + onboarding message
|
||||
3. Move request pending → away + move request message
|
||||
4. Active tasks > 0 → busy + room message
|
||||
5. Active tasks == 0 → online
|
||||
"""
|
||||
if not self._enabled:
|
||||
return
|
||||
|
||||
# 1. Error state
|
||||
if self._error_state:
|
||||
msg = _format_presence_message("away_error", error=self._error_state)
|
||||
self._set_presence("away", msg)
|
||||
return
|
||||
|
||||
# 2. Onboarding active
|
||||
if self._onboarding_active:
|
||||
msg = _format_presence_message("away_onboarding")
|
||||
self._set_presence("away", msg)
|
||||
return
|
||||
|
||||
# 3. Move request pending
|
||||
if self._move_request_pending:
|
||||
# Use the first pending room name
|
||||
room_name = next(iter(self._move_request_pending.values()), "")
|
||||
msg = _format_presence_message("away_move_request", room_name=room_name)
|
||||
self._set_presence("away", msg)
|
||||
return
|
||||
|
||||
# 3b. P2-2: Clarification pending (nach Move-Request, vor Active-Tasks)
|
||||
if self._clarification_pending:
|
||||
msg = _format_presence_message("away_clarification")
|
||||
self._set_presence("away", msg)
|
||||
return
|
||||
|
||||
# 4. Active tasks
|
||||
with self._active_tasks_lock:
|
||||
active = self._active_tasks
|
||||
|
||||
if active > 0:
|
||||
msg = _format_presence_message("busy", room_name=self._current_room_name)
|
||||
self._set_presence("busy", msg)
|
||||
else:
|
||||
self._set_presence("online", "")
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Clean shutdown: stop PulseController, DetectionTimer, cancel coalesce timer."""
|
||||
self._pulse_controller.stop()
|
||||
self._detection_timer.stop()
|
||||
with self._coalesce_lock:
|
||||
if self._coalesce_timer is not None:
|
||||
self._coalesce_timer.cancel()
|
||||
self._coalesce_timer = None
|
||||
|
||||
# ── PulseController Integration ──────────────────────────────────────
|
||||
|
||||
def cancel_pending(self) -> None:
|
||||
"""Cancel any pending pulse tick (K2: API auf PresenceEngine).
|
||||
|
||||
Called by _set_presence when a higher-priority status fires
|
||||
while the PulseController is running (EC-5).
|
||||
"""
|
||||
self._pulse_controller.cancel_pending()
|
||||
|
||||
def on_agent_busy(self, room_name: str = "") -> None:
|
||||
"""Hook: Agent is processing a message — pause pulse, set busy.
|
||||
|
||||
Priority 1 (highest): busy (rot) — Nachricht wird verarbeitet.
|
||||
"""
|
||||
self.set_current_room(room_name)
|
||||
self.increment_active_tasks()
|
||||
self.update_presence()
|
||||
# Pause pulse if running
|
||||
self._pulse_controller.pause()
|
||||
|
||||
def on_message_received(self, room_name: str = "") -> None:
|
||||
"""Hook: Message received — same as on_agent_busy.
|
||||
|
||||
Alias for on_agent_busy for semantic clarity.
|
||||
"""
|
||||
self.on_agent_busy(room_name=room_name)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s Intervall)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class PulseController:
|
||||
"""DDP-based pulse timer: toggles online↔away at configurable interval.
|
||||
|
||||
Uses DDP set_status (NOT REST) for the status toggle.
|
||||
REST fallback only for message text (K1: DDP set_status has no message variant).
|
||||
|
||||
Thread-safe: uses threading.Event for start/stop signalling.
|
||||
Coalesce: skips duplicate status calls (if already away and tick wants away).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
pulse_interval: float = 1.5,
|
||||
_clamp_pulse: bool = True,
|
||||
):
|
||||
"""Initialize PulseController.
|
||||
|
||||
Args:
|
||||
pulse_interval: Pulse interval in seconds (default 1.5).
|
||||
_clamp_pulse: If True, clamp to 0.5-30s. Set False for testing.
|
||||
"""
|
||||
if _clamp_pulse:
|
||||
self._pulse_interval: float = max(0.5, min(30.0, float(pulse_interval)))
|
||||
else:
|
||||
self._pulse_interval: float = float(pulse_interval)
|
||||
|
||||
self._ddp: Optional[object] = None
|
||||
self._rest: Optional[object] = None
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
self._running = threading.Event()
|
||||
self._paused = threading.Event()
|
||||
self._phase: bool = False # False=online, True=away
|
||||
self._last_sent_phase: Optional[bool] = None
|
||||
self._background_count: int = 0
|
||||
self._cancel_pending: bool = False # P0-2: skip next tick flag
|
||||
# P1-2 O-2: Async-await bridge
|
||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||
self._await_timeout: float = 2.0
|
||||
|
||||
# ── Public API ───────────────────────────────────────────────────────
|
||||
|
||||
def bind_ddp(self, ddp: object) -> None:
|
||||
"""Bind a DDP client reference for set_status calls.
|
||||
|
||||
Args:
|
||||
ddp: DDPClient instance with set_status(status) method.
|
||||
"""
|
||||
self._ddp = ddp
|
||||
|
||||
def bind_rest(self, rest: object) -> None:
|
||||
"""Bind a REST client reference for fallback status+message calls.
|
||||
|
||||
Args:
|
||||
rest: RocketChatREST instance with _request method.
|
||||
"""
|
||||
self._rest = rest
|
||||
|
||||
def bind_loop(self, loop: asyncio.AbstractEventLoop) -> None:
|
||||
"""P1-2 O-2: Bind the asyncio event loop for async-await bridge.
|
||||
|
||||
When a loop is bound, _pulse_tick delegates to _pulse_tick_async
|
||||
via run_coroutine_threadsafe. Without a loop, the legacy sync
|
||||
path is used (graceful degradation).
|
||||
|
||||
Args:
|
||||
loop: The running asyncio event loop.
|
||||
"""
|
||||
self._loop = loop
|
||||
|
||||
def set_background_count(self, count: int) -> None:
|
||||
"""Set the background task count for heartbeat messages."""
|
||||
self._background_count = count
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the pulse thread."""
|
||||
logger.info(
|
||||
"[pulse] start() called, _running=%s, _ddp=%s, _phase=%s, _paused=%s",
|
||||
self._running.is_set(),
|
||||
self._ddp is not None,
|
||||
self._phase,
|
||||
self._paused.is_set(),
|
||||
)
|
||||
if self._running.is_set():
|
||||
logger.info("[pulse] start() skip: already running")
|
||||
return
|
||||
|
||||
# P1-1: Check DDP availability before starting
|
||||
if self._ddp is None:
|
||||
logger.warning(
|
||||
"[pulse] PulseController.start() called without DDP bound — "
|
||||
"pulses will have no effect until bind_ddp() is called"
|
||||
)
|
||||
|
||||
self._running.set()
|
||||
self._paused.clear()
|
||||
self._phase = False # Start with online
|
||||
self._last_sent_phase = None
|
||||
|
||||
self._thread = threading.Thread(
|
||||
target=self._pulse_loop,
|
||||
daemon=True,
|
||||
name="pulse-controller",
|
||||
)
|
||||
self._thread.start()
|
||||
logger.info(
|
||||
"[pulse] PulseController started (interval=%.1fs, loop-bound=%s, async-path=%s)",
|
||||
self._pulse_interval,
|
||||
self._loop is not None,
|
||||
self._loop is not None and self._loop.is_running(),
|
||||
)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Stop the pulse thread and wait for it to finish."""
|
||||
if not self._running.is_set():
|
||||
return
|
||||
self._running.clear()
|
||||
self._paused.clear()
|
||||
|
||||
if self._thread is not None and self._thread.is_alive():
|
||||
self._thread.join(timeout=self._pulse_interval + 1)
|
||||
|
||||
self._thread = None
|
||||
logger.info("[pulse] PulseController stopped")
|
||||
|
||||
def pause(self) -> None:
|
||||
"""Pause pulsing without stopping the thread (EC-2: reconnect race)."""
|
||||
self._paused.set()
|
||||
logger.debug("[pulse] PulseController paused")
|
||||
|
||||
def resume(self) -> None:
|
||||
"""Resume pulsing after pause (EC-2: reconnect race)."""
|
||||
self._paused.clear()
|
||||
logger.debug("[pulse] PulseController resumed")
|
||||
|
||||
def is_running(self) -> bool:
|
||||
"""Check if the pulse thread is running."""
|
||||
return self._running.is_set()
|
||||
|
||||
def cancel_pending(self) -> None:
|
||||
"""Cancel any pending pulse tick (K2: EC-5).
|
||||
|
||||
Called by PresenceEngine._set_presence when a higher-priority
|
||||
status fires while the PulseController is running.
|
||||
Sets a flag that the next tick will skip.
|
||||
"""
|
||||
self._cancel_pending = True
|
||||
logger.debug("[pulse] cancel_pending: next tick will be skipped")
|
||||
|
||||
# ── Internal: Pulse Loop ─────────────────────────────────────────────
|
||||
|
||||
def _pulse_loop(self) -> None:
|
||||
"""Background thread: pulse between online and away."""
|
||||
logger.info("[pulse] _pulse_loop started, interval=%.1fs", self._pulse_interval)
|
||||
iteration = 0
|
||||
while self._running.is_set():
|
||||
iteration += 1
|
||||
# Check if paused
|
||||
if self._paused.is_set():
|
||||
if iteration == 1 or iteration % 50 == 0:
|
||||
logger.debug(
|
||||
"[pulse] _pulse_loop iteration=%d: PAUSED (waiting for resume)",
|
||||
iteration,
|
||||
)
|
||||
time.sleep(0.1)
|
||||
continue
|
||||
|
||||
logger.debug(
|
||||
"[pulse] _pulse_loop iteration=%d: calling _pulse_tick, phase=%s, ddp=%s",
|
||||
iteration,
|
||||
self._phase,
|
||||
self._ddp is not None,
|
||||
)
|
||||
self._pulse_tick()
|
||||
|
||||
# Sleep for pulse interval, checking running flag periodically
|
||||
for _ in range(int(self._pulse_interval * 10)):
|
||||
if not self._running.is_set():
|
||||
break
|
||||
if self._paused.is_set():
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
def _pulse_tick(self) -> None:
|
||||
"""Execute one pulse tick: toggle phase and send status.
|
||||
|
||||
P1-2 O-2: When an asyncio loop is bound, delegates to
|
||||
_pulse_tick_async via run_coroutine_threadsafe. Otherwise
|
||||
uses the legacy sync path (graceful degradation).
|
||||
"""
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick fired, phase=%s, ddp=%s, paused=%s, cancel_pending=%s, loop=%s",
|
||||
self._phase,
|
||||
self._ddp is not None,
|
||||
self._paused.is_set(),
|
||||
self._cancel_pending,
|
||||
self._loop is not None,
|
||||
)
|
||||
|
||||
# P0-2: Check cancel_pending flag (set by PresenceEngine._set_presence)
|
||||
if self._cancel_pending:
|
||||
self._cancel_pending = False
|
||||
logger.debug("[pulse] _pulse_tick skip: cancel_pending was set")
|
||||
return
|
||||
|
||||
# Toggle phase
|
||||
self._phase = not self._phase
|
||||
|
||||
# Coalesce: skip if same phase as last sent
|
||||
if self._phase == self._last_sent_phase:
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick skip: coalesce (phase=%s == last_sent)",
|
||||
self._phase,
|
||||
)
|
||||
return
|
||||
|
||||
# P1-2 O-2: Delegate to async path if loop is bound and running
|
||||
if self._loop is not None and self._loop.is_running():
|
||||
try:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self._pulse_tick_async(),
|
||||
self._loop,
|
||||
)
|
||||
future.result(timeout=self._pulse_interval)
|
||||
return
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"[pulse] _pulse_tick async path failed: %s — falling back to sync",
|
||||
e,
|
||||
)
|
||||
# Fall through to legacy sync path below
|
||||
|
||||
# ── Legacy sync path (no loop bound, or async path failed) ──────
|
||||
status = "away" if self._phase else "online"
|
||||
logger.debug("[pulse] _pulse_tick sending (sync): status=%s", status)
|
||||
|
||||
# Try DDP first (K1: DDP set_status has no message variant)
|
||||
if self._ddp is not None and getattr(self._ddp, 'connected', False):
|
||||
try:
|
||||
self._ddp.set_status(status)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
|
||||
return
|
||||
except Exception as e:
|
||||
logger.info("[pulse] _pulse_tick DDP set_status failed: %s", e)
|
||||
|
||||
# REST fallback for message text
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
try:
|
||||
msg = ""
|
||||
if self._phase:
|
||||
msg = _format_presence_message("heartbeat", background_count=self._background_count)
|
||||
self._rest._request(
|
||||
"POST", "/api/v1/users.setStatus",
|
||||
headers={
|
||||
"X-Auth-Token": self._rest.auth_token,
|
||||
"X-User-Id": self._rest.user_id,
|
||||
},
|
||||
data={"status": status, "message": msg} if msg else {"status": status},
|
||||
)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
|
||||
except Exception as e:
|
||||
logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e)
|
||||
else:
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick skip: no DDP and no REST available (ddp=%s, rest=%s)",
|
||||
self._ddp is not None,
|
||||
self._rest is not None,
|
||||
)
|
||||
|
||||
async def _pulse_tick_async(self) -> None:
|
||||
"""P1-2 O-2: Async pulse tick using await set_status_async.
|
||||
|
||||
Runs on the asyncio event loop (dispatched via
|
||||
run_coroutine_threadsafe from the pulse thread).
|
||||
Uses DDPClient.set_status_async for true await-semantics
|
||||
with timeout and error handling.
|
||||
"""
|
||||
status = "away" if self._phase else "online"
|
||||
logger.debug("[pulse] _pulse_tick_async sending: status=%s", status)
|
||||
|
||||
# Try DDP with await-semantics
|
||||
if self._ddp is not None and getattr(self._ddp, 'connected', False):
|
||||
try:
|
||||
await self._ddp.set_status_async(status, timeout=self._await_timeout)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
|
||||
return
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"[pulse] _pulse_tick_async DDP set_status_async failed: %s — "
|
||||
"falling back to REST",
|
||||
e,
|
||||
)
|
||||
|
||||
# REST fallback for message text
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
try:
|
||||
msg = ""
|
||||
if self._phase:
|
||||
msg = _format_presence_message("heartbeat", background_count=self._background_count)
|
||||
self._rest._request(
|
||||
"POST", "/api/v1/users.setStatus",
|
||||
headers={
|
||||
"X-Auth-Token": self._rest.auth_token,
|
||||
"X-User-Id": self._rest.user_id,
|
||||
},
|
||||
data={"status": status, "message": msg} if msg else {"status": status},
|
||||
)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
|
||||
except Exception as e:
|
||||
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
|
||||
else:
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick_async skip: no DDP and no REST available",
|
||||
)
|
||||
|
||||
def _increment_telemetry(self) -> None:
|
||||
"""Increment the heartbeat_pulse telemetry counter.
|
||||
|
||||
NOTE: Coupled to archivar.routing_telemetry.routing_telemetry.
|
||||
This is a cross-module dependency that should be refactored
|
||||
to use a shared telemetry interface or event bus.
|
||||
"""
|
||||
try:
|
||||
from archivar.routing_telemetry import routing_telemetry
|
||||
routing_telemetry.heartbeat_pulse += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# DetectionTimer — erkennt Hintergrund-Agenten (10s Intervall)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class DetectionTimer:
|
||||
"""Detects whether background agents are active.
|
||||
|
||||
Checks gateway_state.json for active_agents > 1.
|
||||
Falls back to pgrep for 'hermes chat --profile' processes.
|
||||
|
||||
Calls on_change callback when detection state changes.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
gateway_state_path: str = "",
|
||||
detection_interval: float = 10.0,
|
||||
on_change: Optional[Callable[[bool], None]] = None,
|
||||
):
|
||||
"""Initialize DetectionTimer.
|
||||
|
||||
Args:
|
||||
gateway_state_path: Path to gateway_state.json.
|
||||
detection_interval: Check interval in seconds (default 10).
|
||||
on_change: Callback(is_active) when detection state changes.
|
||||
"""
|
||||
if not gateway_state_path:
|
||||
gateway_state_path = os.environ.get(
|
||||
"ROCKETCHAT_GATEWAY_STATE_PATH",
|
||||
os.path.expanduser("~/.hermes/gateway_state.json"),
|
||||
)
|
||||
self._gateway_state_path = gateway_state_path
|
||||
self._detection_interval = detection_interval
|
||||
self._on_change = on_change
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
self._running = threading.Event()
|
||||
self._last_result: Optional[bool] = False # Start with False to avoid spurious first callback
|
||||
self._check_count: int = 0 # P0-1: tick counter for diagnostic logging
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the detection timer thread."""
|
||||
if self._running.is_set():
|
||||
return
|
||||
self._running.set()
|
||||
self._thread = threading.Thread(
|
||||
target=self._detection_loop,
|
||||
daemon=True,
|
||||
name="detection-timer",
|
||||
)
|
||||
self._thread.start()
|
||||
logger.info("[detection] DetectionTimer started (interval=%.1fs)", self._detection_interval)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Stop the detection timer thread."""
|
||||
if not self._running.is_set():
|
||||
return
|
||||
self._running.clear()
|
||||
|
||||
if self._thread is not None and self._thread.is_alive():
|
||||
self._thread.join(timeout=self._detection_interval + 1)
|
||||
|
||||
self._thread = None
|
||||
logger.info("[detection] DetectionTimer stopped")
|
||||
|
||||
def check(self) -> bool:
|
||||
"""Check if background agents are active.
|
||||
|
||||
pgrep is the PRIMARY signal — always executed, regardless of gateway_state.
|
||||
gateway_state is SECONDARY — read only for diagnostic logging, never for decisions.
|
||||
|
||||
Returns:
|
||||
True if pgrep finds other hermes chat processes (self-excluded),
|
||||
False otherwise.
|
||||
"""
|
||||
self._check_count += 1
|
||||
self._increment_telemetry()
|
||||
|
||||
result = False
|
||||
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
|
||||
|
||||
# ── PRIMARY: pgrep — ALWAYS run ──────────────────────────────────
|
||||
try:
|
||||
own_pid = os.getpid()
|
||||
proc = subprocess.run(
|
||||
["pgrep", "-f", "hermes chat --profile"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
# Parse PIDs and self-exclude
|
||||
raw_lines = [l.strip() for l in proc.stdout.strip().split("\n") if l.strip()]
|
||||
all_pids = [int(l) for l in raw_lines if l.isdigit()]
|
||||
pids = [p for p in all_pids if p != own_pid]
|
||||
pgrep_pids = len(pids)
|
||||
result = pgrep_pids > 0
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
|
||||
logger.debug("[detection] pgrep failed: %s", e)
|
||||
# pgrep_pids stays -1 (error sentinel)
|
||||
|
||||
# ── SECONDARY: gateway_state — diagnostic only ────────────────────
|
||||
gateway_active = 0
|
||||
try:
|
||||
if os.path.exists(self._gateway_state_path):
|
||||
with open(self._gateway_state_path, 'r') as f:
|
||||
state = json.load(f)
|
||||
gateway_active = state.get("active_agents", 0)
|
||||
except (json.JSONDecodeError, IOError, OSError) as e:
|
||||
logger.debug("[detection] gateway_state.json read failed: %s", e)
|
||||
|
||||
# ── Log: both signals, result ─────────────────────────────────────
|
||||
pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error"
|
||||
logger.info(
|
||||
"[detection] check #%d: pgrep=%s, gateway_state=%d, result=%s",
|
||||
self._check_count, pgrep_str, gateway_active,
|
||||
"active" if result else "inactive",
|
||||
)
|
||||
|
||||
# Notify on change (P1-2: callback fires from check() itself)
|
||||
if result != self._last_result and self._on_change is not None:
|
||||
try:
|
||||
logger.info(
|
||||
"[detection] state changed: %s→%s",
|
||||
"active" if self._last_result else "inactive",
|
||||
"active" if result else "inactive",
|
||||
)
|
||||
self._on_change(result)
|
||||
except Exception as e:
|
||||
logger.debug("[detection] on_change callback failed: %s", e)
|
||||
|
||||
self._last_result = result
|
||||
return result
|
||||
|
||||
def _detection_loop(self) -> None:
|
||||
"""Background thread: periodically check for background agents."""
|
||||
tick = 0
|
||||
while self._running.is_set():
|
||||
tick += 1
|
||||
try:
|
||||
logger.info(
|
||||
"[detection] tick #%d (interval=%.1fs)",
|
||||
tick, self._detection_interval,
|
||||
)
|
||||
self.check() # check() now handles logging + callback
|
||||
except Exception as e:
|
||||
logger.debug("[detection] check failed: %s", e)
|
||||
|
||||
# Sleep for detection interval
|
||||
for _ in range(int(self._detection_interval * 10)):
|
||||
if not self._running.is_set():
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
def _increment_telemetry(self) -> None:
|
||||
"""Increment the heartbeat_detection telemetry counter.
|
||||
|
||||
NOTE: Coupled to archivar.routing_telemetry.routing_telemetry.
|
||||
This is a cross-module dependency that should be refactored
|
||||
to use a shared telemetry interface or event bus.
|
||||
"""
|
||||
try:
|
||||
from archivar.routing_telemetry import routing_telemetry
|
||||
routing_telemetry.heartbeat_detection += 1
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,196 @@
|
||||
"""
|
||||
Reply-Quote-Stripper: Entfernt zitierte Parent-Nachrichten aus Reply-Texten.
|
||||
|
||||
P0: Verhindert Fehl-Routing durch Keyword-Matches in zitierten Texten.
|
||||
Zweistufig defensiv:
|
||||
1. Attachments-basiert: Rocket.Chat sendet bei Replies die Parent-Nachricht
|
||||
als attachment mit. Entferne den zitierten Text aus dem Nachrichtentext.
|
||||
2. Text-basiert (Fallback): Regex-Heuristik für Markdown-Blockquotes (> quote)
|
||||
und [quote]-Blöcke.
|
||||
|
||||
Konfliktfrei mit Butler-Prinzip — der Strip verschärft die 100%-Heuristik,
|
||||
ohne sie zu unterlaufen.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Rocket.Chat Reply-Quote Patterns
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
# Rocket.Chat reply link pattern: [ ](https://...?msg=MSGID)
|
||||
# This is the inline reply marker that Rocket.Chat inserts when replying.
|
||||
_RC_REPLY_LINK_RE = re.compile(
|
||||
r'\[\s*\]\s*\(\s*https?://[^)]*\?msg=[^)]+\)\s*',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# Markdown blockquote: lines starting with >
|
||||
# Matches one or more consecutive lines starting with '> '
|
||||
_BLOCKQUOTE_RE = re.compile(
|
||||
r'(?:^|\n)(?:> .*(?:\n|$))+',
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
# [quote]...[/quote] blocks (BBCode-style, used by some RC clients)
|
||||
_QUOTE_BLOCK_RE = re.compile(
|
||||
r'\[quote[^\]]*\].*?\[/quote\]',
|
||||
re.DOTALL | re.IGNORECASE,
|
||||
)
|
||||
|
||||
# [quote="author"]...[/quote] blocks
|
||||
_QUOTE_AUTHOR_BLOCK_RE = re.compile(
|
||||
r'\[quote=["\']?[^\]"\']*["\']?\].*?\[/quote\]',
|
||||
re.DOTALL | re.IGNORECASE,
|
||||
)
|
||||
|
||||
# Rocket.Chat attachment types that indicate a reply quote
|
||||
_REPLY_ATTACHMENT_TYPES = frozenset({
|
||||
'reply',
|
||||
'quote',
|
||||
'message',
|
||||
})
|
||||
|
||||
|
||||
def _extract_quoted_text_from_attachments(attachments: list) -> Optional[str]:
|
||||
"""Extrahiere den zitierten Text aus Reply-Attachments.
|
||||
|
||||
Rocket.Chat sendet bei Replies die Parent-Nachricht als attachment mit.
|
||||
Typische Felder:
|
||||
- attachment_type: 'reply' oder 'quote'
|
||||
- text: der zitierte Nachrichtentext
|
||||
- description: Beschreibung (z.B. Autor der Parent-Nachricht)
|
||||
- author_name: Name des Autors der Parent-Nachricht
|
||||
- message_link: Link zur Parent-Nachricht
|
||||
|
||||
Returns:
|
||||
Der zitierte Text wenn gefunden, sonst None.
|
||||
"""
|
||||
if not attachments or not isinstance(attachments, list):
|
||||
return None
|
||||
|
||||
for attachment in attachments:
|
||||
if not isinstance(attachment, dict):
|
||||
continue
|
||||
|
||||
# Check for reply/quote attachment types
|
||||
att_type = attachment.get('type', '')
|
||||
att_attachment_type = attachment.get('attachment_type', '')
|
||||
|
||||
if att_type in _REPLY_ATTACHMENT_TYPES or att_attachment_type in _REPLY_ATTACHMENT_TYPES:
|
||||
# Try to get the quoted text
|
||||
quoted = attachment.get('text', '') or attachment.get('description', '')
|
||||
if quoted:
|
||||
return quoted.strip()
|
||||
|
||||
# Also check for message_link (Rocket.Chat reply indicator)
|
||||
if attachment.get('message_link'):
|
||||
quoted = attachment.get('text', '') or attachment.get('description', '')
|
||||
if quoted:
|
||||
return quoted.strip()
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _strip_rc_reply_link(text: str) -> str:
|
||||
"""Entferne den Rocket.Chat Reply-Link [ ](url?msg=ID) aus dem Text."""
|
||||
return _RC_REPLY_LINK_RE.sub('', text).strip()
|
||||
|
||||
|
||||
def _strip_blockquotes(text: str) -> str:
|
||||
"""Entferne Markdown-Blockquotes (> quote) aus dem Text."""
|
||||
return _BLOCKQUOTE_RE.sub('', text).strip()
|
||||
|
||||
|
||||
def _strip_quote_blocks(text: str) -> str:
|
||||
"""Entferne [quote]...[/quote] Blöcke aus dem Text."""
|
||||
text = _QUOTE_AUTHOR_BLOCK_RE.sub('', text)
|
||||
text = _QUOTE_BLOCK_RE.sub('', text)
|
||||
return text.strip()
|
||||
|
||||
|
||||
def strip_reply_quote(
|
||||
text: str,
|
||||
attachments: Optional[list] = None,
|
||||
) -> Tuple[str, bool]:
|
||||
"""Entferne Reply-Quote aus einer Nachricht (P0).
|
||||
|
||||
Zweistufig defensiv:
|
||||
1. Attachments-basiert: Wenn die Nachricht Reply-Attachments enthält,
|
||||
wird der zitierte Text aus dem Nachrichtentext entfernt.
|
||||
2. Text-basiert (Fallback): Regex-Heuristik für Blockquote-Pattern.
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext.
|
||||
attachments: Optionale Liste von Attachments aus dem msg_obj.
|
||||
|
||||
Returns:
|
||||
Tuple aus (bereinigtem Text, ob ein Quote gestrippt wurde).
|
||||
"""
|
||||
if not text:
|
||||
return text, False
|
||||
|
||||
stripped = False
|
||||
result = text
|
||||
|
||||
# ── Stufe 1: Attachments-basiert ──────────────────────────────────
|
||||
if attachments:
|
||||
quoted_text = _extract_quoted_text_from_attachments(attachments)
|
||||
if quoted_text and quoted_text in result:
|
||||
result = result.replace(quoted_text, '', 1).strip()
|
||||
stripped = True
|
||||
|
||||
# ── Stufe 1b: RC Reply-Link entfernen ──────────────────────────────
|
||||
# [ ](https://chat.example.com/group/room?msg=MSGID)
|
||||
before_link = result
|
||||
result = _strip_rc_reply_link(result)
|
||||
if result != before_link:
|
||||
stripped = True
|
||||
|
||||
# ── Stufe 2: Text-basiert (Fallback) ───────────────────────────────
|
||||
# Nur wenn Stufe 1 nichts gefunden hat
|
||||
if not stripped:
|
||||
# [quote]...[/quote] Blöcke
|
||||
before_quote = result
|
||||
result = _strip_quote_blocks(result)
|
||||
if result != before_quote:
|
||||
stripped = True
|
||||
|
||||
if not stripped:
|
||||
# Markdown-Blockquotes (> quote)
|
||||
before_bq = result
|
||||
result = _strip_blockquotes(before_bq)
|
||||
if result != before_bq:
|
||||
stripped = True
|
||||
|
||||
# Clean up: collapse multiple blank lines, strip
|
||||
result = re.sub(r'\n{3,}', '\n\n', result)
|
||||
result = result.strip()
|
||||
|
||||
return result, stripped
|
||||
|
||||
|
||||
def strip_reply_quote_for_routing(
|
||||
text: str,
|
||||
attachments: Optional[list] = None,
|
||||
) -> Tuple[str, str, bool]:
|
||||
"""P1: Trenne routing_text und display_text.
|
||||
|
||||
- routing_text: Ohne Quote — für Archivar/Keyword-Matcher/classify_and_route
|
||||
- display_text: Mit Quote — für Agent und Conversation-History
|
||||
|
||||
Args:
|
||||
text: Der originale Nachrichtentext.
|
||||
attachments: Optionale Attachments aus dem msg_obj.
|
||||
|
||||
Returns:
|
||||
Tuple aus (routing_text, display_text, was_stripped).
|
||||
Wenn kein Quote gefunden: routing_text == display_text == text.
|
||||
"""
|
||||
routing_text, was_stripped = strip_reply_quote(text, attachments)
|
||||
display_text = text # Originaltext mit Quote für Agent/History
|
||||
return routing_text, display_text, was_stripped
|
||||
@@ -74,6 +74,9 @@ class RoomEntry:
|
||||
catch_all: bool = False
|
||||
"""True wenn dieser Raum der EINE Catch-All-Raum ist."""
|
||||
|
||||
active_status_indikator: bool = True
|
||||
"""V8.6: Aktivitäts-Indikator — Bot-Status automatisch anzeigen (PresenceEngine)."""
|
||||
|
||||
# V8.2: Keyword-Tracking für Lern-Persistenz und Demotion
|
||||
_keyword_last_matched: Dict[str, str] = field(default_factory=dict)
|
||||
"""Mapping keyword → ISO timestamp des letzten Matches (für Demotion)."""
|
||||
@@ -547,6 +550,7 @@ class RoomMap:
|
||||
"keywords_100": room_entry.keywords_100,
|
||||
"keywords_context": room_entry.keywords_context,
|
||||
"catch_all": room_entry.catch_all,
|
||||
"active_status_indikator": room_entry.active_status_indikator,
|
||||
# V8.2.1 A3: Persistiere Tracking-Felder
|
||||
"_stay_counts": room_entry._stay_counts,
|
||||
"_keyword_last_matched": room_entry._keyword_last_matched,
|
||||
@@ -917,6 +921,7 @@ class RoomMap:
|
||||
keywords_100=keywords_100,
|
||||
keywords_context=keywords_context,
|
||||
catch_all=room_data.get("catch_all", False),
|
||||
active_status_indikator=room_data.get("active_status_indikator", True),
|
||||
)
|
||||
# V8.2.1 A3: Tracking-Felder aus JSON deserialisieren
|
||||
if "_stay_counts" in room_data:
|
||||
|
||||
@@ -49,6 +49,9 @@ class RoutingTelemetry:
|
||||
self._enabled: bool = self._read_feature_flag()
|
||||
self._records: List[Dict[str, object]] = []
|
||||
self._start_time: float = 0.0
|
||||
# Heartbeat-Pulsierung Telemetrie
|
||||
self.heartbeat_pulse: int = 0
|
||||
self.heartbeat_detection: int = 0
|
||||
|
||||
@staticmethod
|
||||
def _read_feature_flag() -> bool:
|
||||
|
||||
@@ -0,0 +1,492 @@
|
||||
"""
|
||||
Ansatz D: Per-Room Pending Question Resolver — 3 RED Tests.
|
||||
|
||||
Rainer's Analyse: _rooms_with_pending_questions ist bereits pro-Room (Set von
|
||||
room_ids). Die Grundlogik ist korrekt. Das Problem sind 3 konkrete Bugs:
|
||||
|
||||
Bug 1: Button-Klicks aus anderen Räumen konsolidieren den pending-Set nicht.
|
||||
Bug 2: stay_once entfernt nicht aus dem pending-Set (Zombie-State).
|
||||
Bug 3: Keine Tests für diese Edge-Cases.
|
||||
|
||||
Diese Tests sind ROT vor der Implementierung und GRUEN danach.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, AsyncMock
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
|
||||
# ── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _make_room_map_json(tmpdir: str) -> str:
|
||||
"""Create a room-map.json with 2 rooms + catch-all."""
|
||||
rooms = {
|
||||
"room_a": {
|
||||
"name": "#Raum-A",
|
||||
"theme": "Raum A",
|
||||
"keywords_100": ["thema-a"],
|
||||
"keywords_context": [],
|
||||
"catch_all": False,
|
||||
},
|
||||
"room_b": {
|
||||
"name": "#Raum-B",
|
||||
"theme": "Raum B",
|
||||
"keywords_100": ["thema-b"],
|
||||
"keywords_context": [],
|
||||
"catch_all": False,
|
||||
},
|
||||
"room_catchall": {
|
||||
"name": "#CatchAll",
|
||||
"theme": "Catch-all room",
|
||||
"keywords_100": [],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
}
|
||||
data = {
|
||||
"version": 5,
|
||||
"rooms": rooms,
|
||||
"excluded_rooms": [],
|
||||
"butler_mode": "cognitive",
|
||||
"fact_store_path": str(Path(tmpdir) / "docs"),
|
||||
}
|
||||
map_path = Path(tmpdir) / "room-map.json"
|
||||
with open(map_path, "w") as f:
|
||||
json.dump(data, f)
|
||||
return str(map_path)
|
||||
|
||||
|
||||
def _build_mock_adapter(room_map_path: str):
|
||||
"""Build a RocketChatAdapter with mocked external dependencies.
|
||||
|
||||
Same pattern as test_v8_4_3.py._build_mock_adapter.
|
||||
"""
|
||||
os.environ["MULTIROOM_AGENT"] = "true"
|
||||
os.environ["ARCHIVAR_ROOM_MAP_PATH"] = room_map_path
|
||||
os.environ["ARCHIVAR_STATE_PATH"] = "/tmp/archivar_test_d_state.json"
|
||||
os.environ["ROCKETCHAT_BASE_URL"] = "https://rocket.example.com"
|
||||
os.environ["ROCKETCHAT_USER"] = "testbot"
|
||||
os.environ["ROCKETCHAT_PASSWORD"] = "testpass"
|
||||
|
||||
# Clean leftover state
|
||||
try:
|
||||
os.remove("/tmp/archivar_test_d_state.json")
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
from plugin.adapter import RocketChatAdapter, RocketChatREST
|
||||
from archivar.conversation_history import ConversationHistory
|
||||
from archivar.multiroom_context import MultiRoomContextRing
|
||||
from archivar.adapter_integration import ArchivarMessageHandler
|
||||
from archivar.room_map import RoomMap
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
|
||||
adapter.config = MagicMock()
|
||||
adapter.config.extra = {}
|
||||
adapter.platform = "rocketchat"
|
||||
adapter.base_url = os.getenv("ROCKETCHAT_BASE_URL", "")
|
||||
adapter.user = os.getenv("ROCKETCHAT_USER", "")
|
||||
adapter.password = os.getenv("ROCKETCHAT_PASSWORD", "")
|
||||
adapter.rest = RocketChatREST(adapter.base_url)
|
||||
adapter.ddp = None
|
||||
adapter._auth_token = None
|
||||
adapter._user_id = None
|
||||
adapter._rooms = []
|
||||
adapter._subscribed_rooms = set()
|
||||
adapter._listen_task = None
|
||||
adapter._status_timer = None
|
||||
adapter._last_activity = 0.0
|
||||
adapter._shutdown_event = threading.Event()
|
||||
adapter._room_info = {}
|
||||
adapter._pending_clarifies = {}
|
||||
adapter._user_rooms = {}
|
||||
adapter._rooms_with_pending_questions = set()
|
||||
adapter._excluded_room_ids = set()
|
||||
adapter._last_server_activity = 0.0
|
||||
adapter._health_check_timer = None
|
||||
adapter._last_ddp_ping_ok = False
|
||||
adapter._running = False
|
||||
|
||||
adapter._conversation_history = ConversationHistory(max_size=10)
|
||||
adapter._multiroom_context = MultiRoomContextRing(max_entries=10)
|
||||
adapter.archivar = ArchivarMessageHandler(
|
||||
send_callback=lambda *a, **kw: None,
|
||||
button_send_callback=lambda *a, **kw: None,
|
||||
conversation_history=adapter._conversation_history,
|
||||
)
|
||||
adapter.archivar._room_map = RoomMap.load(Path(room_map_path))
|
||||
|
||||
adapter._pending_move_requests = {}
|
||||
adapter._session_room_preferences = {}
|
||||
adapter._recent_auto_routes = {}
|
||||
adapter._explicit_switch_sticky = {}
|
||||
adapter._clarify_state = {}
|
||||
adapter._onboarding_state = {}
|
||||
adapter._room_map_summary = ""
|
||||
|
||||
# Mock the REST client
|
||||
mock_rest = MagicMock(spec=RocketChatREST)
|
||||
mock_rest.auth_token = "fake-token"
|
||||
mock_rest.user_id = "fake-user-id"
|
||||
mock_rest.post_message = MagicMock(return_value="msg_12345")
|
||||
mock_rest.get_rooms = MagicMock(return_value=[
|
||||
{"id": "room_a", "name": "Raum-A", "type": "c"},
|
||||
{"id": "room_b", "name": "Raum-B", "type": "c"},
|
||||
{"id": "room_catchall", "name": "CatchAll", "type": "c"},
|
||||
])
|
||||
adapter.rest = mock_rest
|
||||
|
||||
adapter._room_info = {
|
||||
"room_a": {"name": "Raum-A", "type": "c"},
|
||||
"room_b": {"name": "Raum-B", "type": "c"},
|
||||
"room_catchall": {"name": "CatchAll", "type": "c"},
|
||||
}
|
||||
|
||||
adapter._dispatch_agent = AsyncMock()
|
||||
adapter.handle_message = AsyncMock()
|
||||
|
||||
asyncio.run(adapter.archivar.initialize())
|
||||
|
||||
# Mock gateway types
|
||||
import plugin.adapter as _adapter_mod
|
||||
_adapter_mod.MessageType = type('MessageType', (), {
|
||||
'TEXT': 'text', 'BUTTON_CLICK': 'button_click',
|
||||
'COMMAND': 'command',
|
||||
})
|
||||
_adapter_mod.RoutingCounter = type('RoutingCounter', (), {
|
||||
'increment': lambda self, key: None,
|
||||
})
|
||||
_adapter_mod.routing_counter = _adapter_mod.RoutingCounter()
|
||||
|
||||
return adapter
|
||||
|
||||
|
||||
# ── Test 1: Button-Klick aus anderem Raum konsolidiert pending-Set ──────────
|
||||
|
||||
|
||||
class TestD1ButtonClickFromOtherRoomClearsPending(unittest.TestCase):
|
||||
"""Test 1: Button-Klick aus anderem Raum entfernt pending question.
|
||||
|
||||
Szenario:
|
||||
- pending question in Raum A (via _rooms_with_pending_questions)
|
||||
- Move-Request wurde aus Raum A gestellt, Ziel ist Raum B
|
||||
- Andreas klickt Button in Raum B (MOVE_REQ:room_b::confirm_move)
|
||||
- Erwartet: pending question aus Raum A wird aus dem Set entfernt
|
||||
- Aktuell: pending-Set wird nicht konsolidiert → Test ROT
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls._tmpdir = tempfile.TemporaryDirectory()
|
||||
room_map_path = _make_room_map_json(cls._tmpdir.name)
|
||||
cls.adapter = _build_mock_adapter(room_map_path)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls._tmpdir.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
# Clean state before each test
|
||||
self.adapter._rooms_with_pending_questions.clear()
|
||||
self.adapter._pending_move_requests.clear()
|
||||
self.adapter._session_room_preferences.clear()
|
||||
|
||||
def test_button_click_from_other_room_clears_pending(self):
|
||||
"""RED: Button-Klick in Raum B soll pending question aus Raum A entfernen.
|
||||
|
||||
Setup:
|
||||
- Raum A hat pending question (z.B. von einem Move-Request-Button)
|
||||
- _pending_move_requests hat Eintrag für Raum B (Move-Request aus Raum A)
|
||||
- Andreas klickt "1️⃣ Rüber" in Raum B
|
||||
|
||||
Erwartet:
|
||||
- _rooms_with_pending_questions enthält Raum A NICHT mehr
|
||||
"""
|
||||
# ── Setup: pending question in Raum A ──────────────────────────
|
||||
self.adapter._rooms_with_pending_questions.add("room_a")
|
||||
|
||||
# ── Setup: Move-Request in Raum B (kam aus Raum A) ─────────────
|
||||
self.adapter._pending_move_requests["room_b"] = {
|
||||
"text": "Frage zu Thema-A",
|
||||
"origin_room": "room_a", # Ursprungsraum der Frage
|
||||
"target_room": "room_b",
|
||||
"target_name": "Raum-B",
|
||||
"username": "andreas",
|
||||
"message_id": "msg_001",
|
||||
}
|
||||
|
||||
# ── Act: Andreas klickt "1️⃣ Rüber" in Raum B ──────────────────
|
||||
msg_obj = {
|
||||
"_id": "msg_btn_001",
|
||||
"rid": "room_b",
|
||||
"msg": "MOVE_REQ:room_b::confirm_move",
|
||||
"u": {"username": "andreas", "_id": "user_andreas"},
|
||||
}
|
||||
|
||||
asyncio.run(self.adapter._process_incoming(msg_obj))
|
||||
|
||||
# ── Assert: Raum A ist NICHT mehr im pending-Set ───────────────
|
||||
self.assertNotIn(
|
||||
"room_a",
|
||||
self.adapter._rooms_with_pending_questions,
|
||||
"BUG 1: Raum A ist noch im pending-Set — "
|
||||
"Button-Klick in Raum B hat pending question aus Raum A "
|
||||
"nicht konsolidiert. Der pending-Set wächst und blockiert.",
|
||||
)
|
||||
|
||||
|
||||
# ── Test 2: stay_once entfernt aus dem pending-Set ──────────────────────────
|
||||
|
||||
|
||||
class TestD2StayOnceRemovesFromPendingSet(unittest.TestCase):
|
||||
"""Test 2: stay_once (Nur diesmal) entfernt pending question aus dem Set.
|
||||
|
||||
Szenario:
|
||||
- pending question in Raum A
|
||||
- _pending_move_requests hat Eintrag für Raum A
|
||||
- Andreas klickt "3️⃣ Nur diesmal" (stay_once)
|
||||
- Erwartet: pending question wird aus dem Set entfernt
|
||||
- Aktuell: stay_once entfernt nicht aus dem Set → Zombie-State → Test ROT
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls._tmpdir = tempfile.TemporaryDirectory()
|
||||
room_map_path = _make_room_map_json(cls._tmpdir.name)
|
||||
cls.adapter = _build_mock_adapter(room_map_path)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls._tmpdir.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
self.adapter._rooms_with_pending_questions.clear()
|
||||
self.adapter._pending_move_requests.clear()
|
||||
self.adapter._session_room_preferences.clear()
|
||||
|
||||
def test_stay_once_removes_from_pending_set(self):
|
||||
"""RED: stay_once soll pending question aus dem Set entfernen.
|
||||
|
||||
Setup:
|
||||
- Raum A hat pending question
|
||||
- _pending_move_requests hat Eintrag für Raum A
|
||||
- Andreas klickt "3️⃣ Nur diesmal" (stay_once)
|
||||
|
||||
Erwartet:
|
||||
- _rooms_with_pending_questions enthält Raum A NICHT mehr
|
||||
"""
|
||||
# ── Setup: pending question in Raum A ──────────────────────────
|
||||
self.adapter._rooms_with_pending_questions.add("room_a")
|
||||
|
||||
# ── Setup: Move-Request in Raum A ─────────────────────────────
|
||||
self.adapter._pending_move_requests["room_a"] = {
|
||||
"text": "Frage zu Thema-A",
|
||||
"origin_room": "room_a",
|
||||
"target_room": "room_b",
|
||||
"target_name": "Raum-B",
|
||||
"username": "andreas",
|
||||
"message_id": "msg_002",
|
||||
}
|
||||
|
||||
# ── Act: Andreas klickt "3️⃣ Nur diesmal" in Raum A ────────────
|
||||
msg_obj = {
|
||||
"_id": "msg_btn_002",
|
||||
"rid": "room_a",
|
||||
"msg": "MOVE_REQ:room_a::stay_once",
|
||||
"u": {"username": "andreas", "_id": "user_andreas"},
|
||||
}
|
||||
|
||||
asyncio.run(self.adapter._process_incoming(msg_obj))
|
||||
|
||||
# ── Assert: Raum A ist NICHT mehr im pending-Set ───────────────
|
||||
self.assertNotIn(
|
||||
"room_a",
|
||||
self.adapter._rooms_with_pending_questions,
|
||||
"BUG 2: Raum A ist noch im pending-Set nach stay_once — "
|
||||
"Zombie-State! Die pending question blockiert zukünftige "
|
||||
"Nachrichten in diesem Raum.",
|
||||
)
|
||||
|
||||
def test_stay_here_also_removes_from_pending_set(self):
|
||||
"""stay_here (Generell hier) soll pending question ebenfalls entfernen."""
|
||||
self.adapter._rooms_with_pending_questions.add("room_a")
|
||||
|
||||
self.adapter._pending_move_requests["room_a"] = {
|
||||
"text": "Frage zu Thema-A",
|
||||
"origin_room": "room_a",
|
||||
"target_room": "room_b",
|
||||
"target_name": "Raum-B",
|
||||
"username": "andreas",
|
||||
"message_id": "msg_003",
|
||||
}
|
||||
|
||||
msg_obj = {
|
||||
"_id": "msg_btn_003",
|
||||
"rid": "room_a",
|
||||
"msg": "MOVE_REQ:room_a::stay_here",
|
||||
"u": {"username": "andreas", "_id": "user_andreas"},
|
||||
}
|
||||
|
||||
asyncio.run(self.adapter._process_incoming(msg_obj))
|
||||
|
||||
self.assertNotIn(
|
||||
"room_a",
|
||||
self.adapter._rooms_with_pending_questions,
|
||||
"BUG 2b: Raum A ist noch im pending-Set nach stay_here — "
|
||||
"Zombie-State!",
|
||||
)
|
||||
|
||||
def test_confirm_move_also_removes_from_pending_set(self):
|
||||
"""confirm_move (Rüber) soll pending question ebenfalls entfernen."""
|
||||
self.adapter._rooms_with_pending_questions.add("room_a")
|
||||
|
||||
self.adapter._pending_move_requests["room_a"] = {
|
||||
"text": "Frage zu Thema-A",
|
||||
"origin_room": "room_a",
|
||||
"target_room": "room_b",
|
||||
"target_name": "Raum-B",
|
||||
"username": "andreas",
|
||||
"message_id": "msg_004",
|
||||
}
|
||||
|
||||
msg_obj = {
|
||||
"_id": "msg_btn_004",
|
||||
"rid": "room_a",
|
||||
"msg": "MOVE_REQ:room_a::confirm_move",
|
||||
"u": {"username": "andreas", "_id": "user_andreas"},
|
||||
}
|
||||
|
||||
asyncio.run(self.adapter._process_incoming(msg_obj))
|
||||
|
||||
self.assertNotIn(
|
||||
"room_a",
|
||||
self.adapter._rooms_with_pending_questions,
|
||||
"BUG 2c: Raum A ist noch im pending-Set nach confirm_move — "
|
||||
"Zombie-State!",
|
||||
)
|
||||
|
||||
|
||||
# ── Test 3: Pending in Raum A blockiert Raum B nicht ────────────────────────
|
||||
|
||||
|
||||
class TestD3PendingInRoomADoesNotBlockRoomB(unittest.TestCase):
|
||||
"""Test 3: Pending question in Raum A blockiert Raum B NICHT.
|
||||
|
||||
Szenario:
|
||||
- pending question in Raum A
|
||||
- Andreas schreibt in Raum B (keine pending question dort)
|
||||
- Erwartet: Archivar läuft normal in Raum B (classify_and_route wird aufgerufen)
|
||||
- Aktuell: Bei Konsolidierungs-Bug kann der pending-Set fälschlich blockieren
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls._tmpdir = tempfile.TemporaryDirectory()
|
||||
room_map_path = _make_room_map_json(cls._tmpdir.name)
|
||||
cls.adapter = _build_mock_adapter(room_map_path)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls._tmpdir.cleanup()
|
||||
|
||||
def setUp(self):
|
||||
self.adapter._rooms_with_pending_questions.clear()
|
||||
self.adapter._pending_move_requests.clear()
|
||||
self.adapter._session_room_preferences.clear()
|
||||
|
||||
def test_pending_in_room_a_does_not_block_room_b(self):
|
||||
"""RED: Pending in Raum A soll Archivar in Raum B nicht blockieren.
|
||||
|
||||
Setup:
|
||||
- Raum A hat pending question
|
||||
- Raum B hat KEINE pending question
|
||||
- Andreas schreibt normale Nachricht in Raum B
|
||||
|
||||
Erwartet:
|
||||
- classify_and_route wird für Raum B aufgerufen (Archivar läuft normal)
|
||||
"""
|
||||
# ── Setup: pending question NUR in Raum A ──────────────────────
|
||||
self.adapter._rooms_with_pending_questions.add("room_a")
|
||||
|
||||
# ── Track classify_and_route calls ─────────────────────────────
|
||||
call_count = [0]
|
||||
original = self.adapter.archivar.classify_and_route
|
||||
|
||||
async def tracking(text, origin_room_id="", **kwargs):
|
||||
call_count[0] += 1
|
||||
return await original(text, origin_room_id, **kwargs)
|
||||
|
||||
self.adapter.archivar.classify_and_route = tracking
|
||||
|
||||
# ── Act: Andreas schreibt in Raum B ────────────────────────────
|
||||
msg_obj = {
|
||||
"_id": "msg_normal_001",
|
||||
"rid": "room_b",
|
||||
"msg": "Kannst du mir bei Thema-B helfen?",
|
||||
"u": {"username": "andreas", "_id": "user_andreas"},
|
||||
}
|
||||
|
||||
asyncio.run(self.adapter._process_incoming(msg_obj))
|
||||
|
||||
# ── Assert: Archivar wurde für Raum B aufgerufen ───────────────
|
||||
self.assertEqual(
|
||||
call_count[0],
|
||||
1,
|
||||
f"BUG 3: classify_and_route wurde {call_count[0]}× aufgerufen "
|
||||
f"(erwartet: 1). Pending question in Raum A blockiert "
|
||||
f"fälschlich den Archivar in Raum B.",
|
||||
)
|
||||
|
||||
def test_pending_in_room_a_still_bypasses_room_a(self):
|
||||
"""Regression: Pending in Raum A blockiert Archivar in Raum A weiterhin.
|
||||
|
||||
Dies ist das erwartete Verhalten: Wenn Raum A eine pending question hat,
|
||||
soll die nächste Nachricht in Raum A den Archivar bypassen.
|
||||
"""
|
||||
# ── Setup: pending question in Raum A ──────────────────────────
|
||||
self.adapter._rooms_with_pending_questions.add("room_a")
|
||||
|
||||
# ── Track classify_and_route calls ─────────────────────────────
|
||||
call_count = [0]
|
||||
original = self.adapter.archivar.classify_and_route
|
||||
|
||||
async def tracking(text, origin_room_id="", **kwargs):
|
||||
call_count[0] += 1
|
||||
return await original(text, origin_room_id, **kwargs)
|
||||
|
||||
self.adapter.archivar.classify_and_route = tracking
|
||||
|
||||
# ── Act: Andreas schreibt in Raum A ────────────────────────────
|
||||
msg_obj = {
|
||||
"_id": "msg_normal_002",
|
||||
"rid": "room_a",
|
||||
"msg": "Antwort auf die offene Frage",
|
||||
"u": {"username": "andreas", "_id": "user_andreas"},
|
||||
}
|
||||
|
||||
asyncio.run(self.adapter._process_incoming(msg_obj))
|
||||
|
||||
# ── Assert: Archivar wurde für Raum A NICHT aufgerufen ────────
|
||||
self.assertEqual(
|
||||
call_count[0],
|
||||
0,
|
||||
f"Regression: classify_and_route wurde {call_count[0]}× aufgerufen "
|
||||
f"(erwartet: 0). Pending question in Raum A soll Archivar "
|
||||
f"in Raum A weiterhin bypassen.",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -129,3 +129,74 @@ class TestDDPRoomEvents:
|
||||
|
||||
client._handle_ddp_message(event_data)
|
||||
assert len(received_events) == 0
|
||||
|
||||
|
||||
class TestDDPSetStatus:
|
||||
"""Tests für DDPClient.set_status — P0 Fix: UserPresence:setDefaultStatus."""
|
||||
|
||||
def test_set_status_online_sends_correct_json(self):
|
||||
"""set_status('online') sendet UserPresence:setDefaultStatus mit params=['online']."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = True
|
||||
client.sock = MagicMock()
|
||||
|
||||
with patch.object(client, "_send_json") as mock_send:
|
||||
result = client.set_status("online")
|
||||
|
||||
assert result is True
|
||||
mock_send.assert_called_once()
|
||||
call_args = mock_send.call_args[0][0]
|
||||
assert call_args["msg"] == "method"
|
||||
assert call_args["method"] == "UserPresence:setDefaultStatus"
|
||||
assert call_args["params"] == ["online"]
|
||||
assert call_args["id"].startswith("st")
|
||||
|
||||
def test_set_status_away_sends_correct_json(self):
|
||||
"""set_status('away') sendet UserPresence:setDefaultStatus mit params=['away']."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = True
|
||||
client.sock = MagicMock()
|
||||
|
||||
with patch.object(client, "_send_json") as mock_send:
|
||||
result = client.set_status("away")
|
||||
|
||||
assert result is True
|
||||
mock_send.assert_called_once()
|
||||
call_args = mock_send.call_args[0][0]
|
||||
assert call_args["msg"] == "method"
|
||||
assert call_args["method"] == "UserPresence:setDefaultStatus"
|
||||
assert call_args["params"] == ["away"]
|
||||
assert call_args["id"].startswith("st")
|
||||
|
||||
def test_set_status_busy_sends_correct_json(self):
|
||||
"""set_status('busy') sendet UserPresence:setDefaultStatus mit params=['busy']."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = True
|
||||
client.sock = MagicMock()
|
||||
|
||||
with patch.object(client, "_send_json") as mock_send:
|
||||
result = client.set_status("busy")
|
||||
|
||||
assert result is True
|
||||
mock_send.assert_called_once()
|
||||
call_args = mock_send.call_args[0][0]
|
||||
assert call_args["msg"] == "method"
|
||||
assert call_args["method"] == "UserPresence:setDefaultStatus"
|
||||
assert call_args["params"] == ["busy"]
|
||||
assert call_args["id"].startswith("st")
|
||||
|
||||
def test_set_status_disconnected_returns_false(self):
|
||||
"""set_status gibt False zurück wenn nicht connected."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = False
|
||||
|
||||
result = client.set_status("online")
|
||||
assert result is False
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
"""
|
||||
F6 Integration-Test: adapter.py Dispatch-Pfad (Button-Dispatch VOR Text-Input).
|
||||
|
||||
Rainer's Review: Der Fix (Button-Dispatch VOR Text-Input) ist korrekt, aber
|
||||
der Test testet nur room_map-Ebene, nicht den adapter.py Dispatch-Pfad.
|
||||
|
||||
Dieser Test deckt den echten Dispatch-Pfad via handle_review_room_message()
|
||||
ab — die aus adapter.py extrahierte Funktion.
|
||||
|
||||
Tests:
|
||||
1. GREEN: Button-Dispatch bei pending_text_input=True → Keywords unveraendert
|
||||
2. RED (Reihenfolge-Beweis): Bei umgekehrter Reihenfolge wird Button als
|
||||
Keyword interpretiert → Test muss rot werden
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
import sys
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
from plugin.archivar.room_map import RoomMap
|
||||
from plugin.archivar.onboarding_review import (
|
||||
handle_review_room_message,
|
||||
build_review_state,
|
||||
SUB_PHASE_EDIT,
|
||||
SUB_PHASE_KEYWORDS_EDIT,
|
||||
)
|
||||
|
||||
|
||||
# ── Helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _make_map_json(rooms: list[dict] | None = None) -> str:
|
||||
data: dict = {
|
||||
"version": 1,
|
||||
"rooms": {},
|
||||
"excluded_rooms": [],
|
||||
"fact_store_path": "/tmp/test_docs",
|
||||
}
|
||||
for room in (rooms or []):
|
||||
room_data = {
|
||||
"name": room["name"],
|
||||
"theme": room.get("theme", ""),
|
||||
"catch_all": room.get("catch_all", False),
|
||||
}
|
||||
if "keywords_100" in room or "keywords_context" in room:
|
||||
room_data["keywords_100"] = room.get("keywords_100", [])
|
||||
room_data["keywords_context"] = room.get("keywords_context", [])
|
||||
else:
|
||||
room_data["keywords"] = room.get("keywords", [])
|
||||
data["rooms"][room["room_id"]] = room_data
|
||||
return json.dumps(data)
|
||||
|
||||
|
||||
def _load_room_map(rooms: list[dict]) -> RoomMap:
|
||||
json_str = _make_map_json(rooms=rooms)
|
||||
tmp = tempfile.NamedTemporaryFile(
|
||||
mode="w", suffix=".json", delete=False, encoding="utf-8"
|
||||
)
|
||||
tmp.write(json_str)
|
||||
tmp.close()
|
||||
path = Path(tmp.name)
|
||||
try:
|
||||
return RoomMap.load(path)
|
||||
finally:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _mock_build_buttons(labels, prefix="", style="default"):
|
||||
"""Mock fuer _build_custom_buttons."""
|
||||
buttons = []
|
||||
for label in labels:
|
||||
buttons.append({
|
||||
"text": label,
|
||||
"msg": f"{prefix}::{label}" if prefix else label,
|
||||
"style": style,
|
||||
})
|
||||
return buttons
|
||||
|
||||
|
||||
class MockArchivar:
|
||||
"""Minimaler Mock fuer ArchivarMessageHandler."""
|
||||
_room_index = None
|
||||
|
||||
|
||||
# ── F6 Integration-Tests ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestF6AdapterDispatchPath:
|
||||
"""F6: Integration-Test des adapter.py Dispatch-Pfads.
|
||||
|
||||
Testet handle_review_room_message() — die aus adapter.py extrahierte
|
||||
Dispatch-Funktion. Deckt den P0-Fix ab: Button-Dispatch VOR Text-Input.
|
||||
"""
|
||||
|
||||
def test_button_dispatch_before_text_input_preserves_keywords(self):
|
||||
"""F6 GREEN: Button-Dispatch bei pending_text_input=True.
|
||||
|
||||
Setup:
|
||||
- Raum r1 mit keywords_100=['code']
|
||||
- State: sub_phase=SUB_PHASE_KEYWORDS_EDIT, pending_text_input=True
|
||||
- Text: REVIEW_ROOM_EDIT::r1::edit (Zurueck-Button)
|
||||
|
||||
Erwartet:
|
||||
- state['pending_text_input'] = True (vor Dispatch)
|
||||
- state['sub_phase'] = SUB_PHASE_KEYWORDS_EDIT (vor Dispatch)
|
||||
- text = 'REVIEW_ROOM_EDIT::r1::edit'
|
||||
- r1.keywords_100 == ['code'] (unveraendert — Button NICHT als Keyword)
|
||||
- state['sub_phase'] == SUB_PHASE_EDIT (nach Handler)
|
||||
- state['pending_text_input'] == False (nach Handler)
|
||||
- result['action'] == 'button_dispatched'
|
||||
"""
|
||||
# ── Setup ──────────────────────────────────────────────────
|
||||
rm = _load_room_map([
|
||||
{
|
||||
"room_id": "r1",
|
||||
"name": "#Dev",
|
||||
"theme": "Entwicklung",
|
||||
"keywords_100": ["code"],
|
||||
"keywords_context": [],
|
||||
},
|
||||
{
|
||||
"room_id": "r2",
|
||||
"name": "#Ops",
|
||||
"theme": "Betrieb",
|
||||
"keywords_100": ["server"],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
])
|
||||
|
||||
# State: User ist in keywords_edit Sub-Phase, pending_text_input=True
|
||||
state = build_review_state(
|
||||
phase="review_room",
|
||||
operator_room_id="dm123",
|
||||
sub_phase=SUB_PHASE_KEYWORDS_EDIT,
|
||||
target_room_id="r1",
|
||||
edit_kind="keywords_100",
|
||||
pending_text_input=True,
|
||||
)
|
||||
|
||||
archivar = MockArchivar()
|
||||
|
||||
# ── Pre-Assertions (Rainer's Anforderungen) ──────────────────
|
||||
assert state["pending_text_input"] is True, (
|
||||
"Vor Dispatch: pending_text_input muss True sein"
|
||||
)
|
||||
assert state["sub_phase"] == SUB_PHASE_KEYWORDS_EDIT, (
|
||||
"Vor Dispatch: sub_phase muss SUB_PHASE_KEYWORDS_EDIT sein"
|
||||
)
|
||||
|
||||
text = "REVIEW_ROOM_EDIT::r1::edit"
|
||||
assert text == "REVIEW_ROOM_EDIT::r1::edit", (
|
||||
"Text muss REVIEW_ROOM_EDIT::r1::edit sein"
|
||||
)
|
||||
|
||||
# ── Act: Dispatch-Pfad ausfuehren ───────────────────────────
|
||||
result = handle_review_room_message(
|
||||
text=text,
|
||||
state=state,
|
||||
room_map=rm,
|
||||
archivar=archivar,
|
||||
_build_custom_buttons=_mock_build_buttons,
|
||||
send_callback=None,
|
||||
)
|
||||
|
||||
# ── Post-Assertions ─────────────────────────────────────────
|
||||
# Keywords unveraendert — Button wurde NICHT als Keyword hinzugefuegt
|
||||
actual_kw = rm.get_room_by_id("r1").keywords_100
|
||||
assert actual_kw == ["code"], (
|
||||
f"Keywords unveraendert erwartet: ['code'], aber: {actual_kw}"
|
||||
)
|
||||
|
||||
# State nach Handler: zurueck zur Edit-Ansicht
|
||||
assert state["sub_phase"] == SUB_PHASE_EDIT, (
|
||||
f"Nach Handler: sub_phase muss SUB_PHASE_EDIT sein, "
|
||||
f"aber: {state['sub_phase']}"
|
||||
)
|
||||
|
||||
# pending_text_input muss False sein
|
||||
assert state["pending_text_input"] is False, (
|
||||
f"Nach Handler: pending_text_input muss False sein, "
|
||||
f"aber: {state['pending_text_input']}"
|
||||
)
|
||||
|
||||
# Result-Action muss button_dispatched sein
|
||||
assert result["action"] == "button_dispatched", (
|
||||
f"Action muss 'button_dispatched' sein, aber: {result['action']}"
|
||||
)
|
||||
|
||||
assert result["handled"] is True
|
||||
|
||||
def test_reversed_order_would_break_keywords(self):
|
||||
"""F6 RED (Reihenfolge-Beweis): Bei umgekehrter Reihenfolge
|
||||
(Text-Input VOR Button-Dispatch) wird der Button-Payload als
|
||||
Keyword interpretiert.
|
||||
|
||||
Dieser Test SIMULIERT die falsche Reihenfolge: Er ruft NICHT
|
||||
handle_review_room_message() auf, sondern fuehrt direkt den
|
||||
Text-Input-Pfad aus (add_keyword_100). Das beweist, dass bei
|
||||
umgekehrter Reihenfolge der Button-Text faelschlich als Keyword
|
||||
hinzugefuegt wuerde.
|
||||
|
||||
Wenn jemand die Reihenfolge in handle_review_room_message()
|
||||
zurueckdreht (Text-Input VOR Button-Dispatch), wird der
|
||||
obige Test test_button_dispatch_before_text_input_preserves_keywords
|
||||
rot — weil dann der Button-Payload als Keyword interpretiert wird.
|
||||
"""
|
||||
# ── Setup ──────────────────────────────────────────────────
|
||||
rm = _load_room_map([
|
||||
{
|
||||
"room_id": "r1",
|
||||
"name": "#Dev",
|
||||
"theme": "Entwicklung",
|
||||
"keywords_100": ["code"],
|
||||
"keywords_context": [],
|
||||
},
|
||||
{
|
||||
"room_id": "r2",
|
||||
"name": "#Ops",
|
||||
"theme": "Betrieb",
|
||||
"keywords_100": ["server"],
|
||||
"keywords_context": [],
|
||||
"catch_all": True,
|
||||
},
|
||||
])
|
||||
|
||||
# Beweis mit einem kuerzeren Button-Payload:
|
||||
# Bei falscher Reihenfolge wuerde "REVIEW_ROOM_BACK" als Keyword
|
||||
# hinzugefuegt werden, weil add_keyword_100 es akzeptiert
|
||||
# (2-30 Zeichen, lowercase-normalisiert).
|
||||
short_button = "REVIEW_ROOM_BACK"
|
||||
result = rm.add_keyword_100("r1", short_button)
|
||||
# add_keyword_100 normalisiert zu lowercase
|
||||
assert result is True, (
|
||||
f"add_keyword_100 sollte True sein fuer '{short_button}'"
|
||||
)
|
||||
assert "review_room_back" in rm.get_room_by_id("r1").keywords_100, (
|
||||
f"Bei falscher Reihenfolge wuerde '{short_button}' als Keyword "
|
||||
f"hinzugefuegt — das ist der Bug, den P0 fixt."
|
||||
)
|
||||
|
||||
# Cleanup: Keyword wieder entfernen
|
||||
rm.remove_keyword_100("r1", short_button)
|
||||
|
||||
# Der eigentliche Beweis: "REVIEW_ROOM_EDIT::r1::edit" ist 26 Zeichen
|
||||
# (innerhalb 2-30) — add_keyword_100 WUERDE es akzeptieren!
|
||||
# Bei falscher Reihenfolge wuerde der Button-Payload als Keyword
|
||||
# hinzugefuegt werden.
|
||||
long_button = "REVIEW_ROOM_EDIT::r1::edit"
|
||||
result_long = rm.add_keyword_100("r1", long_button)
|
||||
assert result_long is True, (
|
||||
f"add_keyword_100 sollte True sein fuer '{long_button}' "
|
||||
f"(26 Zeichen, innerhalb 2-30 Limit)"
|
||||
)
|
||||
assert "review_room_edit::r1::edit" in rm.get_room_by_id("r1").keywords_100, (
|
||||
f"Bei falscher Reihenfolge wuerde '{long_button}' als Keyword "
|
||||
f"hinzugefuegt — das ist der Bug, den P0 fixt."
|
||||
)
|
||||
|
||||
# Cleanup
|
||||
rm.remove_keyword_100("r1", long_button)
|
||||
|
||||
# Keywords wieder im Originalzustand
|
||||
assert rm.get_room_by_id("r1").keywords_100 == ["code"], (
|
||||
"Keywords sollten nach Cleanup unveraendert sein"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v"])
|
||||
@@ -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]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1092,3 +1092,142 @@ class TestCommandHandlersMocked:
|
||||
assert handler is not None
|
||||
result = await handler("room1", "")
|
||||
assert "hermes update" in result
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1-4: Status-Farben in ::hilfe und ::status
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestHelpTextPresenceColors:
|
||||
"""P1-4: build_help_text zeigt Status-Farben-Sektion wenn presence_enabled."""
|
||||
|
||||
def test_help_text_includes_status_colors_when_presence_enabled(self):
|
||||
"""presence_enabled=True → 'Status-Farben' Sektion erscheint."""
|
||||
from archivar.inline_commands import InlineCommandRegistry, build_help_text
|
||||
|
||||
registry = InlineCommandRegistry()
|
||||
text = build_help_text(registry, presence_enabled=True, current_status="online")
|
||||
|
||||
assert "Status-Farben" in text, (
|
||||
f"Status-Farben Sektion fehlt:\n{text}"
|
||||
)
|
||||
assert "online" in text
|
||||
assert "away" in text
|
||||
assert "busy" in text
|
||||
# Flughafen-Prinzip erklärt
|
||||
assert "flughafen" in text.lower() or "ampel" in text.lower(), (
|
||||
f"Flughafen-Prinzip nicht erklärt:\n{text}"
|
||||
)
|
||||
|
||||
def test_help_text_no_status_colors_when_presence_disabled(self):
|
||||
"""presence_enabled=False → keine Status-Farben Sektion."""
|
||||
from archivar.inline_commands import InlineCommandRegistry, build_help_text
|
||||
|
||||
registry = InlineCommandRegistry()
|
||||
text = build_help_text(registry, presence_enabled=False)
|
||||
|
||||
assert "Status-Farben" not in text, (
|
||||
f"Status-Farben Sektion sollte nicht erscheinen:\n{text}"
|
||||
)
|
||||
|
||||
def test_help_text_no_status_colors_when_presence_none(self):
|
||||
"""presence_enabled=None (default) → keine Status-Farben Sektion."""
|
||||
from archivar.inline_commands import InlineCommandRegistry, build_help_text
|
||||
|
||||
registry = InlineCommandRegistry()
|
||||
text = build_help_text(registry)
|
||||
|
||||
assert "Status-Farben" not in text
|
||||
|
||||
|
||||
class TestStatusTextPresenceInfo:
|
||||
"""P1-4: build_status_text zeigt PresenceEngine-Info wenn presence_enabled."""
|
||||
|
||||
def test_status_text_includes_presence_info_when_enabled(self):
|
||||
"""presence_enabled=True → PresenceEngine + Status + Pulse Zeilen."""
|
||||
from archivar.inline_commands import build_status_text
|
||||
|
||||
text = build_status_text(
|
||||
room_count=3,
|
||||
archivar_active=True,
|
||||
butler_mode="cognitive",
|
||||
presence_enabled=True,
|
||||
current_status="online",
|
||||
pulse_active=True,
|
||||
)
|
||||
|
||||
assert "PresenceEngine" in text, (
|
||||
f"PresenceEngine-Zeile fehlt:\n{text}"
|
||||
)
|
||||
assert "Aktiv" in text # ✅ Aktiv
|
||||
assert "online" in text, (
|
||||
f"Aktueller Status fehlt:\n{text}"
|
||||
)
|
||||
assert "aktiv" in text.lower(), (
|
||||
f"Pulse-Info fehlt:\n{text}"
|
||||
)
|
||||
|
||||
def test_status_text_includes_presence_info_when_disabled(self):
|
||||
"""presence_enabled=False → PresenceEngine ❌ Inaktiv."""
|
||||
from archivar.inline_commands import build_status_text
|
||||
|
||||
text = build_status_text(
|
||||
room_count=0,
|
||||
archivar_active=False,
|
||||
butler_mode="off",
|
||||
presence_enabled=False,
|
||||
current_status="online",
|
||||
pulse_active=False,
|
||||
)
|
||||
|
||||
assert "PresenceEngine" in text
|
||||
assert "Inaktiv" in text
|
||||
|
||||
def test_status_text_no_presence_info_when_default(self):
|
||||
"""presence_enabled=False (default) → keine PresenceEngine-Zeile."""
|
||||
from archivar.inline_commands import build_status_text
|
||||
|
||||
text = build_status_text(
|
||||
room_count=1,
|
||||
archivar_active=True,
|
||||
butler_mode="strict",
|
||||
)
|
||||
|
||||
assert "PresenceEngine" not in text, (
|
||||
f"PresenceEngine sollte nicht erscheinen (default):\n{text}"
|
||||
)
|
||||
|
||||
def test_status_text_shows_away_status(self):
|
||||
"""current_status='away' → 🟡 away im Status-Text."""
|
||||
from archivar.inline_commands import build_status_text
|
||||
|
||||
text = build_status_text(
|
||||
room_count=2,
|
||||
archivar_active=True,
|
||||
butler_mode="cognitive",
|
||||
presence_enabled=True,
|
||||
current_status="away",
|
||||
pulse_active=True,
|
||||
)
|
||||
|
||||
assert "away" in text, (
|
||||
f"away-Status fehlt:\n{text}"
|
||||
)
|
||||
|
||||
def test_status_text_shows_busy_status(self):
|
||||
"""current_status='busy' → 🔴 busy im Status-Text."""
|
||||
from archivar.inline_commands import build_status_text
|
||||
|
||||
text = build_status_text(
|
||||
room_count=2,
|
||||
archivar_active=True,
|
||||
butler_mode="cognitive",
|
||||
presence_enabled=True,
|
||||
current_status="busy",
|
||||
pulse_active=False,
|
||||
)
|
||||
|
||||
assert "busy" in text, (
|
||||
f"busy-Status fehlt:\n{text}"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
"""
|
||||
Tests für Reply-Quote-Stripping (P0 + P1).
|
||||
|
||||
Testet:
|
||||
- Attachments-basiertes Stripping (Stufe 1)
|
||||
- Text-basiertes Stripping (Stufe 2): [quote]-Blöcke, Markdown-Blockquotes
|
||||
- RC Reply-Link-Entfernung
|
||||
- Edge Cases: Nachrichten ohne Quote, verschachtelte Quotes, Edits
|
||||
- P1: routing_text vs display_text Trennung
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
from plugin.archivar.reply_quote_stripper import (
|
||||
strip_reply_quote,
|
||||
strip_reply_quote_for_routing,
|
||||
_extract_quoted_text_from_attachments,
|
||||
_strip_rc_reply_link,
|
||||
_strip_blockquotes,
|
||||
_strip_quote_blocks,
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Stufe 1: Attachments-basiertes Stripping
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestAttachmentBasedStripping:
|
||||
"""Tests für attachments-basiertes Quote-Stripping (Stufe 1)."""
|
||||
|
||||
def test_reply_attachment_type_reply(self):
|
||||
"""Attachment mit type='reply' wird erkannt und gestrippt."""
|
||||
text = "Meine Antwort auf deine Frage\n\nDas ist der zitierte Text von der Parent-Nachricht"
|
||||
attachments = [
|
||||
{
|
||||
"type": "reply",
|
||||
"text": "Das ist der zitierte Text von der Parent-Nachricht",
|
||||
"author_name": "bernd",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
assert "zitierte Text" not in result
|
||||
assert "Meine Antwort" in result
|
||||
|
||||
def test_reply_attachment_type_quote(self):
|
||||
"""Attachment mit type='quote' wird erkannt."""
|
||||
text = "Ja, genau!\n\nUrsprüngliche Frage: Wie funktioniert der Archivar?"
|
||||
attachments = [
|
||||
{
|
||||
"type": "quote",
|
||||
"text": "Ursprüngliche Frage: Wie funktioniert der Archivar?",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
assert "Ursprüngliche Frage" not in result
|
||||
assert "Ja, genau!" in result
|
||||
|
||||
def test_reply_attachment_with_attachment_type_field(self):
|
||||
"""Attachment mit attachment_type='reply' wird erkannt."""
|
||||
text = "Gute Idee!\n\nWir sollten den Archivar erweitern um Multi-Room-Support"
|
||||
attachments = [
|
||||
{
|
||||
"attachment_type": "reply",
|
||||
"description": "Wir sollten den Archivar erweitern um Multi-Room-Support",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
assert "Multi-Room-Support" not in result
|
||||
assert "Gute Idee!" in result
|
||||
|
||||
def test_reply_attachment_with_message_link(self):
|
||||
"""Attachment mit message_link wird als Reply-Indikator erkannt."""
|
||||
text = "Antwort\n\nOriginal: Bitte dokumentiere das neue Feature"
|
||||
attachments = [
|
||||
{
|
||||
"message_link": "https://chat.example.com/group/room?msg=abc123",
|
||||
"text": "Original: Bitte dokumentiere das neue Feature",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
assert "dokumentiere" not in result
|
||||
assert "Antwort" in result
|
||||
|
||||
def test_no_reply_attachment_no_strip(self):
|
||||
"""Normales File-Attachment löst KEIN Stripping aus."""
|
||||
text = "Schau dir mal diese Datei an"
|
||||
attachments = [
|
||||
{
|
||||
"type": "file",
|
||||
"title": "dokumentation.pdf",
|
||||
"title_link": "/file-upload/abc123/dokumentation.pdf",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is False
|
||||
assert result == text
|
||||
|
||||
def test_empty_attachments_no_strip(self):
|
||||
"""Leere Attachment-Liste → kein Strip."""
|
||||
text = "Normaler Text ohne Quote"
|
||||
result, stripped = strip_reply_quote(text, [])
|
||||
assert stripped is False
|
||||
assert result == text
|
||||
|
||||
def test_none_attachments_no_strip(self):
|
||||
"""None attachments → kein Strip."""
|
||||
text = "Normaler Text ohne Quote"
|
||||
result, stripped = strip_reply_quote(text, None)
|
||||
assert stripped is False
|
||||
assert result == text
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Stufe 1b: RC Reply-Link-Entfernung
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestRCReplyLinkStripping:
|
||||
"""Tests für Rocket.Chat Reply-Link-Entfernung."""
|
||||
|
||||
def test_strip_rc_reply_link(self):
|
||||
"""[ ](url?msg=ID) wird entfernt."""
|
||||
text = "[ ](https://chat.example.com/group/room?msg=abc123) Meine Antwort"
|
||||
result = _strip_rc_reply_link(text)
|
||||
assert "[ ](https://chat.example.com" not in result
|
||||
assert "Meine Antwort" in result
|
||||
|
||||
def test_strip_rc_reply_link_with_text_after(self):
|
||||
"""Reply-Link am Anfang, Text danach."""
|
||||
text = "[ ](https://chat.example.com/group/room?msg=abc123) Was meinst du zum Archivar?"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "Archivar" in result
|
||||
assert "msg=abc123" not in result
|
||||
|
||||
def test_no_reply_link_no_strip(self):
|
||||
"""Text ohne Reply-Link bleibt unverändert."""
|
||||
text = "Was meinst du zum Archivar?"
|
||||
result = _strip_rc_reply_link(text)
|
||||
assert result == text
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Stufe 2: Text-basiertes Stripping
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestTextBasedStripping:
|
||||
"""Tests für text-basiertes Quote-Stripping (Stufe 2)."""
|
||||
|
||||
def test_strip_quote_block(self):
|
||||
"""[quote]...[/quote] Block wird entfernt."""
|
||||
text = "Meine Antwort\n\n[quote]Das ist ein zitierter Text[/quote]"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "[quote]" not in result
|
||||
assert "zitierter Text" not in result
|
||||
assert "Meine Antwort" in result
|
||||
|
||||
def test_strip_quote_author_block(self):
|
||||
"""[quote="author"]...[/quote] Block wird entfernt."""
|
||||
text = 'Antwort\n\n[quote="bernd"]Original: Bitte dokumentiere das[/quote]'
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "dokumentiere" not in result
|
||||
assert "Antwort" in result
|
||||
|
||||
def test_strip_markdown_blockquote(self):
|
||||
"""> Markdown-Blockquote wird entfernt."""
|
||||
text = "Meine Antwort\n\n> Das ist ein zitierter Text\n> mit mehreren Zeilen"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "zitierter Text" not in result
|
||||
assert "Meine Antwort" in result
|
||||
|
||||
def test_strip_multiline_blockquote(self):
|
||||
"""Mehrzeilige > Blockquote wird komplett entfernt."""
|
||||
text = "Antwort:\n\n> Zeile 1 des Zitats\n> Zeile 2 des Zitats\n> Zeile 3 des Zitats\n\nEigener Text"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "Zeile 1" not in result
|
||||
assert "Zeile 2" not in result
|
||||
assert "Zeile 3" not in result
|
||||
assert "Antwort:" in result
|
||||
assert "Eigener Text" in result
|
||||
|
||||
def test_quote_block_with_keyword_inside(self):
|
||||
"""Quote-Block mit Keyword 'archivar' wird entfernt — verhindert Fehl-Routing."""
|
||||
text = "Frage zum Plugin\n\n[quote]Der Archivar routet Nachrichten automatisch[/quote]"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "Archivar" not in result
|
||||
assert "Frage zum Plugin" in result
|
||||
|
||||
def test_blockquote_with_keyword_inside(self):
|
||||
"""Markdown-Blockquote mit Keyword wird entfernt."""
|
||||
text = "Neue Frage\n\n> Bitte dokumentiere das Multi-Room-Feature im Archivar"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "dokumentiere" not in result
|
||||
assert "Multi-Room" not in result
|
||||
assert "Neue Frage" in result
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Edge Cases
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestEdgeCases:
|
||||
"""Edge-Case-Tests für Reply-Quote-Stripping."""
|
||||
|
||||
def test_no_quote_no_change(self):
|
||||
"""Nachricht ohne Quote bleibt unverändert."""
|
||||
text = "Kannst du mir den Archivar erklären?"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is False
|
||||
assert result == text
|
||||
|
||||
def test_empty_text(self):
|
||||
"""Leerer Text bleibt leer."""
|
||||
result, stripped = strip_reply_quote("")
|
||||
assert stripped is False
|
||||
assert result == ""
|
||||
|
||||
def test_text_with_gt_symbol_not_blockquote(self):
|
||||
"""> mitten im Text (kein Zeilenanfang) ist kein Blockquote."""
|
||||
text = "Die Bedingung ist x > 5 und y < 10"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is False
|
||||
assert "x > 5" in result
|
||||
|
||||
def test_nested_quotes_outermost_only(self):
|
||||
"""Verschachtelte Quotes: nur die äußerste wird entfernt (defensiv)."""
|
||||
text = "Antwort\n\n> Äußeres Zitat\n> > Inneres Zitat\n> Noch äußeres"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
# Der gesamte > Block wird entfernt
|
||||
assert "Äußeres Zitat" not in result
|
||||
assert "Inneres Zitat" not in result
|
||||
assert "Antwort" in result
|
||||
|
||||
def test_edit_message_no_quote(self):
|
||||
"""Edit-Nachrichten ohne Quote werden nicht verändert."""
|
||||
text = "EDIT: Korrigierte Version des Archivar-Dokuments"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is False
|
||||
assert "Archivar" in result # Keyword bleibt erhalten
|
||||
|
||||
def test_quote_block_with_attachment_priority(self):
|
||||
"""Attachments-basiertes Stripping hat Priorität vor Text-basiertem."""
|
||||
text = "Antwort\n\n> Das ist ein Blockquote\n\nZitierter Attachment-Text"
|
||||
attachments = [
|
||||
{
|
||||
"type": "reply",
|
||||
"text": "Zitierter Attachment-Text",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
# Attachment-Text wurde entfernt
|
||||
assert "Zitierter Attachment-Text" not in result
|
||||
# Blockquote wurde NICHT entfernt (weil Stufe 1 schon gestrippt hat)
|
||||
# Das ist okay — wir strippen nur einmal
|
||||
|
||||
def test_whitespace_only_after_strip(self):
|
||||
"""Nach Strip nur noch Whitespace → leerer String."""
|
||||
text = "[ ](https://chat.example.com/group/room?msg=abc123)"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert result == ""
|
||||
|
||||
def test_multiple_blank_lines_collapsed(self):
|
||||
"""Mehrfache Leerzeilen nach Strip werden kollabiert."""
|
||||
text = "Antwort\n\n\n\n> Zitat\n\n\n\nEigener Text"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "\n\n\n\n" not in result
|
||||
assert "Antwort" in result
|
||||
assert "Eigener Text" in result
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1: routing_text vs display_text
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestRoutingVsDisplayText:
|
||||
"""Tests für P1: Trennung von routing_text und display_text."""
|
||||
|
||||
def test_routing_text_stripped_display_text_preserved(self):
|
||||
"""routing_text ohne Quote, display_text mit Quote."""
|
||||
text = "Meine Frage\n\n[quote]Der Archivar ist ein Routing-System[/quote]"
|
||||
routing_text, display_text, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is True
|
||||
assert "Archivar" not in routing_text # Quote gestrippt
|
||||
assert "Meine Frage" in routing_text
|
||||
assert display_text == text # Original erhalten
|
||||
assert "Archivar" in display_text # Quote im display_text
|
||||
|
||||
def test_no_quote_both_same(self):
|
||||
"""Ohne Quote sind routing_text und display_text identisch."""
|
||||
text = "Kannst du den Archivar erklären?"
|
||||
routing_text, display_text, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is False
|
||||
assert routing_text == text
|
||||
assert display_text == text
|
||||
|
||||
def test_attachment_quote_routing_stripped(self):
|
||||
"""Attachment-Quote: routing_text gestrippt, display_text erhalten."""
|
||||
text = "Ja, gute Frage!\n\nBitte dokumentiere das Multi-Room-Feature"
|
||||
attachments = [
|
||||
{
|
||||
"type": "reply",
|
||||
"text": "Bitte dokumentiere das Multi-Room-Feature",
|
||||
}
|
||||
]
|
||||
routing_text, display_text, was_stripped = strip_reply_quote_for_routing(
|
||||
text, attachments
|
||||
)
|
||||
|
||||
assert was_stripped is True
|
||||
assert "dokumentiere" not in routing_text
|
||||
assert "Ja, gute Frage!" in routing_text
|
||||
assert display_text == text
|
||||
assert "dokumentiere" in display_text
|
||||
|
||||
def test_rc_reply_link_routing_stripped(self):
|
||||
"""RC Reply-Link: routing_text ohne Link, display_text mit Link."""
|
||||
text = "[ ](https://chat.example.com/group/room?msg=abc123) Frage zum Archivar"
|
||||
routing_text, display_text, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is True
|
||||
assert "msg=abc123" not in routing_text
|
||||
assert "Frage zum Archivar" in routing_text
|
||||
assert display_text == text
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Integration: Keyword-Matcher mit gestripptem Text
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestKeywordMatcherIntegration:
|
||||
"""Integrationstest: Keyword-Matcher sieht gestrippten Text nicht."""
|
||||
|
||||
def test_keyword_in_quote_not_matched(self):
|
||||
"""Keyword NUR im Quote → kein Match nach Strip."""
|
||||
from plugin.archivar.keyword_matcher import match_keyword
|
||||
|
||||
text = "Frage zum Plugin\n\n[quote]Bitte dokumentiere das Archivar-Feature[/quote]"
|
||||
routing_text, _, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is True
|
||||
# 'dokumentiere' war nur im Quote → nach Strip kein Match
|
||||
assert not match_keyword("dokumentiere", routing_text)
|
||||
# 'archivar' war nur im Quote → nach Strip kein Match
|
||||
assert not match_keyword("archivar", routing_text)
|
||||
|
||||
def test_keyword_in_body_still_matched(self):
|
||||
"""Keyword im Body (nicht im Quote) → Match nach Strip."""
|
||||
from plugin.archivar.keyword_matcher import match_keyword
|
||||
|
||||
text = "Bitte dokumentiere das Plugin\n\n[quote]Alte Frage zum Archivar[/quote]"
|
||||
routing_text, _, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is True
|
||||
# 'dokumentiere' ist im Body → Match
|
||||
assert match_keyword("dokumentiere", routing_text)
|
||||
# 'archivar' war im Quote → kein Match
|
||||
assert not match_keyword("archivar", routing_text)
|
||||
@@ -420,6 +420,33 @@ class TestDispatchReviewButton:
|
||||
assert state["sub_phase"] == SUB_PHASE_THEME_EDIT
|
||||
assert state["pending_text_input"] is True
|
||||
|
||||
def test_back_button_not_intercepted_by_text_input(self):
|
||||
"""P0: Bei pending_text_input=True wird Button-Klick als Button dispatch, NICHT als Keyword-Freitext."""
|
||||
rm = _load_room_map([
|
||||
{"room_id": "r1", "name": "#Dev", "theme": "dev", "keywords_100": ["code"], "keywords_context": []},
|
||||
{"room_id": "r2", "name": "#Ops", "theme": "ops", "keywords_100": ["server"], "keywords_context": [], "catch_all": True},
|
||||
])
|
||||
# Simuliere: User ist in keywords_edit Sub-Phase, pending_text_input=True
|
||||
state = self._make_state(
|
||||
sub_phase=SUB_PHASE_KEYWORDS_EDIT,
|
||||
target_room_id="r1",
|
||||
edit_kind="keywords_100",
|
||||
pending_text_input=True,
|
||||
)
|
||||
archivar = self._make_archivar_mock(rm)
|
||||
# Klick auf "↩️ Zurück" sendet REVIEW_ROOM_EDIT::r1::edit
|
||||
payload = f"{REVIEW_ROOM_EDIT}::r1::edit"
|
||||
handled, text, attachments = dispatch_review_button(
|
||||
payload, state, rm, archivar, _mock_build_buttons, None
|
||||
)
|
||||
# Soll als Button behandelt werden, NICHT als Keyword
|
||||
assert handled is True
|
||||
# State muss auf edit Sub-Phase zurückgesetzt sein
|
||||
assert state["sub_phase"] == SUB_PHASE_EDIT
|
||||
assert state["pending_text_input"] is False
|
||||
# Keywords unverändert (kein "REVIEW_ROOM_EDIT::r1::edit" als Keyword)
|
||||
assert rm.get_room_by_id("r1").keywords_100 == ["code"]
|
||||
|
||||
def test_dispatch_catch_all_toggle(self):
|
||||
rm = _load_room_map([
|
||||
{"room_id": "r1", "name": "#Dev", "theme": "dev", "keywords": ["code"]},
|
||||
|
||||
@@ -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.
|
||||
|
||||
+15
-1
@@ -18,7 +18,21 @@ import urllib.request
|
||||
from typing import Any, Dict, List, Optional
|
||||
import urllib.parse
|
||||
|
||||
from tools.registry import tool_error, tool_result
|
||||
|
||||
# Inlined from tools.registry — avoids import conflict with the plugin's
|
||||
# own tools.py module (which shadows the core tools/ package when the
|
||||
# plugin directory is on sys.path).
|
||||
def tool_error(message, **extra) -> str:
|
||||
result = {"error": str(message)}
|
||||
if extra:
|
||||
result.update(extra)
|
||||
return json.dumps(result, ensure_ascii=False)
|
||||
|
||||
|
||||
def tool_result(data=None, **kwargs) -> str:
|
||||
if data is not None:
|
||||
return json.dumps(data, ensure_ascii=False)
|
||||
return json.dumps(kwargs, ensure_ascii=False)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
"""
|
||||
V8.5: Test für _build_room_map_summary() — Keywords in Raumübersicht.
|
||||
|
||||
Andreas hat vermisst, dass die Raumübersicht in ::hilfe keine Keywords
|
||||
(keywords_100, keywords_context) anzeigt. Dieser Test verifiziert, dass
|
||||
_build_room_map_summary() beide Keyword-Listen in der Ausgabe enthält.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
# Ensure the plugin package is importable
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
|
||||
from plugin.archivar.room_map import RoomMap, RoomEntry
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Hilfsfunktion: Mock-Adapter mit kontrollierter Raum-Map
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
def _make_mock_adapter(room_map: RoomMap | None = None):
|
||||
"""Erzeugt einen minimalen Mock-Adapter mit kontrollierter Raum-Map.
|
||||
|
||||
Der Adapter wird so gepatcht, dass _MULTIROOM() True zurückgibt und
|
||||
self.archivar eine mock-Instanz mit der gewünschten _room_map ist.
|
||||
"""
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
# Erzeuge eine Instanz OHNE echten __init__ (der braucht PlatformConfig)
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
|
||||
# Mock-Archivar mit _room_map
|
||||
mock_archivar = MagicMock()
|
||||
mock_archivar._room_map = room_map
|
||||
adapter.archivar = mock_archivar
|
||||
|
||||
return adapter
|
||||
|
||||
|
||||
def _make_room_map(rooms: dict[str, RoomEntry]) -> RoomMap:
|
||||
"""Erzeugt eine RoomMap mit den gegebenen Räumen."""
|
||||
return RoomMap(
|
||||
rooms=rooms,
|
||||
excluded_room_ids=set(),
|
||||
fact_store_path=Path("/tmp/test_fact_store"),
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test: Keywords erscheinen in der Zusammenfassung
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
@patch("plugin.adapter._MULTIROOM", return_value=True)
|
||||
def test_room_map_summary_shows_keywords(mock_multiroom):
|
||||
"""Verifiziert dass keywords_100 und keywords_context in der Ausgabe erscheinen."""
|
||||
room_map = _make_room_map({
|
||||
"6a19b0ff": RoomEntry(
|
||||
room_id="6a19b0ff",
|
||||
name="Rocketchat-Plugin",
|
||||
theme="Hermes Gateway Plugin Entwicklung",
|
||||
keywords_100=["multi-room", "rocketchat plugin", "archivar"],
|
||||
keywords_context=["gateway", "plugin", "rc", "deployment"],
|
||||
catch_all=True,
|
||||
),
|
||||
"abc123": RoomEntry(
|
||||
room_id="abc123",
|
||||
name="BAT Trading",
|
||||
theme="Krypto-Trading und Analyse",
|
||||
keywords_100=["bat", "trading", "krypto"],
|
||||
keywords_context=["docker", "api", "container"],
|
||||
catch_all=False,
|
||||
),
|
||||
})
|
||||
|
||||
adapter = _make_mock_adapter(room_map)
|
||||
|
||||
summary = adapter._build_room_map_summary()
|
||||
|
||||
# Soll Keywords 100% enthalten
|
||||
assert "Keywords 100%:" in summary, (
|
||||
f"keywords_100 fehlen in der Zusammenfassung:\n{summary}"
|
||||
)
|
||||
assert "multi-room, rocketchat plugin, archivar" in summary, (
|
||||
f"keywords_100 für Rocketchat-Plugin fehlen:\n{summary}"
|
||||
)
|
||||
assert "bat, trading, krypto" in summary, (
|
||||
f"keywords_100 für BAT Trading fehlen:\n{summary}"
|
||||
)
|
||||
|
||||
# Soll Keywords Kontext enthalten
|
||||
assert "Keywords Kontext:" in summary, (
|
||||
f"keywords_context fehlen in der Zusammenfassung:\n{summary}"
|
||||
)
|
||||
assert "gateway, plugin, rc, deployment" in summary, (
|
||||
f"keywords_context für Rocketchat-Plugin fehlen:\n{summary}"
|
||||
)
|
||||
assert "docker, api, container" in summary, (
|
||||
f"keywords_context für BAT Trading fehlen:\n{summary}"
|
||||
)
|
||||
|
||||
# Soll Catch-All-Marker enthalten
|
||||
assert "CATCH-ALL" in summary, (
|
||||
f"Catch-All-Marker fehlt:\n{summary}"
|
||||
)
|
||||
|
||||
# Soll Raum-Namen und IDs enthalten
|
||||
assert "Rocketchat-Plugin (6a19b0ff)" in summary
|
||||
assert "BAT Trading (abc123)" in summary
|
||||
|
||||
|
||||
@patch("plugin.adapter._MULTIROOM", return_value=True)
|
||||
def test_room_map_summary_empty_keywords(mock_multiroom):
|
||||
"""Verifiziert dass leere Keyword-Listen keine leeren Zeilen erzeugen."""
|
||||
room_map = _make_room_map({
|
||||
"dm123": RoomEntry(
|
||||
room_id="dm123",
|
||||
name="DM Admin",
|
||||
theme="Catch-All für nicht zuordenbare Nachrichten",
|
||||
keywords_100=[],
|
||||
keywords_context=[],
|
||||
catch_all=True,
|
||||
),
|
||||
})
|
||||
|
||||
adapter = _make_mock_adapter(room_map)
|
||||
|
||||
summary = adapter._build_room_map_summary()
|
||||
|
||||
# Soll KEINE Keywords-Zeilen enthalten (weil beide Listen leer sind)
|
||||
assert "Keywords 100%:" not in summary, (
|
||||
f"Leere keywords_100 sollten keine Zeile erzeugen:\n{summary}"
|
||||
)
|
||||
assert "Keywords Kontext:" not in summary, (
|
||||
f"Leere keywords_context sollten keine Zeile erzeugen:\n{summary}"
|
||||
)
|
||||
|
||||
# Soll trotzdem Raum-Info enthalten
|
||||
assert "DM Admin (dm123)" in summary
|
||||
assert "CATCH-ALL" in summary
|
||||
|
||||
|
||||
@patch("plugin.adapter._MULTIROOM", return_value=True)
|
||||
def test_room_map_summary_no_rooms(mock_multiroom):
|
||||
"""Verifiziert dass leere Raum-Map leeren String zurückgibt."""
|
||||
room_map = _make_room_map({})
|
||||
|
||||
adapter = _make_mock_adapter(room_map)
|
||||
|
||||
summary = adapter._build_room_map_summary()
|
||||
|
||||
assert summary == "", (
|
||||
f"Leere Raum-Map sollte leeren String zurückgeben, nicht:\n{summary}"
|
||||
)
|
||||
|
||||
|
||||
@patch("plugin.adapter._MULTIROOM", return_value=False)
|
||||
def test_room_map_summary_multiroom_disabled(mock_multiroom):
|
||||
"""Verifiziert dass deaktiviertes Multiroom leeren String zurückgibt."""
|
||||
room_map = _make_room_map({
|
||||
"abc": RoomEntry(
|
||||
room_id="abc",
|
||||
name="Test",
|
||||
theme="Test",
|
||||
keywords_100=["test"],
|
||||
keywords_context=["test"],
|
||||
),
|
||||
})
|
||||
|
||||
adapter = _make_mock_adapter(room_map)
|
||||
|
||||
summary = adapter._build_room_map_summary()
|
||||
|
||||
assert summary == "", (
|
||||
f"Deaktiviertes Multiroom sollte leeren String zurückgeben, nicht:\n{summary}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# V8.6: PresenceEngine-Init-Logging (R-3 + R-4)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestPresenceEngineInitLogging:
|
||||
"""R-3: INFO-Log bei erfolgreicher PresenceEngine-Initialisierung."""
|
||||
|
||||
def test_presence_engine_init_logs_info(self):
|
||||
"""Bei erfolgreicher Init wird ein INFO-Log mit enabled/coalesce_ms geschrieben."""
|
||||
import logging
|
||||
from io import StringIO
|
||||
|
||||
log_stream = StringIO()
|
||||
handler = logging.StreamHandler(log_stream)
|
||||
handler.setLevel(logging.INFO)
|
||||
|
||||
logger = logging.getLogger("plugin.adapter")
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
try:
|
||||
# Simuliere die PresenceEngine-Init wie in adapter.py Z.805-815
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
|
||||
_presence_enabled = True
|
||||
_coalesce_ms = 2000
|
||||
|
||||
engine = PresenceEngine(
|
||||
rest=mock_rest,
|
||||
enabled=_presence_enabled,
|
||||
coalesce_ms=_coalesce_ms,
|
||||
pulse_interval=10,
|
||||
)
|
||||
|
||||
# R-3: Log-Ausgabe
|
||||
logger.info(
|
||||
"[rocketchat] V8.6: PresenceEngine initialisiert (enabled=%s, coalesce_ms=%s)",
|
||||
_presence_enabled,
|
||||
_coalesce_ms,
|
||||
)
|
||||
|
||||
log_output = log_stream.getvalue()
|
||||
assert "V8.6: PresenceEngine initialisiert" in log_output, (
|
||||
f"INFO-Log fehlt:\n{log_output}"
|
||||
)
|
||||
assert "enabled=True" in log_output, (
|
||||
f"enabled-Parameter fehlt im Log:\n{log_output}"
|
||||
)
|
||||
assert "coalesce_ms=2000" in log_output, (
|
||||
f"coalesce_ms-Parameter fehlt im Log:\n{log_output}"
|
||||
)
|
||||
finally:
|
||||
logger.removeHandler(handler)
|
||||
|
||||
|
||||
class TestPresenceEngineInitErrorHandling:
|
||||
"""R-4: try/except um die Initialisierung — graceful degradation."""
|
||||
|
||||
def test_presence_engine_init_error_logs_and_graceful_degrade(self):
|
||||
"""Bei Fehler: ERROR-Log + self._presence_engine = None."""
|
||||
import logging
|
||||
from io import StringIO
|
||||
|
||||
log_stream = StringIO()
|
||||
handler = logging.StreamHandler(log_stream)
|
||||
handler.setLevel(logging.ERROR)
|
||||
|
||||
logger = logging.getLogger("plugin.adapter")
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(logging.ERROR)
|
||||
|
||||
try:
|
||||
# Simuliere einen Fehler bei der PresenceEngine-Init
|
||||
_presence_engine = None
|
||||
try:
|
||||
raise RuntimeError("PresenceEngine-Modul nicht gefunden")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"[rocketchat] V8.6: PresenceEngine-Initialisierung FEHLGESCHLAGEN: %s",
|
||||
e,
|
||||
)
|
||||
_presence_engine = None # Graceful degradation
|
||||
|
||||
log_output = log_stream.getvalue()
|
||||
assert "V8.6: PresenceEngine-Initialisierung FEHLGESCHLAGEN" in log_output, (
|
||||
f"ERROR-Log fehlt:\n{log_output}"
|
||||
)
|
||||
assert "PresenceEngine-Modul nicht gefunden" in log_output, (
|
||||
f"Fehlermeldung fehlt im Log:\n{log_output}"
|
||||
)
|
||||
assert _presence_engine is None, (
|
||||
"Graceful degradation: _presence_engine muss None sein"
|
||||
)
|
||||
finally:
|
||||
logger.removeHandler(handler)
|
||||
|
||||
|
||||
class TestPresenceEngineNoneGuard:
|
||||
"""P1-3: _send_onboarding_message und _complete_onboarding müssen
|
||||
ohne _presence_engine (None) keinen AttributeError werfen."""
|
||||
|
||||
def test_send_onboarding_message_without_presence_engine(self):
|
||||
"""_send_onboarding_message: ohne _presence_engine → kein Crash."""
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
# _presence_engine NICHT setzen — simuliert graceful degradation
|
||||
adapter.archivar = MagicMock()
|
||||
adapter.archivar._state = MagicMock()
|
||||
adapter.archivar._stats = {}
|
||||
adapter._room_info = {}
|
||||
adapter._onboarding_state = None
|
||||
adapter._get_build_custom_buttons = MagicMock(return_value=MagicMock())
|
||||
adapter._post_message_with_retry = AsyncMock()
|
||||
|
||||
missing_rooms = [{"room_id": "room1", "name": "#test"}]
|
||||
|
||||
with patch("plugin.adapter._MULTIROOM", return_value=True):
|
||||
try:
|
||||
asyncio.run(adapter._send_onboarding_message("op_room", missing_rooms))
|
||||
except AttributeError as e:
|
||||
pytest.fail(
|
||||
f"_send_onboarding_message crashed ohne _presence_engine: {e}"
|
||||
)
|
||||
|
||||
def test_complete_onboarding_without_presence_engine(self):
|
||||
"""_complete_onboarding: ohne _presence_engine → kein Crash."""
|
||||
import asyncio
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
# _presence_engine NICHT setzen
|
||||
adapter.archivar = MagicMock()
|
||||
adapter.archivar._stats = {}
|
||||
adapter.archivar._state = MagicMock()
|
||||
adapter._onboarding_state = {"missing_rooms": []}
|
||||
adapter._room_map_summary = ""
|
||||
|
||||
with patch("archivar.onboarding.release_onboarding_lock"):
|
||||
try:
|
||||
asyncio.run(adapter._complete_onboarding("op_room"))
|
||||
except AttributeError as e:
|
||||
pytest.fail(
|
||||
f"_complete_onboarding crashed ohne _presence_engine: {e}"
|
||||
)
|
||||
|
||||
|
||||
class TestFileBlockStripping:
|
||||
"""P2-1: _download_and_inline_files muss [FILE]-Blöcke nach
|
||||
fehlgeschlagenen Downloads aus dem Text entfernen."""
|
||||
|
||||
def test_file_blocks_stripped_after_failed_download(self):
|
||||
"""Fehlgeschlagener Download → [FILE]-Blöcke werden entfernt."""
|
||||
import asyncio
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.download_file = MagicMock(return_value=None) # Download fails
|
||||
adapter.rest = mock_rest
|
||||
|
||||
text = (
|
||||
"Hier ist eine Datei:\n"
|
||||
"[FILE] report.pdf (application/pdf)\n"
|
||||
"Download: https://chat.example.com/file-upload/abc123/report.pdf\n"
|
||||
"\n"
|
||||
"Und noch eine:\n"
|
||||
"[FILE] image.png (image/png)\n"
|
||||
"Download: https://chat.example.com/file-upload/def456/image.png\n"
|
||||
"\n"
|
||||
"Ende der Nachricht."
|
||||
)
|
||||
|
||||
result = asyncio.run(adapter._download_and_inline_files(text))
|
||||
|
||||
# [FILE]-Blöcke müssen entfernt sein
|
||||
assert "[FILE]" not in result, (
|
||||
f"[FILE]-Marker nicht entfernt:\n{result}"
|
||||
)
|
||||
assert "Download:" not in result, (
|
||||
f"Download-URL nicht entfernt:\n{result}"
|
||||
)
|
||||
# Restlicher Text muss erhalten bleiben
|
||||
assert "Hier ist eine Datei:" in result
|
||||
assert "Ende der Nachricht." in result
|
||||
|
||||
def test_file_blocks_stripped_mixed_success_failure(self):
|
||||
"""Ein erfolgreicher Download + ein Fehlschlag → nur Fail-Marker entfernt."""
|
||||
import asyncio
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
mock_rest = MagicMock()
|
||||
|
||||
# Erster Download erfolgreich, zweiter fehlgeschlagen
|
||||
call_count = [0]
|
||||
|
||||
def download_file(fid, fname):
|
||||
call_count[0] += 1
|
||||
if call_count[0] == 1:
|
||||
return "Inhalt der PDF-Datei"
|
||||
return None
|
||||
|
||||
mock_rest.download_file = download_file
|
||||
adapter.rest = mock_rest
|
||||
|
||||
text = (
|
||||
"[FILE] report.pdf (application/pdf)\n"
|
||||
"Download: https://chat.example.com/file-upload/abc123/report.pdf\n"
|
||||
"\n"
|
||||
"[FILE] missing.doc (application/msword)\n"
|
||||
"Download: https://chat.example.com/file-upload/xyz789/missing.doc\n"
|
||||
)
|
||||
|
||||
result = asyncio.run(adapter._download_and_inline_files(text))
|
||||
|
||||
# Erfolgreicher Download: Content muss da sein
|
||||
assert "[FILE CONTENT: report.pdf]" in result
|
||||
assert "Inhalt der PDF-Datei" in result
|
||||
# Fehlgeschlagener Download: [FILE]-Block muss weg sein
|
||||
assert "missing.doc" not in result, (
|
||||
f"Fehlgeschlagener [FILE]-Block nicht entfernt:\n{result}"
|
||||
)
|
||||
assert "xyz789" not in result
|
||||
|
||||
def test_file_blocks_stripped_unicode_filename(self):
|
||||
"""Unicode-Dateinamen in [FILE]-Blöcken werden korrekt gestrippt."""
|
||||
import asyncio
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.download_file = MagicMock(return_value=None)
|
||||
adapter.rest = mock_rest
|
||||
|
||||
text = (
|
||||
"Schau dir das an:\n"
|
||||
"[FILE] Überblick_2024.pdf (application/pdf)\n"
|
||||
"Download: https://chat.example.com/file-upload/abc123/Überblick_2024.pdf\n"
|
||||
"\n"
|
||||
"Und:\n"
|
||||
"[FILE] 報告書.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document)\n"
|
||||
"Download: https://chat.example.com/file-upload/def456/報告書.docx\n"
|
||||
)
|
||||
|
||||
result = asyncio.run(adapter._download_and_inline_files(text))
|
||||
|
||||
assert "[FILE]" not in result, (
|
||||
f"Unicode [FILE]-Marker nicht entfernt:\n{result}"
|
||||
)
|
||||
assert "Download:" not in result
|
||||
assert "Schau dir das an:" in result
|
||||
@@ -0,0 +1,483 @@
|
||||
"""
|
||||
P1-2 O-2: Tests für echte await-Semantik bei DDP setDefaultStatus.
|
||||
|
||||
10 Tests:
|
||||
1-5: DDPClient.set_status_async (Future-Store, Timeout, Error, NotConnected, Leak)
|
||||
6-8: PulseController async-bridge (loop-bound, fallback, pause)
|
||||
9-10: Legacy-Pfade unverändert (on_connected, idle timer)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import concurrent.futures
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch, PropertyMock
|
||||
|
||||
import pytest
|
||||
|
||||
# Ensure the plugin package is importable
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from plugin.adapter import (
|
||||
DDPClient,
|
||||
DDPTimeout,
|
||||
DDPServerError,
|
||||
DDPNotConnected,
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Hilfsfunktionen
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
def _make_ddp_client(connected: bool = True) -> DDPClient:
|
||||
"""Erzeugt einen DDPClient mit Mock-Socket für Tests."""
|
||||
client = DDPClient.__new__(DDPClient)
|
||||
client.host = "test.example.com"
|
||||
client._on_message = None
|
||||
client._on_connected = None
|
||||
client._on_room_event = None
|
||||
client.sock = None
|
||||
client.connected = connected
|
||||
client._running = False
|
||||
client._reader_thread = None
|
||||
client._write_lock = threading.Lock()
|
||||
client._msg_queue = MagicMock()
|
||||
client._next_sub_id = 1
|
||||
client._sub_rooms = {}
|
||||
client._session = None
|
||||
client._reconnect_attempt = 0
|
||||
client._last_rx_time = 0.0
|
||||
# P1-2 O-2 fields
|
||||
client._pending_results = {}
|
||||
client._loop = None
|
||||
client._result_lock = threading.Lock()
|
||||
client._msg_seq = 0
|
||||
return client
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 1: set_status_async resolves on result message
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestSetStatusAsyncResolvesOnResult:
|
||||
"""Test 1: Reader schickt result → Future wird True."""
|
||||
|
||||
def test_set_status_async_resolves_on_result_message(self):
|
||||
"""Simuliere: set_status_async sendet, Reader löst Future auf."""
|
||||
client = _make_ddp_client(connected=True)
|
||||
client._send_json = MagicMock() # Mock send
|
||||
|
||||
# Starte einen asyncio-Loop im Hintergrund
|
||||
async def _run():
|
||||
# Rufe set_status_async auf
|
||||
task = asyncio.create_task(client.set_status_async("online", timeout=5.0))
|
||||
|
||||
# Warte kurz, dass die msg_id registriert wird
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
# Simuliere: Reader-Thread empfängt result
|
||||
msg_id = None
|
||||
with client._result_lock:
|
||||
for mid in list(client._pending_results.keys()):
|
||||
msg_id = mid
|
||||
break
|
||||
|
||||
assert msg_id is not None, "msg_id sollte in _pending_results registriert sein"
|
||||
|
||||
# Reader löst Future auf (simuliert _handle_result_message)
|
||||
client._handle_result_message({
|
||||
"msg": "result",
|
||||
"id": msg_id,
|
||||
"result": True,
|
||||
})
|
||||
|
||||
# Warte auf Task
|
||||
result = await asyncio.wait_for(task, timeout=2.0)
|
||||
assert result is True
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
def test_set_status_async_sends_correct_frame(self):
|
||||
"""set_status_async sendet korrektes DDP-Frame."""
|
||||
client = _make_ddp_client(connected=True)
|
||||
sent_frames = []
|
||||
client._send_json = lambda obj: sent_frames.append(obj)
|
||||
|
||||
async def _run():
|
||||
# Starte set_status_async
|
||||
task = asyncio.create_task(client.set_status_async("away", timeout=5.0))
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
# Finde die msg_id aus dem gesendeten Frame
|
||||
assert len(sent_frames) == 1
|
||||
frame = sent_frames[0]
|
||||
assert frame["msg"] == "method"
|
||||
assert frame["method"] == "UserPresence:setDefaultStatus"
|
||||
assert frame["params"] == ["away"]
|
||||
assert frame["id"].startswith("st")
|
||||
msg_id = frame["id"]
|
||||
|
||||
# Simuliere result vom Server
|
||||
client._handle_result_message({
|
||||
"msg": "result",
|
||||
"id": msg_id,
|
||||
"result": True,
|
||||
})
|
||||
|
||||
result = await asyncio.wait_for(task, timeout=2.0)
|
||||
assert result is True
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 2: set_status_async times out without result
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestSetStatusAsyncTimeout:
|
||||
"""Test 2: kein result → DDPTimeout nach timeout."""
|
||||
|
||||
def test_set_status_async_times_out_without_result(self):
|
||||
"""Wenn kein result kommt, wird DDPTimeout geworfen."""
|
||||
client = _make_ddp_client(connected=True)
|
||||
client._send_json = MagicMock()
|
||||
|
||||
async def _run():
|
||||
with pytest.raises(DDPTimeout) as exc_info:
|
||||
await client.set_status_async("online", timeout=0.1)
|
||||
assert "timed out" in str(exc_info.value).lower()
|
||||
|
||||
# Future sollte aus _pending_results entfernt sein
|
||||
with client._result_lock:
|
||||
assert len(client._pending_results) == 0
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 3: set_status_async raises on server error
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestSetStatusAsyncServerError:
|
||||
"""Test 3: error-Feld → DDPServerError."""
|
||||
|
||||
def test_set_status_async_raises_on_server_error(self):
|
||||
"""Server schickt error → DDPServerError wird geworfen."""
|
||||
client = _make_ddp_client(connected=True)
|
||||
client._send_json = MagicMock()
|
||||
|
||||
async def _run():
|
||||
task = asyncio.create_task(client.set_status_async("busy", timeout=5.0))
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
# Finde msg_id
|
||||
msg_id = None
|
||||
with client._result_lock:
|
||||
for mid in list(client._pending_results.keys()):
|
||||
msg_id = mid
|
||||
break
|
||||
|
||||
assert msg_id is not None
|
||||
|
||||
# Simuliere Server-Error
|
||||
client._handle_result_message({
|
||||
"msg": "result",
|
||||
"id": msg_id,
|
||||
"error": {"error": "status not allowed"},
|
||||
})
|
||||
|
||||
with pytest.raises(DDPServerError) as exc_info:
|
||||
await asyncio.wait_for(task, timeout=2.0)
|
||||
assert "status not allowed" in str(exc_info.value)
|
||||
|
||||
# Future sollte aus Store entfernt sein
|
||||
with client._result_lock:
|
||||
assert msg_id not in client._pending_results
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 4: set_status_async not connected raises
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestSetStatusAsyncNotConnected:
|
||||
"""Test 4: DDPNotConnected wenn nicht connected."""
|
||||
|
||||
def test_set_status_async_not_connected_raises(self):
|
||||
"""Nicht connected → DDPNotConnected."""
|
||||
client = _make_ddp_client(connected=False)
|
||||
|
||||
async def _run():
|
||||
with pytest.raises(DDPNotConnected):
|
||||
await client.set_status_async("online")
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 5: _pending_results store does not leak
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestPendingResultsNoLeak:
|
||||
"""Test 5: 100 parallel, 50 ohne result → Sweep räumt auf."""
|
||||
|
||||
def test_pending_results_store_does_not_leak(self):
|
||||
"""Sweep entfernt stale Futures (>2s alt)."""
|
||||
client = _make_ddp_client(connected=True)
|
||||
client._send_json = MagicMock()
|
||||
|
||||
# Registriere 50 "alte" Futures (Timestamp vor 3s)
|
||||
old_ts = int((time.time() - 3.0) * 1000)
|
||||
for i in range(50):
|
||||
msg_id = f"st{old_ts}_{i}"
|
||||
future = concurrent.futures.Future()
|
||||
with client._result_lock:
|
||||
client._pending_results[msg_id] = future
|
||||
|
||||
# Registriere 50 "frische" Futures (Timestamp jetzt)
|
||||
fresh_ts = int(time.time() * 1000)
|
||||
for i in range(50, 100):
|
||||
msg_id = f"st{fresh_ts}_{i}"
|
||||
future = concurrent.futures.Future()
|
||||
with client._result_lock:
|
||||
client._pending_results[msg_id] = future
|
||||
|
||||
assert len(client._pending_results) == 100
|
||||
|
||||
# Sweep ausführen
|
||||
client._sweep_pending_results()
|
||||
|
||||
# Nur die 50 frischen sollten übrig sein
|
||||
remaining = len(client._pending_results)
|
||||
assert remaining == 50, (
|
||||
f"Erwartet 50 verbleibende Futures, bekam {remaining}"
|
||||
)
|
||||
|
||||
# Alle verbleibenden sollten frische msg_ids haben
|
||||
for msg_id in client._pending_results:
|
||||
ts_part = msg_id[2:].split("_")[0]
|
||||
ts_ms = int(ts_part)
|
||||
assert ts_ms >= fresh_ts, (
|
||||
f"Alte msg_id {msg_id} wurde nicht gesweept"
|
||||
)
|
||||
|
||||
def test_sweep_handles_malformed_msg_ids(self):
|
||||
"""Sweep entfernt auch Futures mit kaputten msg_ids."""
|
||||
client = _make_ddp_client(connected=True)
|
||||
|
||||
# Registriere Future mit kaputter msg_id
|
||||
future = concurrent.futures.Future()
|
||||
with client._result_lock:
|
||||
client._pending_results["kaputt"] = future
|
||||
|
||||
client._sweep_pending_results()
|
||||
|
||||
assert len(client._pending_results) == 0
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 6: PulseController uses async when loop bound
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestPulseControllerAsyncWhenLoopBound:
|
||||
"""Test 6: set_status_async aufgerufen, set_status 0x wenn Loop gebunden."""
|
||||
|
||||
def test_pulse_controller_uses_async_when_loop_bound(self):
|
||||
"""Mit gebundenem Loop → _pulse_tick_async wird aufgerufen."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock()
|
||||
# set_status_async muss eine echte Coroutine sein
|
||||
async def _mock_set_status_async(status, timeout=2.0):
|
||||
return True
|
||||
mock_ddp.set_status_async = _mock_set_status_async
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
async def _run():
|
||||
loop = asyncio.get_running_loop()
|
||||
pc.bind_loop(loop)
|
||||
await pc._pulse_tick_async()
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
# set_status (sync) sollte NICHT aufgerufen worden sein
|
||||
mock_ddp.set_status.assert_not_called()
|
||||
|
||||
def test_pulse_controller_async_falls_back_to_rest(self):
|
||||
"""Wenn set_status_async fehlschlägt → REST-Fallback."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
async def _mock_set_status_async_raises(status, timeout=2.0):
|
||||
raise DDPTimeout("timeout")
|
||||
mock_ddp.set_status_async = _mock_set_status_async_raises
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
pc.bind_ddp(mock_ddp)
|
||||
pc.bind_rest(mock_rest)
|
||||
|
||||
async def _run():
|
||||
loop = asyncio.get_running_loop()
|
||||
pc.bind_loop(loop)
|
||||
await pc._pulse_tick_async()
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
# REST sollte als Fallback aufgerufen worden sein
|
||||
mock_rest._request.assert_called_once()
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 7: PulseController fallback to sync when no loop
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestPulseControllerFallbackToSync:
|
||||
"""Test 7: set_status (sync) aufgerufen wenn kein Loop gebunden."""
|
||||
|
||||
def test_pulse_controller_fallback_to_sync_when_no_loop(self):
|
||||
"""Ohne Loop → legacy sync-Pfad mit set_status."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(return_value=True)
|
||||
mock_ddp.set_status_async = MagicMock()
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# KEIN Loop gebunden → _pulse_tick nutzt sync-Pfad
|
||||
pc._pulse_tick()
|
||||
|
||||
# set_status (sync) sollte aufgerufen worden sein
|
||||
mock_ddp.set_status.assert_called_once()
|
||||
# set_status_async sollte NICHT aufgerufen worden sein
|
||||
mock_ddp.set_status_async.assert_not_called()
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 8: PulseController pause still works in async mode
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestPulseControllerPauseInAsyncMode:
|
||||
"""Test 8: pause stoppt async-Pfad."""
|
||||
|
||||
def test_pulse_controller_pause_still_works_in_async_mode(self):
|
||||
"""Pausierter PulseController führt keinen Tick aus."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(return_value=True)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# Pausieren
|
||||
pc.pause()
|
||||
assert pc._paused.is_set()
|
||||
|
||||
# _pulse_tick sollte wegen Pause nichts tun
|
||||
# (die Pause-Prüfung ist in _pulse_loop, nicht in _pulse_tick)
|
||||
# _pulse_tick selbst prüft nur cancel_pending
|
||||
# Also: _pulse_tick wird trotz Pause ausgeführt, wenn direkt aufgerufen
|
||||
# Das ist korrekt — die Pause greift in _pulse_loop
|
||||
pc._pulse_tick()
|
||||
# set_status wird aufgerufen (weil _pulse_tick Pause nicht prüft)
|
||||
# Das ist das erwartete Verhalten: _pulse_loop ist für Pause zuständig
|
||||
|
||||
# Resume
|
||||
pc.resume()
|
||||
assert not pc._paused.is_set()
|
||||
|
||||
def test_pulse_controller_cancel_pending_skips_tick(self):
|
||||
"""cancel_pending Flag überspringt nächsten Tick."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(return_value=True)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# Setze cancel_pending
|
||||
pc.cancel_pending()
|
||||
assert pc._cancel_pending is True
|
||||
|
||||
# _pulse_tick sollte übersprungen werden
|
||||
pc._pulse_tick()
|
||||
|
||||
# set_status sollte NICHT aufgerufen worden sein
|
||||
mock_ddp.set_status.assert_not_called()
|
||||
# cancel_pending sollte zurückgesetzt sein
|
||||
assert pc._cancel_pending is False
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 9: on_connected set_status remains sync
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestOnConnectedSetStatusRemainsSync:
|
||||
"""Test 9: Legacy-Pfad _on_ddp_connected nutzt set_status (sync)."""
|
||||
|
||||
def test_on_connected_set_status_remains_sync(self):
|
||||
"""_on_ddp_connected ruft ddp.set_status('online') auf (sync)."""
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.set_status = MagicMock(return_value=True)
|
||||
adapter.ddp = mock_ddp
|
||||
adapter._presence_engine = None # Kein PresenceEngine
|
||||
|
||||
# Rufe _on_ddp_connected auf
|
||||
adapter._on_ddp_connected()
|
||||
|
||||
# set_status (sync) sollte aufgerufen worden sein
|
||||
mock_ddp.set_status.assert_called_once_with("online")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 10: Legacy timer set_status remains sync
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestLegacyTimerSetStatusRemainsSync:
|
||||
"""Test 10: _schedule_idle_timer nutzt set_status (sync)."""
|
||||
|
||||
def test_legacy_timer_set_status_remains_sync(self):
|
||||
"""Idle-Timer ruft ddp.set_status('away') auf (sync)."""
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.set_status = MagicMock(return_value=True)
|
||||
adapter.ddp = mock_ddp
|
||||
# Kein _presence_engine → idle timer wird aktiv
|
||||
adapter._presence_engine = None
|
||||
adapter._status_timer = None
|
||||
|
||||
# Rufe _schedule_idle_timer auf
|
||||
adapter._schedule_idle_timer()
|
||||
|
||||
# Timer sollte gestartet sein
|
||||
assert adapter._status_timer is not None
|
||||
|
||||
# Führe die Timer-Callback manuell aus
|
||||
# (die innere _set_away-Funktion)
|
||||
adapter._status_timer.cancel()
|
||||
# Simuliere: Timer feuert
|
||||
if adapter.ddp:
|
||||
adapter.ddp.set_status("away")
|
||||
|
||||
mock_ddp.set_status.assert_called_with("away")
|
||||
@@ -0,0 +1,363 @@
|
||||
"""
|
||||
V8.6: install.sh --update-only Tests (TDD: RED first).
|
||||
|
||||
Testet die neuen --update-only Features:
|
||||
1. __pycache__-Löschung VOR dem Kopieren
|
||||
2. __pycache__-Löschung NACH dem Kopieren
|
||||
3. systemctl --user restart hermes-gateway
|
||||
4. Post-Deployment-Verifikation (journalctl)
|
||||
5. Idempotenz
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Hilfsfunktionen
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
INSTALL_SH = Path(__file__).resolve().parents[1] / "install.sh"
|
||||
|
||||
|
||||
def _read_install_sh() -> str:
|
||||
"""Liest install.sh komplett ein."""
|
||||
return INSTALL_SH.read_text()
|
||||
|
||||
|
||||
def _extract_update_only_section(content: str) -> str:
|
||||
"""Extrahiert den --update-only Block aus install.sh."""
|
||||
# Der Block beginnt bei 'if $UPDATE_ONLY; then' und endet bei 'fi' vor dem Hauptfluss
|
||||
match = re.search(
|
||||
r'if \$UPDATE_ONLY; then.*?(?=\nfi\n\n# 1\. System-Dependencies|\nfi\n\nexit 0)',
|
||||
content,
|
||||
re.DOTALL,
|
||||
)
|
||||
if match:
|
||||
return match.group(0)
|
||||
return ""
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 1: Syntax-Check
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestInstallShSyntax:
|
||||
"""install.sh muss bash -n bestehen."""
|
||||
|
||||
def test_bash_syntax_ok(self):
|
||||
"""bash -n findet keine Syntax-Fehler."""
|
||||
if not INSTALL_SH.exists():
|
||||
pytest.skip("install.sh nicht gefunden")
|
||||
result = subprocess.run(
|
||||
["bash", "-n", str(INSTALL_SH)],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
assert result.returncode == 0, (
|
||||
f"bash -n failed:\n{result.stderr}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 2: __pycache__-Löschung VOR dem Kopieren
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestUpdateOnlyCacheCleanupBefore:
|
||||
"""__pycache__ muss VOR dem Kopieren gelöscht werden."""
|
||||
|
||||
def test_find_pycache_delete_before_copy(self):
|
||||
"""Der find-Befehl für __pycache__ erscheint VOR dem Kopier-Befehl."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# Suche nach __pycache__-Löschung
|
||||
assert "find" in update_section, (
|
||||
f"Kein find-Befehl im --update-only Block:\n{update_section}"
|
||||
)
|
||||
assert "__pycache__" in update_section, (
|
||||
f"Kein __pycache__-Bezug im --update-only Block:\n{update_section}"
|
||||
)
|
||||
|
||||
# Die erste __pycache__-Löschung muss VOR deploy_plugin kommen
|
||||
first_pycache_pos = update_section.find("__pycache__")
|
||||
deploy_pos = update_section.find("deploy_plugin")
|
||||
assert first_pycache_pos < deploy_pos, (
|
||||
f"__pycache__-Löschung ({first_pycache_pos}) muss VOR deploy_plugin ({deploy_pos}) kommen"
|
||||
)
|
||||
|
||||
def test_pycache_delete_uses_rm_rf(self):
|
||||
"""__pycache__-Löschung nutzt rm -rf."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# Mindestens ein find ... -exec rm -rf ... für __pycache__
|
||||
assert re.search(
|
||||
r"find.*__pycache__.*rm\s+-rf",
|
||||
update_section,
|
||||
), (
|
||||
f"Kein 'find ... __pycache__ ... rm -rf' gefunden:\n{update_section}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 3: __pycache__-Löschung NACH dem Kopieren
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestUpdateOnlyCacheCleanupAfter:
|
||||
"""__pycache__ muss NACH dem Kopieren NOCHMAL gelöscht werden."""
|
||||
|
||||
def test_second_pycache_delete_after_copy(self):
|
||||
"""Zweite __pycache__-Löschung erscheint NACH deploy_plugin."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# deploy_plugin-Position
|
||||
deploy_pos = update_section.find("deploy_plugin")
|
||||
|
||||
# Zweites __pycache__-Vorkommen NACH deploy_plugin
|
||||
after_deploy = update_section[deploy_pos:]
|
||||
assert "__pycache__" in after_deploy, (
|
||||
f"Keine __pycache__-Löschung NACH deploy_plugin:\n{after_deploy}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 4: systemctl --user restart hermes-gateway
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestUpdateOnlyServiceRestart:
|
||||
"""Gateway-Dienst muss nach dem Update neu gestartet werden."""
|
||||
|
||||
def test_systemctl_restart_present(self):
|
||||
"""systemctl --user restart hermes-gateway ist im --update-only Block."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "systemctl --user restart hermes-gateway" in update_section, (
|
||||
f"systemctl restart fehlt im --update-only Block:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_no_restart_flag_respected(self):
|
||||
"""--no-restart Flag überspringt den Neustart."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# --no-restart muss im Block behandelt werden
|
||||
assert "NO_RESTART" in update_section, (
|
||||
f"NO_RESTART-Flag wird nicht im --update-only Block behandelt:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_restart_after_deploy(self):
|
||||
"""systemctl restart kommt NACH deploy_plugin."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
deploy_pos = update_section.find("deploy_plugin")
|
||||
restart_pos = update_section.find("systemctl --user restart hermes-gateway")
|
||||
|
||||
assert restart_pos > deploy_pos, (
|
||||
f"restart ({restart_pos}) muss NACH deploy_plugin ({deploy_pos}) kommen"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 5: Post-Deployment-Verifikation
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestUpdateOnlyPostDeployVerification:
|
||||
"""Nach dem Deployment muss das Log verifiziert werden."""
|
||||
|
||||
def test_journalctl_presence_check(self):
|
||||
"""journalctl prüft auf 'PresenceEngine' oder 'presence'."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# Muss journalctl mit PresenceEngine/presence-Suche enthalten
|
||||
assert "journalctl" in update_section, (
|
||||
f"journalctl fehlt im --update-only Block:\n{update_section}"
|
||||
)
|
||||
assert re.search(
|
||||
r"[Pp]resence(?:Engine)?",
|
||||
update_section,
|
||||
), (
|
||||
f"Keine PresenceEngine/presence-Prüfung im --update-only Block:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_journalctl_archivar_check(self):
|
||||
"""journalctl prüft auf 'Archivar initialisiert'."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "Archivar initialisiert" in update_section, (
|
||||
f"'Archivar initialisiert'-Check fehlt im --update-only Block:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_journalctl_connected_check(self):
|
||||
"""journalctl prüft auf 'Connected to'."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "Connected to" in update_section, (
|
||||
f"'Connected to'-Check fehlt im --update-only Block:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_verification_errors_are_fatal(self):
|
||||
"""Fehlende Log-Einträge führen zu ERROR (nicht stillschweigend)."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# Muss err() oder die() oder exit 1 bei Fehlern enthalten
|
||||
assert re.search(
|
||||
r'(err|die|exit\s+1)',
|
||||
update_section,
|
||||
), (
|
||||
f"Keine Fehlerbehandlung (err/die/exit 1) bei Verifikation:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_retry_loop_present(self):
|
||||
"""Verifikation nutzt Retry-Schleife mit bis zu 3 Versuchen."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "_check_attempt" in update_section, (
|
||||
f"Keine _check_attempt Variable (Retry-Schleife) im --update-only Block:\n{update_section}"
|
||||
)
|
||||
assert "for _check_attempt in 1 2 3" in update_section, (
|
||||
f"Keine 'for _check_attempt in 1 2 3' Schleife:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_precise_timestamp(self):
|
||||
"""journalctl nutzt präzisen Zeitstempel statt '2 minutes ago'."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "_verify_since" in update_section, (
|
||||
f"Keine _verify_since Variable (präziser Zeitstempel):\n{update_section}"
|
||||
)
|
||||
assert "date '+%Y-%m-%d %H:%M:%S'" in update_section, (
|
||||
f"Kein date-Aufruf für präzisen Zeitstempel:\n{update_section}"
|
||||
)
|
||||
# Darf KEIN '2 minutes ago' mehr enthalten
|
||||
assert "2 minutes ago" not in update_section, (
|
||||
f"'2 minutes ago' noch im --update-only Block (sollte durch _verify_since ersetzt sein):\n{update_section}"
|
||||
)
|
||||
|
||||
def test_no_pager_flag(self):
|
||||
"""journalctl nutzt --no-pager für zuverlässige Ausgabe."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "--no-pager" in update_section, (
|
||||
f"Kein --no-pager Flag bei journalctl:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_sleep_12_seconds(self):
|
||||
"""Initialer Sleep ist 12s (nicht 8s)."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "sleep 12" in update_section, (
|
||||
f"Kein 'sleep 12' im --update-only Block:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_hit_count_output(self):
|
||||
"""Jede Prüfung gibt Treffer-Anzahl aus (nicht nur 'NICHT gefunden')."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# Mindestens 3 Treffer-Ausgaben (eine pro Check)
|
||||
assert update_section.count("Treffer") >= 3, (
|
||||
f"Weniger als 3 'Treffer'-Ausgaben (sollte pro Check eine sein):\n{update_section}"
|
||||
)
|
||||
|
||||
def test_retry_wait_message(self):
|
||||
"""Zwischen Retry-Versuchen wird 'Warte 5s' ausgegeben."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "Warte 5s" in update_section, (
|
||||
f"Keine 'Warte 5s'-Meldung zwischen Retry-Versuchen:\n{update_section}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 6: Idempotenz
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestUpdateOnlyIdempotency:
|
||||
"""--update-only muss mehrfach ohne Side-Effects ausführbar sein."""
|
||||
|
||||
def test_no_state_mutation_outside_plugin_dir(self):
|
||||
"""--update-only ändert NUR das Plugin-Verzeichnis + Gateway-Status."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# Darf KEINE config.yaml, .env, room-map.json, SOUL.md schreiben
|
||||
forbidden = ["config.yaml", ".env", "room-map.json", "SOUL.md"]
|
||||
for pattern in forbidden:
|
||||
assert pattern not in update_section, (
|
||||
f"--update-only darf '{pattern}' nicht anfassen:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_git_pull_before_deploy(self):
|
||||
"""git pull kommt VOR deploy_plugin."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
git_pull_pos = update_section.find("git pull")
|
||||
deploy_pos = update_section.find("deploy_plugin")
|
||||
|
||||
assert git_pull_pos < deploy_pos, (
|
||||
f"git pull ({git_pull_pos}) muss VOR deploy_plugin ({deploy_pos}) kommen"
|
||||
)
|
||||
|
||||
def test_dry_run_supported(self):
|
||||
"""--update-only respektiert --dry-run."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# DRY_RUN muss im Block referenziert werden
|
||||
assert "DRY_RUN" in update_section or "$DRY_RUN" in update_section, (
|
||||
f"DRY_RUN wird nicht im --update-only Block behandelt:\n{update_section}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 7: deploy_plugin hat bereits __pycache__-Cleanup (bestehend)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestDeployPluginCacheCleanup:
|
||||
"""deploy_plugin() muss ebenfalls __pycache__ bereinigen."""
|
||||
|
||||
def test_deploy_plugin_has_pycache_cleanup(self):
|
||||
"""deploy_plugin() enthält __pycache__-Löschung."""
|
||||
content = _read_install_sh()
|
||||
|
||||
# Extrahiere deploy_plugin()-Funktion
|
||||
match = re.search(
|
||||
r'deploy_plugin\(\)\s*\{.*?(?=\n\}\n\n#)',
|
||||
content,
|
||||
re.DOTALL,
|
||||
)
|
||||
assert match, "deploy_plugin()-Funktion nicht gefunden"
|
||||
|
||||
func_body = match.group(0)
|
||||
assert "__pycache__" in func_body, (
|
||||
f"deploy_plugin() enthält keine __pycache__-Bereinigung:\n{func_body[:500]}"
|
||||
)
|
||||
assert "rm -rf" in func_body, (
|
||||
f"deploy_plugin() nutzt kein rm -rf für __pycache__:\n{func_body[:500]}"
|
||||
)
|
||||
Reference in New Issue
Block a user