Compare commits
24 Commits
3d842b745d
..
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 |
@@ -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
|
||||||
|
========================================================================
|
||||||
@@ -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.*
|
||||||
+117
-3
@@ -1234,7 +1234,8 @@ if $CHECK_ONLY; then
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
if $UPDATE_ONLY; then
|
if $UPDATE_ONLY; then
|
||||||
# P1-9: Update-Only — Plugin-Code aktualisieren (git pull) + deployen.
|
# 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.
|
# Keine Konfigurationsänderungen, keine System-Dependencies, keine Secrets.
|
||||||
banner "Update-Only (Plugin-Code aktualisieren)"
|
banner "Update-Only (Plugin-Code aktualisieren)"
|
||||||
|
|
||||||
@@ -1256,19 +1257,132 @@ if $UPDATE_ONLY; then
|
|||||||
PIPX_VENV="$(find_pipx_venv 2>/dev/null)" \
|
PIPX_VENV="$(find_pipx_venv 2>/dev/null)" \
|
||||||
|| die "pipx-venv nicht gefunden — vorher Normal-Install ausführen"
|
|| die "pipx-venv nicht gefunden — vorher Normal-Install ausführen"
|
||||||
VENV_PY="$PIPX_VENV/bin/python"
|
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
|
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
|
if ! $DRY_RUN; then
|
||||||
systemctl --user daemon-reload 2>/dev/null || true
|
systemctl --user daemon-reload 2>/dev/null || true
|
||||||
rm -f "$HOME/.hermes/gateway_state.json" "$HOME/.hermes/gateway.lock" 2>/dev/null || true
|
rm -f "$HOME/.hermes/gateway_state.json" "$HOME/.hermes/gateway.lock" 2>/dev/null || true
|
||||||
systemctl --user reset-failed hermes-gateway 2>/dev/null || true
|
systemctl --user reset-failed hermes-gateway 2>/dev/null || true
|
||||||
# P1-9(c): --no-restart überspringt den Gateway-Neustart
|
|
||||||
if $NO_RESTART; then
|
if $NO_RESTART; then
|
||||||
ok "Gateway-Neustart übersprungen (--no-restart)"
|
ok "Gateway-Neustart übersprungen (--no-restart)"
|
||||||
else
|
else
|
||||||
|
log "Starte Gateway neu..."
|
||||||
systemctl --user restart hermes-gateway 2>/dev/null || true
|
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
|
||||||
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
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|||||||
+385
-22
@@ -9,6 +9,7 @@ Zero external dependencies — stdlib only.
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
|
import concurrent.futures
|
||||||
import contextvars
|
import contextvars
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
@@ -50,6 +51,9 @@ if _MULTIROOM():
|
|||||||
from archivar.routing_counter import routing_counter
|
from archivar.routing_counter import routing_counter
|
||||||
from archivar.routing_telemetry import routing_telemetry
|
from archivar.routing_telemetry import routing_telemetry
|
||||||
|
|
||||||
|
# P0: Reply-Quote-Stripping — verhindert Fehl-Routing durch zitierte Parent-Nachrichten
|
||||||
|
from archivar.reply_quote_stripper import strip_reply_quote_for_routing
|
||||||
|
|
||||||
# ── Access __init__ symbols (plugin loaded as flat module, no relative imports) ──
|
# ── Access __init__ symbols (plugin loaded as flat module, no relative imports) ──
|
||||||
import sys as _sys
|
import sys as _sys
|
||||||
_init_module = _sys.modules.get('rocketchat')
|
_init_module = _sys.modules.get('rocketchat')
|
||||||
@@ -267,6 +271,24 @@ class RocketChatREST:
|
|||||||
return bool(r and r.get("success"))
|
return bool(r and r.get("success"))
|
||||||
|
|
||||||
|
|
||||||
|
class DDPTimeout(Exception):
|
||||||
|
"""Raised when a DDP method call times out waiting for a result message."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class DDPServerError(Exception):
|
||||||
|
"""Raised when the DDP server returns an error for a method call."""
|
||||||
|
|
||||||
|
def __init__(self, error_data: dict):
|
||||||
|
self.error_data = error_data
|
||||||
|
super().__init__(f"DDP server error: {error_data}")
|
||||||
|
|
||||||
|
|
||||||
|
class DDPNotConnected(Exception):
|
||||||
|
"""Raised when a DDP method is called but the client is not connected."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class DDPClient:
|
class DDPClient:
|
||||||
PING_INTERVAL = 8.0
|
PING_INTERVAL = 8.0
|
||||||
|
|
||||||
@@ -287,6 +309,11 @@ class DDPClient:
|
|||||||
self._session: Optional[str] = None
|
self._session: Optional[str] = None
|
||||||
self._reconnect_attempt = 0
|
self._reconnect_attempt = 0
|
||||||
self._last_rx_time = 0.0
|
self._last_rx_time = 0.0
|
||||||
|
# P1-2 O-2: Future-Store für await-Semantik
|
||||||
|
self._pending_results: Dict[str, concurrent.futures.Future] = {}
|
||||||
|
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||||
|
self._result_lock = threading.Lock()
|
||||||
|
self._msg_seq: int = 0
|
||||||
|
|
||||||
def _create_socket(self) -> socket.socket:
|
def _create_socket(self) -> socket.socket:
|
||||||
ctx = ssl.create_default_context()
|
ctx = ssl.create_default_context()
|
||||||
@@ -344,6 +371,7 @@ class DDPClient:
|
|||||||
import select
|
import select
|
||||||
self.sock.settimeout(1.0)
|
self.sock.settimeout(1.0)
|
||||||
last_ping = time.time()
|
last_ping = time.time()
|
||||||
|
last_sweep = time.time()
|
||||||
while self._running:
|
while self._running:
|
||||||
try:
|
try:
|
||||||
if time.time() - last_ping >= self.PING_INTERVAL:
|
if time.time() - last_ping >= self.PING_INTERVAL:
|
||||||
@@ -352,6 +380,10 @@ class DDPClient:
|
|||||||
last_ping = time.time()
|
last_ping = time.time()
|
||||||
except Exception:
|
except Exception:
|
||||||
break
|
break
|
||||||
|
# P1-2 O-2: Periodic sweep of stale pending results (every 5s)
|
||||||
|
if time.time() - last_sweep >= 5.0:
|
||||||
|
self._sweep_pending_results()
|
||||||
|
last_sweep = time.time()
|
||||||
readable, _, _ = select.select([self.sock], [], [], 1.0)
|
readable, _, _ = select.select([self.sock], [], [], 1.0)
|
||||||
if not readable:
|
if not readable:
|
||||||
continue
|
continue
|
||||||
@@ -393,6 +425,15 @@ class DDPClient:
|
|||||||
self._on_connected()
|
self._on_connected()
|
||||||
elif msg_type == "ping":
|
elif msg_type == "ping":
|
||||||
self._send_json({"msg": "pong"})
|
self._send_json({"msg": "pong"})
|
||||||
|
# P1-2 O-2: Handle DDP result messages (resolve pending Futures)
|
||||||
|
elif msg_type == "result":
|
||||||
|
self._handle_result_message(data)
|
||||||
|
# P1-2 O-2: Handle DDP updated messages (log only, result follows)
|
||||||
|
elif msg_type == "updated":
|
||||||
|
logger.debug(
|
||||||
|
"DDP: updated message received (id=%s)",
|
||||||
|
data.get("id", "?"),
|
||||||
|
)
|
||||||
elif msg_type in ("changed", "added") and data.get("collection") == "stream-room-messages":
|
elif msg_type in ("changed", "added") and data.get("collection") == "stream-room-messages":
|
||||||
fields = data.get("fields", {})
|
fields = data.get("fields", {})
|
||||||
args = fields.get("args", [])
|
args = fields.get("args", [])
|
||||||
@@ -538,13 +579,171 @@ class DDPClient:
|
|||||||
room_id[:12], event["name"], event["type"])
|
room_id[:12], event["name"], event["type"])
|
||||||
self._on_room_event(event)
|
self._on_room_event(event)
|
||||||
|
|
||||||
|
def _handle_result_message(self, data: dict) -> None:
|
||||||
|
"""P1-2 O-2: Resolve pending Futures when a DDP result message arrives.
|
||||||
|
|
||||||
|
Called from the reader thread (PURE SYNC — no asyncio calls here).
|
||||||
|
Looks up the msg_id in _pending_results and resolves the Future
|
||||||
|
with the result or error.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
data: The parsed DDP JSON message with msg='result'.
|
||||||
|
"""
|
||||||
|
msg_id = data.get("id", "")
|
||||||
|
if not msg_id:
|
||||||
|
return
|
||||||
|
|
||||||
|
with self._result_lock:
|
||||||
|
future = self._pending_results.pop(msg_id, None)
|
||||||
|
|
||||||
|
if future is None:
|
||||||
|
# No pending future for this msg_id — likely a result for
|
||||||
|
# a fire-and-forget call (legacy set_status) or already timed out
|
||||||
|
return
|
||||||
|
|
||||||
|
if future.done():
|
||||||
|
# Already resolved (e.g., by timeout sweep)
|
||||||
|
return
|
||||||
|
|
||||||
|
if "error" in data:
|
||||||
|
future.set_exception(DDPServerError(data["error"]))
|
||||||
|
else:
|
||||||
|
future.set_result(data.get("result", True))
|
||||||
|
|
||||||
def set_status(self, status: str) -> bool:
|
def set_status(self, status: str) -> bool:
|
||||||
|
"""Set the user presence status via DDP (fire-and-forget, no await).
|
||||||
|
|
||||||
|
.. deprecated::
|
||||||
|
Use :meth:`set_status_async` for await-semantics with timeout
|
||||||
|
and error handling. This method remains for legacy callers
|
||||||
|
(on_connected callback, idle timer) that don't need the result.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if the frame was sent, False if not connected.
|
||||||
|
"""
|
||||||
if not self.connected:
|
if not self.connected:
|
||||||
return False
|
return False
|
||||||
method = f"UserPresence:{status}"
|
method = "UserPresence:setDefaultStatus"
|
||||||
self._send_json({"msg": "method", "method": method, "params": [], "id": f"st{int(time.time()*1000)}"})
|
self._send_json({"msg": "method", "method": method, "params": [status], "id": f"st{int(time.time()*1000)}"})
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
def bind_loop(self, loop: asyncio.AbstractEventLoop) -> None:
|
||||||
|
"""Bind the asyncio event loop for async operations.
|
||||||
|
|
||||||
|
Called by the adapter after the event loop is running.
|
||||||
|
The loop reference is used by set_status_async to bridge
|
||||||
|
between the DDP reader thread and the asyncio world.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
loop: The running asyncio event loop.
|
||||||
|
"""
|
||||||
|
self._loop = loop
|
||||||
|
|
||||||
|
async def set_status_async(self, status: str, timeout: float = 2.0) -> bool:
|
||||||
|
"""Set the user presence status via DDP with await-semantics.
|
||||||
|
|
||||||
|
Sends a DDP method call and waits for the corresponding result
|
||||||
|
message from the server. Uses a Future registered in
|
||||||
|
_pending_results that the reader thread resolves when the
|
||||||
|
result message arrives.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
status: Rocket.Chat status ('online', 'away', 'busy').
|
||||||
|
timeout: Maximum seconds to wait for the result (default 2.0).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if the server confirmed the status change.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
DDPNotConnected: If the DDP client is not connected.
|
||||||
|
DDPTimeout: If no result message arrives within timeout.
|
||||||
|
DDPServerError: If the server returns an error for the call.
|
||||||
|
"""
|
||||||
|
if not self.connected:
|
||||||
|
raise DDPNotConnected("DDP client is not connected")
|
||||||
|
|
||||||
|
# Generate unique msg_id with sequence counter to prevent collisions
|
||||||
|
with self._result_lock:
|
||||||
|
self._msg_seq += 1
|
||||||
|
msg_id = f"st{int(time.time() * 1000)}_{self._msg_seq}"
|
||||||
|
|
||||||
|
# Create Future and register it
|
||||||
|
future: concurrent.futures.Future = concurrent.futures.Future()
|
||||||
|
with self._result_lock:
|
||||||
|
self._pending_results[msg_id] = future
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Send the DDP method call
|
||||||
|
method = "UserPresence:setDefaultStatus"
|
||||||
|
self._send_json({
|
||||||
|
"msg": "method",
|
||||||
|
"method": method,
|
||||||
|
"params": [status],
|
||||||
|
"id": msg_id,
|
||||||
|
})
|
||||||
|
|
||||||
|
# Await the future — bridge concurrent.Future to asyncio with timeout
|
||||||
|
result = await asyncio.wait_for(
|
||||||
|
asyncio.wrap_future(future),
|
||||||
|
timeout=timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
# If we get here, the reader thread resolved the future
|
||||||
|
if result is False:
|
||||||
|
raise DDPServerError({"error": "server returned false"})
|
||||||
|
return True
|
||||||
|
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
# Clean up the pending future
|
||||||
|
with self._result_lock:
|
||||||
|
self._pending_results.pop(msg_id, None)
|
||||||
|
raise DDPTimeout(
|
||||||
|
f"setDefaultStatus('{status}') timed out after {timeout}s"
|
||||||
|
)
|
||||||
|
except (DDPTimeout, DDPServerError, DDPNotConnected):
|
||||||
|
# Re-raise our own exceptions without wrapping
|
||||||
|
with self._result_lock:
|
||||||
|
self._pending_results.pop(msg_id, None)
|
||||||
|
raise
|
||||||
|
except Exception:
|
||||||
|
# Clean up on any other exception
|
||||||
|
with self._result_lock:
|
||||||
|
self._pending_results.pop(msg_id, None)
|
||||||
|
raise
|
||||||
|
|
||||||
|
def _sweep_pending_results(self) -> None:
|
||||||
|
"""Sweep through _pending_results and cancel Futures older than 2s.
|
||||||
|
|
||||||
|
Called periodically from the reader loop to prevent memory leaks
|
||||||
|
from method calls whose result messages never arrive.
|
||||||
|
"""
|
||||||
|
now = time.time()
|
||||||
|
stale_ids = []
|
||||||
|
with self._result_lock:
|
||||||
|
for msg_id, future in list(self._pending_results.items()):
|
||||||
|
# msg_id format: st<TIMESTAMP_MS>_<SEQ>
|
||||||
|
# Extract timestamp from msg_id
|
||||||
|
try:
|
||||||
|
ts_part = msg_id[2:].split("_")[0] # strip 'st' prefix
|
||||||
|
ts_ms = int(ts_part)
|
||||||
|
ts_s = ts_ms / 1000.0
|
||||||
|
if now - ts_s > 2.0:
|
||||||
|
stale_ids.append(msg_id)
|
||||||
|
except (ValueError, IndexError):
|
||||||
|
# Malformed msg_id — clean it up
|
||||||
|
stale_ids.append(msg_id)
|
||||||
|
|
||||||
|
for msg_id in stale_ids:
|
||||||
|
future = self._pending_results.pop(msg_id, None)
|
||||||
|
if future is not None and not future.done():
|
||||||
|
future.cancel()
|
||||||
|
|
||||||
|
if stale_ids:
|
||||||
|
logger.debug(
|
||||||
|
"DDP: Swept %d stale pending results (age > 2s)",
|
||||||
|
len(stale_ids),
|
||||||
|
)
|
||||||
|
|
||||||
def disconnect(self):
|
def disconnect(self):
|
||||||
self._running = False
|
self._running = False
|
||||||
if self.sock:
|
if self.sock:
|
||||||
@@ -800,16 +999,36 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self._register_inline_commands()
|
self._register_inline_commands()
|
||||||
|
|
||||||
# V8.6: PresenceEngine — Aktivitäts-Indikator
|
# V8.6: PresenceEngine — Aktivitäts-Indikator
|
||||||
|
try:
|
||||||
from archivar.presence_engine import PresenceEngine
|
from archivar.presence_engine import PresenceEngine
|
||||||
_presence_enabled = os.getenv("ROCKETCHAT_PRESENCE_ENABLED", "true").strip().lower() not in ("false", "0", "no", "off")
|
_presence_enabled = os.getenv("ROCKETCHAT_PRESENCE_ENABLED", "true").strip().lower() not in ("false", "0", "no", "off")
|
||||||
_coalesce_ms = int(os.getenv("ROCKETCHAT_PRESENCE_COALESCE_MS", "2000"))
|
_coalesce_ms = int(os.getenv("ROCKETCHAT_PRESENCE_COALESCE_MS", "2000"))
|
||||||
_pulse_interval = int(os.getenv("ROCKETCHAT_PRESENCE_PULSE_INTERVAL", "10"))
|
_pulse_interval = float(os.getenv("ROCKETCHAT_PRESENCE_PULSE_INTERVAL", "1.5"))
|
||||||
self._presence_engine = PresenceEngine(
|
self._presence_engine = PresenceEngine(
|
||||||
rest=self.rest,
|
rest=self.rest,
|
||||||
enabled=_presence_enabled,
|
enabled=_presence_enabled,
|
||||||
coalesce_ms=_coalesce_ms,
|
coalesce_ms=_coalesce_ms,
|
||||||
pulse_interval=_pulse_interval,
|
pulse_interval=_pulse_interval,
|
||||||
)
|
)
|
||||||
|
# P0-1: PulseController mit REST und DDP verdrahten
|
||||||
|
self._presence_engine._pulse_controller.bind_rest(self.rest)
|
||||||
|
if self.ddp:
|
||||||
|
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||||||
|
# P2-2: PresenceEngine an ArchivarMessageHandler weiterreichen
|
||||||
|
if self.archivar is not None:
|
||||||
|
self.archivar.set_presence_engine(self._presence_engine)
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] V8.6: PresenceEngine initialisiert (enabled=%s, coalesce_ms=%s, pulse_interval=%.1fs)",
|
||||||
|
_presence_enabled,
|
||||||
|
_coalesce_ms,
|
||||||
|
_pulse_interval,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(
|
||||||
|
"[rocketchat] V8.6: PresenceEngine-Initialisierung FEHLGESCHLAGEN: %s",
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
self._presence_engine = None # Graceful degradation -> alter Idle-Timer greift
|
||||||
|
|
||||||
def _build_room_map_summary(self) -> str:
|
def _build_room_map_summary(self) -> str:
|
||||||
"""Baut eine menschenlesbare Raum-Map-Übersicht für den System-Prompt.
|
"""Baut eine menschenlesbare Raum-Map-Übersicht für den System-Prompt.
|
||||||
@@ -844,6 +1063,22 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
lines.append(f" Keywords Kontext: {kwctx}")
|
lines.append(f" Keywords Kontext: {kwctx}")
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
def _on_ddp_connected(self) -> None:
|
||||||
|
"""Callback when DDP connection is established.
|
||||||
|
|
||||||
|
Sets initial online status and binds DDP to PulseController
|
||||||
|
if PresenceEngine is active (EC-1: on_connected_cb race).
|
||||||
|
"""
|
||||||
|
if self.ddp:
|
||||||
|
self.ddp.set_status("online")
|
||||||
|
# V8.6: PulseController DDP-Bindung nach Connect (EC-1)
|
||||||
|
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||||
|
try:
|
||||||
|
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||||||
|
logger.debug("[rocketchat] V8.6: PulseController DDP gebunden (on_connected_cb)")
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug("[rocketchat] V8.6: PulseController bind_ddp failed: %s", e)
|
||||||
|
|
||||||
def _on_ddp_room_event(self, event: dict) -> None:
|
def _on_ddp_room_event(self, event: dict) -> None:
|
||||||
"""A1b: Callback für DDP rooms-changed Events.
|
"""A1b: Callback für DDP rooms-changed Events.
|
||||||
|
|
||||||
@@ -1202,7 +1437,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
||||||
self.ddp = DDPClient(
|
self.ddp = DDPClient(
|
||||||
host=host,
|
host=host,
|
||||||
on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None,
|
on_connected_cb=self._on_ddp_connected,
|
||||||
on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events
|
on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events
|
||||||
)
|
)
|
||||||
if not self.ddp.connect_and_login(self._auth_token):
|
if not self.ddp.connect_and_login(self._auth_token):
|
||||||
@@ -1211,6 +1446,24 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self._rooms = self.rest.get_rooms()
|
self._rooms = self.rest.get_rooms()
|
||||||
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
|
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
|
||||||
|
|
||||||
|
# P1-2 O-2: Bind asyncio loop to DDPClient and PulseController
|
||||||
|
try:
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
self.ddp.bind_loop(loop)
|
||||||
|
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||||
|
self._presence_engine._pulse_controller.bind_loop(loop)
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: yes "
|
||||||
|
"(loop=%s)",
|
||||||
|
id(loop),
|
||||||
|
)
|
||||||
|
except RuntimeError:
|
||||||
|
# No running event loop (e.g., in tests) — graceful degradation
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: no "
|
||||||
|
"(no running event loop)"
|
||||||
|
)
|
||||||
|
|
||||||
# A1b: Subscribe to stream-notify-room for rooms-changed events
|
# A1b: Subscribe to stream-notify-room for rooms-changed events
|
||||||
if self.ddp.connected:
|
if self.ddp.connected:
|
||||||
room_events_sub = self.ddp.subscribe_room_events()
|
room_events_sub = self.ddp.subscribe_room_events()
|
||||||
@@ -1435,13 +1688,30 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
||||||
self.ddp = DDPClient(
|
self.ddp = DDPClient(
|
||||||
host=host,
|
host=host,
|
||||||
on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None,
|
on_connected_cb=self._on_ddp_connected,
|
||||||
on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events (P0-3)
|
on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events (P0-3)
|
||||||
)
|
)
|
||||||
if not self.ddp.connect_and_login(self._auth_token):
|
if not self.ddp.connect_and_login(self._auth_token):
|
||||||
logger.error("[rocketchat] _reconnect_ddp: DDP connect/login failed")
|
logger.error("[rocketchat] _reconnect_ddp: DDP connect/login failed")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
# P1-2 O-2: Re-bind asyncio loop to new DDPClient and PulseController
|
||||||
|
try:
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
self.ddp.bind_loop(loop)
|
||||||
|
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||||
|
self._presence_engine._pulse_controller.bind_loop(loop)
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: yes "
|
||||||
|
"(reconnect, loop=%s)",
|
||||||
|
id(loop),
|
||||||
|
)
|
||||||
|
except RuntimeError:
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: no "
|
||||||
|
"(reconnect, no running event loop)"
|
||||||
|
)
|
||||||
|
|
||||||
# A1b: Re-subscribe to stream-notify-room for rooms-changed events (P0-3)
|
# A1b: Re-subscribe to stream-notify-room for rooms-changed events (P0-3)
|
||||||
if self.ddp.connected:
|
if self.ddp.connected:
|
||||||
room_events_sub = self.ddp.subscribe_room_events()
|
room_events_sub = self.ddp.subscribe_room_events()
|
||||||
@@ -1588,6 +1858,27 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
text = file_info_text
|
text = file_info_text
|
||||||
msg_obj["msg"] = text
|
msg_obj["msg"] = text
|
||||||
|
|
||||||
|
# ── P0+P1: Reply-Quote-Stripping ──────────────────────────────────
|
||||||
|
# Verhindert Fehl-Routing durch zitierte Parent-Nachrichten.
|
||||||
|
# Zweistufig defensiv:
|
||||||
|
# 1. Attachments-basiert (Rocket.Chat Reply-Attachments)
|
||||||
|
# 2. Text-basiert (Markdown-Blockquotes, [quote]-Blöcke)
|
||||||
|
# routing_text (ohne Quote) → Archivar/Keyword-Matcher/classify_and_route
|
||||||
|
# display_text (mit Quote) → Agent-Dispatch + Conversation-History
|
||||||
|
routing_text, display_text, quote_stripped = strip_reply_quote_for_routing(
|
||||||
|
text, attachments
|
||||||
|
)
|
||||||
|
if quote_stripped:
|
||||||
|
routing_counter.increment('reply_quote_stripped')
|
||||||
|
logger.debug(
|
||||||
|
"[rocketchat] P0: Reply-Quote gestrippt — "
|
||||||
|
"routing_text=%s, display_text=%s",
|
||||||
|
routing_text[:80], display_text[:80],
|
||||||
|
)
|
||||||
|
# text bleibt display_text für Agent/History;
|
||||||
|
# routing_text wird für Archivar-Klassifikation verwendet.
|
||||||
|
# ── Ende P0+P1 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
# Skip own messages (case-insensitive comparison)
|
# Skip own messages (case-insensitive comparison)
|
||||||
filter_match = (username == (self.user or "").lower())
|
filter_match = (username == (self.user or "").lower())
|
||||||
logger.debug("Filter check: username=%s, self.user=%s, match=%s", username, self.user, filter_match)
|
logger.debug("Filter check: username=%s, self.user=%s, match=%s", username, self.user, filter_match)
|
||||||
@@ -1627,7 +1918,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ──
|
# ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ──
|
||||||
# ::-Befehle und natürliche Hilfeseiten-Anfragen müssen VOR dem
|
# ::-Befehle und natürliche Hilfeseiten-Anfragen müssen VOR dem
|
||||||
# generischen Hermes-Agent-Onboarding erkannt werden.
|
# generischen Hermes-Agent-Onboarding erkannt werden.
|
||||||
inline_handled = await self._handle_inline_command(text, room_id, room_name, username)
|
inline_handled = await self._handle_inline_command(routing_text, room_id, room_name, username)
|
||||||
if inline_handled:
|
if inline_handled:
|
||||||
logger.debug("[rocketchat] R5: Inline-Command verarbeitet — skipping agent dispatch")
|
logger.debug("[rocketchat] R5: Inline-Command verarbeitet — skipping agent dispatch")
|
||||||
routing_counter.increment('inline_command_handled')
|
routing_counter.increment('inline_command_handled')
|
||||||
@@ -1636,13 +1927,15 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# ── Ende R5 Inline-Command-Erkennung ────────────────────────────────
|
# ── Ende R5 Inline-Command-Erkennung ────────────────────────────────
|
||||||
|
|
||||||
# ── B5v6.5: Conversation History — User-Nachricht aufzeichnen ──
|
# ── B5v6.5: Conversation History — User-Nachricht aufzeichnen ──
|
||||||
|
# P1: display_text (mit Quote) für Agent/History, damit kein Kontext verloren geht
|
||||||
if _MULTIROOM() and self._conversation_history is not None:
|
if _MULTIROOM() and self._conversation_history is not None:
|
||||||
await self._conversation_history.add(room_id, "user", text)
|
await self._conversation_history.add(room_id, "user", display_text)
|
||||||
|
|
||||||
# V8.1 P4: MultiRoomContext-Ring — Thema aus Nachricht extrahieren
|
# V8.1 P4: MultiRoomContext-Ring — Thema aus Nachricht extrahieren
|
||||||
if _MULTIROOM() and self._multiroom_context is not None:
|
if _MULTIROOM() and self._multiroom_context is not None:
|
||||||
# Extrahiere ein kurzes Topic aus der Nachricht (erste 80 Zeichen)
|
# Extrahiere ein kurzes Topic aus der Nachricht (erste 80 Zeichen)
|
||||||
topic = text[:80].replace("\n", " ").strip()
|
# P1: routing_text für Topic-Extraktion (ohne Quote)
|
||||||
|
topic = routing_text[:80].replace("\n", " ").strip()
|
||||||
if topic:
|
if topic:
|
||||||
await self._multiroom_context.add(room_id, room_name, topic)
|
await self._multiroom_context.add(room_id, room_name, topic)
|
||||||
|
|
||||||
@@ -1968,7 +2261,16 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# V8.2.1 A2: Nachklärung bei stay_once — Strategie-Buttons senden
|
# V8.2.1 A2: Nachklärung bei stay_once — Strategie-Buttons senden
|
||||||
if _MULTIROOM() and self.archivar is not None:
|
if _MULTIROOM() and self.archivar is not None:
|
||||||
if self.archivar._should_trigger_nachklaerung("stay_once"):
|
if self.archivar._should_trigger_nachklaerung("stay_once"):
|
||||||
nachklaerung_buttons = self.archivar._get_nachklaerung_buttons()
|
# Keywords des Zielraums als lesbaren Text einbauen
|
||||||
|
target_room_id = move_req.get("target_room", "")
|
||||||
|
target_keywords = []
|
||||||
|
if target_room_id and self.archivar._room_map is not None:
|
||||||
|
target_entry = self.archivar._room_map.rooms.get(target_room_id)
|
||||||
|
if target_entry:
|
||||||
|
target_keywords = target_entry.keywords_100[:5]
|
||||||
|
nachklaerung_buttons = self.archivar._get_nachklaerung_buttons(
|
||||||
|
keywords=target_keywords if target_keywords else None
|
||||||
|
)
|
||||||
await self._send_archivar_buttons(
|
await self._send_archivar_buttons(
|
||||||
room_id,
|
room_id,
|
||||||
nachklaerung_buttons["text"],
|
nachklaerung_buttons["text"],
|
||||||
@@ -2131,7 +2433,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
del self._recent_auto_routes[room_id]
|
del self._recent_auto_routes[room_id]
|
||||||
# Dispatch im Ursprungsraum
|
# Dispatch im Ursprungsraum
|
||||||
await self._dispatch_agent(
|
await self._dispatch_agent(
|
||||||
text=text,
|
text=display_text,
|
||||||
room_id=room_id,
|
room_id=room_id,
|
||||||
room_name=room_name,
|
room_name=room_name,
|
||||||
room_type=room_type,
|
room_type=room_type,
|
||||||
@@ -2231,7 +2533,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
target_room_name_disp = target_room_info.get("name", target_room_display)
|
target_room_name_disp = target_room_info.get("name", target_room_display)
|
||||||
target_room_type = target_room_info.get("type", "c")
|
target_room_type = target_room_info.get("type", "c")
|
||||||
await self._dispatch_agent(
|
await self._dispatch_agent(
|
||||||
text=text,
|
text=display_text,
|
||||||
room_id=target_room_id,
|
room_id=target_room_id,
|
||||||
room_name=target_room_name_disp,
|
room_name=target_room_name_disp,
|
||||||
room_type=target_room_type,
|
room_type=target_room_type,
|
||||||
@@ -2249,7 +2551,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# Nur die Nachricht selbst wird — nach User-Entscheidung — kopiert.
|
# Nur die Nachricht selbst wird — nach User-Entscheidung — kopiert.
|
||||||
category = ""
|
category = ""
|
||||||
decision = None
|
decision = None
|
||||||
is_auftrag = _is_auftrag(text)
|
is_auftrag = _is_auftrag(routing_text)
|
||||||
|
|
||||||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Entering Archivar block — room_type=%s, is_auftrag=%s, _MULTIROOM=%s, archivar=%s", room_type, is_auftrag, _MULTIROOM(), self.archivar is not None)
|
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Entering Archivar block — room_type=%s, is_auftrag=%s, _MULTIROOM=%s, archivar=%s", room_type, is_auftrag, _MULTIROOM(), self.archivar is not None)
|
||||||
|
|
||||||
@@ -2363,7 +2665,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
)
|
)
|
||||||
routing_telemetry.flush()
|
routing_telemetry.flush()
|
||||||
# Kopiere Nachricht in den Zielraum
|
# Kopiere Nachricht in den Zielraum
|
||||||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{text}"
|
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||||||
|
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}"
|
||||||
await self._post_message_with_retry(target_room_id, target_txt)
|
await self._post_message_with_retry(target_room_id, target_txt)
|
||||||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||||||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||||||
@@ -2371,7 +2674,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
logger.info(
|
logger.info(
|
||||||
"[rocketchat] V8.3-5: Topic-Scoped Sticky active — "
|
"[rocketchat] V8.3-5: Topic-Scoped Sticky active — "
|
||||||
"auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
|
"auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
|
||||||
text[:80], target_name, sticky_topic,
|
display_text[:80], target_name, sticky_topic,
|
||||||
pref["expires_at"] - time.time(),
|
pref["expires_at"] - time.time(),
|
||||||
)
|
)
|
||||||
# Dispatch direkt — kein Archivar
|
# Dispatch direkt — kein Archivar
|
||||||
@@ -2379,7 +2682,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
target_room_name = target_room_info.get("name", target_name)
|
target_room_name = target_room_info.get("name", target_name)
|
||||||
target_room_type = target_room_info.get("type", "c")
|
target_room_type = target_room_info.get("type", "c")
|
||||||
await self._dispatch_agent(
|
await self._dispatch_agent(
|
||||||
text=text,
|
text=display_text,
|
||||||
room_id=target_room_id,
|
room_id=target_room_id,
|
||||||
room_name=target_room_name,
|
room_name=target_room_name,
|
||||||
room_type=target_room_type,
|
room_type=target_room_type,
|
||||||
@@ -2407,7 +2710,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
duration_ms=0.0,
|
duration_ms=0.0,
|
||||||
)
|
)
|
||||||
routing_telemetry.flush()
|
routing_telemetry.flush()
|
||||||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{text}"
|
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||||||
|
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}"
|
||||||
await self._post_message_with_retry(target_room_id, target_txt)
|
await self._post_message_with_retry(target_room_id, target_txt)
|
||||||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||||||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||||||
@@ -2415,7 +2719,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
logger.info(
|
logger.info(
|
||||||
"[rocketchat] V8.3-5: Topic-Scoped Sticky active — "
|
"[rocketchat] V8.3-5: Topic-Scoped Sticky active — "
|
||||||
"auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
|
"auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
|
||||||
text[:80], target_name, sticky_topic,
|
display_text[:80], target_name, sticky_topic,
|
||||||
pref["expires_at"] - time.time(),
|
pref["expires_at"] - time.time(),
|
||||||
)
|
)
|
||||||
# Dispatch direkt — kein Archivar
|
# Dispatch direkt — kein Archivar
|
||||||
@@ -2423,7 +2727,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
target_room_name = target_room_info.get("name", target_name)
|
target_room_name = target_room_info.get("name", target_name)
|
||||||
target_room_type = target_room_info.get("type", "c")
|
target_room_type = target_room_info.get("type", "c")
|
||||||
await self._dispatch_agent(
|
await self._dispatch_agent(
|
||||||
text=text,
|
text=display_text,
|
||||||
room_id=target_room_id,
|
room_id=target_room_id,
|
||||||
room_name=target_room_name,
|
room_name=target_room_name,
|
||||||
room_type=target_room_type,
|
room_type=target_room_type,
|
||||||
@@ -2453,7 +2757,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# P0-FIX: is_dm=True bei DMs — der Router braucht das für den DM-Guard.
|
# P0-FIX: is_dm=True bei DMs — der Router braucht das für den DM-Guard.
|
||||||
# room_type wird in L1579 aus self._room_info gelesen.
|
# room_type wird in L1579 aus self._room_info gelesen.
|
||||||
_is_dm = (room_type == "d")
|
_is_dm = (room_type == "d")
|
||||||
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id, is_dm=_is_dm)
|
# P0: routing_text (ohne Quote) für Klassifikation verwenden
|
||||||
|
decision = await self.archivar.classify_and_route(routing_text, origin_room_id=room_id, is_dm=_is_dm)
|
||||||
# V8.3.3: Telemetrie nach jeder Routing-Entscheidung flushen
|
# V8.3.3: Telemetrie nach jeder Routing-Entscheidung flushen
|
||||||
routing_telemetry.flush()
|
routing_telemetry.flush()
|
||||||
if decision and decision.category:
|
if decision and decision.category:
|
||||||
@@ -2483,7 +2788,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
and hasattr(decision, 'target_room')
|
and hasattr(decision, 'target_room')
|
||||||
and decision.target_room):
|
and decision.target_room):
|
||||||
self._pending_move_requests[room_id] = {
|
self._pending_move_requests[room_id] = {
|
||||||
'text': text,
|
# P1: display_text (mit Quote) für Move-Request speichern
|
||||||
|
'text': display_text,
|
||||||
'origin_room': room_id,
|
'origin_room': room_id,
|
||||||
'target_room': decision.target_room,
|
'target_room': decision.target_room,
|
||||||
'target_name': getattr(
|
'target_name': getattr(
|
||||||
@@ -2575,7 +2881,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
room_id[:8],
|
room_id[:8],
|
||||||
)
|
)
|
||||||
# Kopiere Nachricht in den Zielraum
|
# Kopiere Nachricht in den Zielraum
|
||||||
target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{text}"
|
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||||||
|
target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{display_text}"
|
||||||
target_message_id = await self._post_message_with_retry(target_room_id, target_txt)
|
target_message_id = await self._post_message_with_retry(target_room_id, target_txt)
|
||||||
# Setze _CURRENT_ORIGIN_ROOM auf Zielraum → Agent antwortet dort
|
# Setze _CURRENT_ORIGIN_ROOM auf Zielraum → Agent antwortet dort
|
||||||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||||||
@@ -2585,7 +2892,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
logger.info(
|
logger.info(
|
||||||
"[rocketchat] V8.1 P1: Auto-Route '%s' → %s — "
|
"[rocketchat] V8.1 P1: Auto-Route '%s' → %s — "
|
||||||
"Agent dispatched in target room",
|
"Agent dispatched in target room",
|
||||||
text[:80], target_name,
|
display_text[:80], target_name,
|
||||||
)
|
)
|
||||||
# V8.1.1 R2: Ring-GC bei Auto-Route — stale Topics aus Ursprungsraum entfernen
|
# V8.1.1 R2: Ring-GC bei Auto-Route — stale Topics aus Ursprungsraum entfernen
|
||||||
if _MULTIROOM() and self._multiroom_context is not None:
|
if _MULTIROOM() and self._multiroom_context is not None:
|
||||||
@@ -3097,9 +3404,20 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
async def _cmd_hilfe(self, room_id: str, args: str) -> str:
|
async def _cmd_hilfe(self, room_id: str, args: str) -> str:
|
||||||
"""::hilfe — Zeigt die Hilfeseite mit allen Befehlen."""
|
"""::hilfe — Zeigt die Hilfeseite mit allen Befehlen."""
|
||||||
from archivar.inline_commands import build_help_text
|
from archivar.inline_commands import build_help_text
|
||||||
|
|
||||||
|
# P1-4: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||||||
|
presence_enabled = None
|
||||||
|
current_status = "online"
|
||||||
|
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||||
|
if _has_presence:
|
||||||
|
presence_enabled = self._presence_engine.is_enabled()
|
||||||
|
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
|
||||||
|
|
||||||
return build_help_text(
|
return build_help_text(
|
||||||
self._inline_commands,
|
self._inline_commands,
|
||||||
room_map_summary=self._room_map_summary,
|
room_map_summary=self._room_map_summary,
|
||||||
|
presence_enabled=presence_enabled,
|
||||||
|
current_status=current_status,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def _cmd_status(self, room_id: str, args: str) -> str:
|
async def _cmd_status(self, room_id: str, args: str) -> str:
|
||||||
@@ -3119,12 +3437,25 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
butler_mode = getattr(room_map, 'butler_mode', 'unknown')
|
butler_mode = getattr(room_map, 'butler_mode', 'unknown')
|
||||||
onboarding_active = self.archivar._stats.get("onboarding_active", False)
|
onboarding_active = self.archivar._stats.get("onboarding_active", False)
|
||||||
|
|
||||||
|
# P1-4: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||||||
|
presence_enabled = None
|
||||||
|
current_status = "online"
|
||||||
|
pulse_active = False
|
||||||
|
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||||
|
if _has_presence:
|
||||||
|
presence_enabled = self._presence_engine.is_enabled()
|
||||||
|
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
|
||||||
|
pulse_active = self._presence_engine._pulse_controller.is_running()
|
||||||
|
|
||||||
return build_status_text(
|
return build_status_text(
|
||||||
room_count=room_count,
|
room_count=room_count,
|
||||||
archivar_active=archivar_active,
|
archivar_active=archivar_active,
|
||||||
butler_mode=butler_mode,
|
butler_mode=butler_mode,
|
||||||
onboarding_active=onboarding_active,
|
onboarding_active=onboarding_active,
|
||||||
room_map_summary=self._room_map_summary,
|
room_map_summary=self._room_map_summary,
|
||||||
|
presence_enabled=presence_enabled,
|
||||||
|
current_status=current_status,
|
||||||
|
pulse_active=pulse_active,
|
||||||
)
|
)
|
||||||
|
|
||||||
async def _cmd_reset(self, room_id: str, args: str) -> str:
|
async def _cmd_reset(self, room_id: str, args: str) -> str:
|
||||||
@@ -3484,11 +3815,19 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
|
|
||||||
if subcmd in ("on", "an", "ein", "enable", "start"):
|
if subcmd in ("on", "an", "ein", "enable", "start"):
|
||||||
self._presence_engine.enable()
|
self._presence_engine.enable()
|
||||||
|
# P0-3: ::setstatus on → PulseController aktivieren
|
||||||
|
if hasattr(self._presence_engine, '_pulse_controller'):
|
||||||
|
self._presence_engine._pulse_controller.bind_rest(self.rest)
|
||||||
|
if self.ddp:
|
||||||
|
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||||||
logger.info("[rocketchat] V8.6: ::setstatus on — PresenceEngine aktiviert")
|
logger.info("[rocketchat] V8.6: ::setstatus on — PresenceEngine aktiviert")
|
||||||
return "🟢 **Aktivitäts-Indikator: AN**\n\nDer Bot zeigt jetzt seinen Status automatisch an (online/busy/away)."
|
return "🟢 **Aktivitäts-Indikator: AN**\n\nDer Bot zeigt jetzt seinen Status automatisch an (online/busy/away)."
|
||||||
|
|
||||||
elif subcmd in ("off", "aus", "disable", "stop"):
|
elif subcmd in ("off", "aus", "disable", "stop"):
|
||||||
self._presence_engine.disable()
|
self._presence_engine.disable()
|
||||||
|
# P0-3: ::setstatus off → PulseController stoppen
|
||||||
|
if hasattr(self._presence_engine, '_pulse_controller'):
|
||||||
|
self._presence_engine._pulse_controller.stop()
|
||||||
logger.info("[rocketchat] V8.6: ::setstatus off — PresenceEngine deaktiviert")
|
logger.info("[rocketchat] V8.6: ::setstatus off — PresenceEngine deaktiviert")
|
||||||
return "🔴 **Aktivitäts-Indikator: AUS**\n\nDer Bot-Status bleibt auf 'online'. Keine automatischen Status-Wechsel."
|
return "🔴 **Aktivitäts-Indikator: AUS**\n\nDer Bot-Status bleibt auf 'online'. Keine automatischen Status-Wechsel."
|
||||||
|
|
||||||
@@ -4033,6 +4372,20 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
"actions": buttons,
|
"actions": buttons,
|
||||||
}]
|
}]
|
||||||
|
|
||||||
|
# Split buttons into groups of max 3 per attachment (UX: mobile readability)
|
||||||
|
MAX_BUTTONS_PER_ROW = 3
|
||||||
|
if len(buttons) > MAX_BUTTONS_PER_ROW:
|
||||||
|
attachments = []
|
||||||
|
for i in range(0, len(buttons), MAX_BUTTONS_PER_ROW):
|
||||||
|
chunk = buttons[i:i + MAX_BUTTONS_PER_ROW]
|
||||||
|
attachments.append({
|
||||||
|
"color": "#1d74f5",
|
||||||
|
"actions": chunk,
|
||||||
|
})
|
||||||
|
# First attachment gets the title
|
||||||
|
if attachments:
|
||||||
|
attachments[0]["title"] = text
|
||||||
|
|
||||||
success = await self._post_message_with_retry(room_id, text, attachments=attachments)
|
success = await self._post_message_with_retry(room_id, text, attachments=attachments)
|
||||||
if success is not None:
|
if success is not None:
|
||||||
# Mark room so the response stays here (no Archivar routing)
|
# Mark room so the response stays here (no Archivar routing)
|
||||||
@@ -4224,6 +4577,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if _MULTIROOM() and self.archivar is not None:
|
if _MULTIROOM() and self.archivar is not None:
|
||||||
self.archivar._stats["onboarding_active"] = True
|
self.archivar._stats["onboarding_active"] = True
|
||||||
# ── V8.6: PresenceEngine — Onboarding start → away ──
|
# ── V8.6: PresenceEngine — Onboarding start → away ──
|
||||||
|
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||||
|
if _has_presence:
|
||||||
self._presence_engine.set_onboarding_active(True)
|
self._presence_engine.set_onboarding_active(True)
|
||||||
self._presence_engine.update_presence()
|
self._presence_engine.update_presence()
|
||||||
|
|
||||||
@@ -5769,6 +6124,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self.archivar._state.clear_onboarding_state()
|
self.archivar._state.clear_onboarding_state()
|
||||||
self._onboarding_state = {}
|
self._onboarding_state = {}
|
||||||
# ── V8.6: PresenceEngine — Onboarding end → online ──
|
# ── V8.6: PresenceEngine — Onboarding end → online ──
|
||||||
|
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||||
|
if _has_presence:
|
||||||
self._presence_engine.set_onboarding_active(False)
|
self._presence_engine.set_onboarding_active(False)
|
||||||
self._presence_engine.update_presence()
|
self._presence_engine.update_presence()
|
||||||
# F8: State Machine — AWAITING_TEST → ACTIVE
|
# F8: State Machine — AWAITING_TEST → ACTIVE
|
||||||
@@ -5907,6 +6264,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
block = f"\n\n[FILE CONTENT: {fname}]\n{content[:10000]}\n[/FILE]"
|
block = f"\n\n[FILE CONTENT: {fname}]\n{content[:10000]}\n[/FILE]"
|
||||||
text += block
|
text += block
|
||||||
logger.debug("[rocketchat] Inlined file %s (%d chars)", fname, len(block))
|
logger.debug("[rocketchat] Inlined file %s (%d chars)", fname, len(block))
|
||||||
|
# P2-1: Alle übrigen [FILE]-Blöcke entfernen (fehlgeschlagene Downloads)
|
||||||
|
# Non-greedy Pattern: erfasst [FILE]...Download:... bis zum nächsten \n
|
||||||
|
# re.DOTALL damit Zeilenumbrüche innerhalb des Blocks matchen
|
||||||
|
text = re.sub(
|
||||||
|
r'\[FILE\].*?Download:[^\n]+\n?', '', text, flags=re.DOTALL
|
||||||
|
)
|
||||||
return text
|
return text
|
||||||
|
|
||||||
async def disconnect(self) -> None:
|
async def disconnect(self) -> None:
|
||||||
|
|||||||
@@ -133,6 +133,7 @@ class ArchivarMessageHandler:
|
|||||||
"""
|
"""
|
||||||
self._send_callback = send_callback
|
self._send_callback = send_callback
|
||||||
self._button_send_callback = button_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"]
|
self._enable_llm = LLM_CONFIG["enabled"]
|
||||||
|
|
||||||
# Create LLM client if enabled and not provided
|
# Create LLM client if enabled and not provided
|
||||||
@@ -549,6 +550,8 @@ class ArchivarMessageHandler:
|
|||||||
|
|
||||||
Button-Garantie: REST-Pfad first, Text-Fallback nur bei Fehler.
|
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:
|
Args:
|
||||||
room_id: Zielraum-ID
|
room_id: Zielraum-ID
|
||||||
text: Originalnachricht
|
text: Originalnachricht
|
||||||
@@ -557,6 +560,11 @@ class ArchivarMessageHandler:
|
|||||||
Returns:
|
Returns:
|
||||||
True wenn erfolgreich gesendet, False bei Fehler
|
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:
|
try:
|
||||||
# Hole Button-Template
|
# Hole Button-Template
|
||||||
template = BUTTON_TEMPLATES.get("clarify_intent", {})
|
template = BUTTON_TEMPLATES.get("clarify_intent", {})
|
||||||
@@ -608,6 +616,11 @@ class ArchivarMessageHandler:
|
|||||||
self._stats["errors"] += 1
|
self._stats["errors"] += 1
|
||||||
self._stats["last_error"] = str(e)
|
self._stats["last_error"] = str(e)
|
||||||
return False
|
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:
|
async def _send_move_request(self, room_id: str, text: str, decision: RoutingDecision) -> bool:
|
||||||
"""Sende einen Move-Request-Button (Butler-Prinzip).
|
"""Sende einen Move-Request-Button (Butler-Prinzip).
|
||||||
@@ -1164,6 +1177,14 @@ class ArchivarMessageHandler:
|
|||||||
self._button_send_callback = callback
|
self._button_send_callback = callback
|
||||||
logger.debug("Button send callback registered")
|
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:
|
def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None:
|
||||||
"""Set the bot's current subscribed room IDs for routing validation.
|
"""Set the bot's current subscribed room IDs for routing validation.
|
||||||
|
|
||||||
@@ -1223,14 +1244,23 @@ class ArchivarMessageHandler:
|
|||||||
strategie_topics = {"absprache", "planung", "strategie", "entscheidung"}
|
strategie_topics = {"absprache", "planung", "strategie", "entscheidung"}
|
||||||
return topic.lower().strip() in strategie_topics
|
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.
|
"""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:
|
Returns:
|
||||||
Button-Template mit Strategie-Optionen.
|
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 {
|
return {
|
||||||
"text": "Ist es eines dieser Themen?",
|
"text": text,
|
||||||
"actions": [
|
"actions": [
|
||||||
{"text": "🤝 Absprache", "type": "absprache"},
|
{"text": "🤝 Absprache", "type": "absprache"},
|
||||||
{"text": "📋 Planung", "type": "planung"},
|
{"text": "📋 Planung", "type": "planung"},
|
||||||
|
|||||||
@@ -211,12 +211,19 @@ class InlineCommandRegistry:
|
|||||||
# ── Help-Text-Generator ─────────────────────────────────────────────────
|
# ── 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.
|
"""Baut die Hilfeseite mit ::-Befehlen und natürlichen Sprach-Befehlen.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
registry: Die InlineCommandRegistry mit allen registrierten Befehlen.
|
registry: Die InlineCommandRegistry mit allen registrierten Befehlen.
|
||||||
room_map_summary: Optionale Raum-Map-Übersicht für den Status-Teil.
|
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:
|
Returns:
|
||||||
Formatierte Hilfeseite als Markdown-String.
|
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("### 📋 Plugin-Status")
|
||||||
lines.append("")
|
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:
|
if room_map_summary:
|
||||||
lines.append(room_map_summary)
|
lines.append(room_map_summary)
|
||||||
else:
|
else:
|
||||||
@@ -314,6 +341,9 @@ def build_status_text(
|
|||||||
butler_mode: str = "unknown",
|
butler_mode: str = "unknown",
|
||||||
onboarding_active: bool = False,
|
onboarding_active: bool = False,
|
||||||
room_map_summary: str = "",
|
room_map_summary: str = "",
|
||||||
|
presence_enabled: Optional[bool] = None,
|
||||||
|
current_status: str = "online",
|
||||||
|
pulse_active: bool = False,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""Baut die Status-Seite mit aktuellen Plugin-Informationen.
|
"""Baut die Status-Seite mit aktuellen Plugin-Informationen.
|
||||||
|
|
||||||
@@ -323,6 +353,9 @@ def build_status_text(
|
|||||||
butler_mode: Butler-Modus ('cognitive', 'strict', 'off').
|
butler_mode: Butler-Modus ('cognitive', 'strict', 'off').
|
||||||
onboarding_active: Ob Onboarding gerade läuft.
|
onboarding_active: Ob Onboarding gerade läuft.
|
||||||
room_map_summary: Raum-Map-Übersicht.
|
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:
|
Returns:
|
||||||
Formatierte Status-Seite.
|
Formatierte Status-Seite.
|
||||||
@@ -342,6 +375,21 @@ def build_status_text(
|
|||||||
f"- **Onboarding:** {'🔄 Läuft' if onboarding_active else '✅ Abgeschlossen'}",
|
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:
|
if room_map_summary:
|
||||||
lines.append("")
|
lines.append("")
|
||||||
lines.append(room_map_summary)
|
lines.append(room_map_summary)
|
||||||
|
|||||||
+617
-110
@@ -9,14 +9,16 @@ Zero external dependencies — stdlib only.
|
|||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import subprocess
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
import urllib.request
|
import urllib.request
|
||||||
import urllib.error
|
import urllib.error
|
||||||
from typing import Optional, Dict
|
from typing import Optional, Dict, Callable
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
# Ensure presence_engine logs are visible in journalctl by adding a stderr handler
|
# Ensure presence_engine logs are visible in journalctl by adding a stderr handler
|
||||||
@@ -58,6 +60,8 @@ def _format_presence_message(
|
|||||||
return "Onboarding läuft"
|
return "Onboarding läuft"
|
||||||
elif status == "away_move_request":
|
elif status == "away_move_request":
|
||||||
return f"Wartet auf Bestätigung in {room_name}" if room_name else "Wartet auf Bestätigung"
|
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":
|
elif status == "away_error":
|
||||||
return f"⚠️ Fehler: {error}" if error else "⚠️ Fehler"
|
return f"⚠️ Fehler: {error}" if error else "⚠️ Fehler"
|
||||||
elif status == "heartbeat":
|
elif status == "heartbeat":
|
||||||
@@ -83,7 +87,8 @@ class PresenceEngine:
|
|||||||
rest=None,
|
rest=None,
|
||||||
enabled: bool = True,
|
enabled: bool = True,
|
||||||
coalesce_ms: int = 2000,
|
coalesce_ms: int = 2000,
|
||||||
pulse_interval: float = 10,
|
pulse_interval: float = 1.5,
|
||||||
|
gateway_state_path: str = "",
|
||||||
_clamp_pulse: bool = True,
|
_clamp_pulse: bool = True,
|
||||||
):
|
):
|
||||||
"""Initialize the PresenceEngine.
|
"""Initialize the PresenceEngine.
|
||||||
@@ -92,8 +97,10 @@ class PresenceEngine:
|
|||||||
rest: RocketChatREST instance for API calls.
|
rest: RocketChatREST instance for API calls.
|
||||||
enabled: Whether presence updates are enabled.
|
enabled: Whether presence updates are enabled.
|
||||||
coalesce_ms: Coalesce delay in milliseconds (default 2000).
|
coalesce_ms: Coalesce delay in milliseconds (default 2000).
|
||||||
pulse_interval: Heartbeat pulse interval in seconds (5-30, default 10).
|
pulse_interval: PulseController interval in seconds (0.5-30, default 1.5).
|
||||||
_clamp_pulse: If True, clamp pulse_interval to 5-30. Set False for testing.
|
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._rest = rest
|
||||||
self._enabled = enabled
|
self._enabled = enabled
|
||||||
@@ -120,19 +127,32 @@ class PresenceEngine:
|
|||||||
self._move_request_pending: Dict[str, str] = {} # room_id → room_name
|
self._move_request_pending: Dict[str, str] = {} # room_id → room_name
|
||||||
self._error_state: Optional[str] = None
|
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
|
# Current room name for busy messages
|
||||||
self._current_room_name: str = ""
|
self._current_room_name: str = ""
|
||||||
|
|
||||||
# Heartbeat
|
# Background tasks counter (for display + PulseController coordination)
|
||||||
if _clamp_pulse:
|
|
||||||
self._pulse_interval: float = max(5.0, min(30.0, float(pulse_interval)))
|
|
||||||
else:
|
|
||||||
self._pulse_interval: float = float(pulse_interval)
|
|
||||||
self._background_tasks: int = 0
|
self._background_tasks: int = 0
|
||||||
self._background_tasks_lock = threading.Lock()
|
self._background_tasks_lock = threading.Lock()
|
||||||
self._heartbeat_thread: Optional[threading.Thread] = None
|
|
||||||
self._heartbeat_running = threading.Event()
|
# P0-1: PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s)
|
||||||
self._heartbeat_phase: bool = False # False=online, True=away
|
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 ───────────────────────────────────────────────────────
|
# ── Public API ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -141,14 +161,16 @@ class PresenceEngine:
|
|||||||
return self._enabled
|
return self._enabled
|
||||||
|
|
||||||
def enable(self) -> None:
|
def enable(self) -> None:
|
||||||
"""Enable presence updates."""
|
"""Enable presence updates. Starts DetectionTimer."""
|
||||||
self._enabled = True
|
self._enabled = True
|
||||||
|
self._detection_timer.start()
|
||||||
logger.info("[presence] PresenceEngine enabled")
|
logger.info("[presence] PresenceEngine enabled")
|
||||||
|
|
||||||
def disable(self) -> None:
|
def disable(self) -> None:
|
||||||
"""Disable presence updates. Stops heartbeat if running."""
|
"""Disable presence updates. Stops PulseController and DetectionTimer."""
|
||||||
self._enabled = False
|
self._enabled = False
|
||||||
self._stop_heartbeat()
|
self._pulse_controller.stop()
|
||||||
|
self._detection_timer.stop()
|
||||||
logger.info("[presence] PresenceEngine disabled")
|
logger.info("[presence] PresenceEngine disabled")
|
||||||
|
|
||||||
def increment_active_tasks(self) -> int:
|
def increment_active_tasks(self) -> int:
|
||||||
@@ -170,7 +192,14 @@ class PresenceEngine:
|
|||||||
with self._active_tasks_lock:
|
with self._active_tasks_lock:
|
||||||
if self._active_tasks > 0:
|
if self._active_tasks > 0:
|
||||||
self._active_tasks -= 1
|
self._active_tasks -= 1
|
||||||
return self._active_tasks
|
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:
|
def set_onboarding_active(self, active: bool) -> None:
|
||||||
"""Set the onboarding sentinel."""
|
"""Set the onboarding sentinel."""
|
||||||
@@ -184,6 +213,14 @@ class PresenceEngine:
|
|||||||
"""Clear a move request."""
|
"""Clear a move request."""
|
||||||
self._move_request_pending.pop(room_id, None)
|
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:
|
def set_error_state(self, error: Optional[str]) -> None:
|
||||||
"""Set or clear the error state."""
|
"""Set or clear the error state."""
|
||||||
self._error_state = error
|
self._error_state = error
|
||||||
@@ -201,7 +238,7 @@ class PresenceEngine:
|
|||||||
with self._background_tasks_lock:
|
with self._background_tasks_lock:
|
||||||
self._background_tasks += 1
|
self._background_tasks += 1
|
||||||
count = self._background_tasks
|
count = self._background_tasks
|
||||||
self._maybe_start_heartbeat()
|
self._pulse_controller.set_background_count(count)
|
||||||
return count
|
return count
|
||||||
|
|
||||||
def decrement_background_tasks(self) -> int:
|
def decrement_background_tasks(self) -> int:
|
||||||
@@ -214,8 +251,9 @@ class PresenceEngine:
|
|||||||
if self._background_tasks > 0:
|
if self._background_tasks > 0:
|
||||||
self._background_tasks -= 1
|
self._background_tasks -= 1
|
||||||
count = self._background_tasks
|
count = self._background_tasks
|
||||||
|
self._pulse_controller.set_background_count(count)
|
||||||
if count == 0:
|
if count == 0:
|
||||||
self._stop_heartbeat()
|
self._pulse_controller.stop()
|
||||||
return count
|
return count
|
||||||
|
|
||||||
# ── Internal: Presence Setting ───────────────────────────────────────
|
# ── Internal: Presence Setting ───────────────────────────────────────
|
||||||
@@ -233,6 +271,12 @@ class PresenceEngine:
|
|||||||
if not self._enabled:
|
if not self._enabled:
|
||||||
return
|
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:
|
with self._coalesce_lock:
|
||||||
self._pending_status = status
|
self._pending_status = status
|
||||||
self._pending_message = message
|
self._pending_message = message
|
||||||
@@ -311,102 +355,24 @@ class PresenceEngine:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning("[presence] Failed to set status: %s", e)
|
logger.warning("[presence] Failed to set status: %s", e)
|
||||||
|
|
||||||
# ── Heartbeat ────────────────────────────────────────────────────────
|
# ── DetectionTimer Callback ──────────────────────────────────────────
|
||||||
|
|
||||||
def _maybe_start_heartbeat(self) -> None:
|
def _on_detection_change(self, is_active: bool) -> None:
|
||||||
"""Start heartbeat if background_tasks > 0 and agent is idle.
|
"""Callback from DetectionTimer: start/stop PulseController.
|
||||||
|
|
||||||
P1-5: Hält beide Locks gleichzeitig um Race Condition zu vermeiden.
|
When background agents are detected (is_active=True), start pulsing.
|
||||||
|
When no background agents (is_active=False), stop pulsing.
|
||||||
"""
|
"""
|
||||||
if not self._enabled:
|
if not self._enabled:
|
||||||
return
|
return
|
||||||
# P1-5: Beide Locks gleichzeitig halten für konsistente Snapshot-Reads
|
if is_active:
|
||||||
with self._active_tasks_lock:
|
if not self._pulse_controller.is_running():
|
||||||
with self._background_tasks_lock:
|
self._pulse_controller.start()
|
||||||
is_idle = self._active_tasks == 0
|
logger.info("[presence] PulseController gestartet (Hintergrund-Agenten erkannt)")
|
||||||
has_background = self._background_tasks > 0
|
|
||||||
|
|
||||||
if has_background and is_idle and not self._heartbeat_running.is_set():
|
|
||||||
self._start_heartbeat()
|
|
||||||
|
|
||||||
def _start_heartbeat(self) -> None:
|
|
||||||
"""Start the heartbeat pulse thread."""
|
|
||||||
if not self._enabled:
|
|
||||||
return
|
|
||||||
if self._heartbeat_running.is_set():
|
|
||||||
return
|
|
||||||
|
|
||||||
self._heartbeat_running.set()
|
|
||||||
self._heartbeat_phase = False # Start with online
|
|
||||||
|
|
||||||
self._heartbeat_thread = threading.Thread(
|
|
||||||
target=self._heartbeat_loop,
|
|
||||||
daemon=True,
|
|
||||||
name="presence-heartbeat",
|
|
||||||
)
|
|
||||||
self._heartbeat_thread.start()
|
|
||||||
logger.info("[presence] Heartbeat started (interval=%ds)", self._pulse_interval)
|
|
||||||
|
|
||||||
def _stop_heartbeat(self) -> None:
|
|
||||||
"""Stop the heartbeat pulse thread."""
|
|
||||||
if not self._heartbeat_running.is_set():
|
|
||||||
return
|
|
||||||
|
|
||||||
self._heartbeat_running.clear()
|
|
||||||
|
|
||||||
# Wait for thread to finish (with timeout)
|
|
||||||
if self._heartbeat_thread is not None and self._heartbeat_thread.is_alive():
|
|
||||||
self._heartbeat_thread.join(timeout=self._pulse_interval + 1)
|
|
||||||
|
|
||||||
self._heartbeat_thread = None
|
|
||||||
logger.info("[presence] Heartbeat stopped")
|
|
||||||
|
|
||||||
def _heartbeat_loop(self) -> None:
|
|
||||||
"""Background thread: pulse between online and away.
|
|
||||||
|
|
||||||
P1-5: Hält beide Locks gleichzeitig für konsistente Snapshot-Reads.
|
|
||||||
"""
|
|
||||||
while self._heartbeat_running.is_set():
|
|
||||||
# P1-5: Beide Locks gleichzeitig halten
|
|
||||||
with self._background_tasks_lock:
|
|
||||||
with self._active_tasks_lock:
|
|
||||||
bg_count = self._background_tasks
|
|
||||||
is_idle = self._active_tasks == 0
|
|
||||||
|
|
||||||
if bg_count == 0:
|
|
||||||
# No more background tasks — stop
|
|
||||||
self._heartbeat_running.clear()
|
|
||||||
# Set back to online (bypass coalesce for immediate effect)
|
|
||||||
self._send_rest("online", "")
|
|
||||||
self._last_sent_status = "online"
|
|
||||||
self._last_sent_message = ""
|
|
||||||
break
|
|
||||||
|
|
||||||
if not is_idle:
|
|
||||||
# Agent is busy — stop pulsing, let busy status take over
|
|
||||||
self._heartbeat_running.clear()
|
|
||||||
break
|
|
||||||
|
|
||||||
# Toggle phase
|
|
||||||
self._heartbeat_phase = not self._heartbeat_phase
|
|
||||||
|
|
||||||
if self._heartbeat_phase:
|
|
||||||
# Away phase: show heartbeat message
|
|
||||||
msg = _format_presence_message("heartbeat", background_count=bg_count)
|
|
||||||
self._send_rest("away", msg)
|
|
||||||
self._last_sent_status = "away"
|
|
||||||
self._last_sent_message = msg
|
|
||||||
else:
|
else:
|
||||||
# Online phase: no message
|
if self._pulse_controller.is_running():
|
||||||
self._send_rest("online", "")
|
self._pulse_controller.stop()
|
||||||
self._last_sent_status = "online"
|
logger.info("[presence] PulseController gestoppt (keine Hintergrund-Agenten)")
|
||||||
self._last_sent_message = ""
|
|
||||||
|
|
||||||
# Sleep for pulse interval, checking running flag periodically
|
|
||||||
for _ in range(int(self._pulse_interval * 10)):
|
|
||||||
if not self._heartbeat_running.is_set():
|
|
||||||
break
|
|
||||||
time.sleep(0.1)
|
|
||||||
|
|
||||||
# ── Convenience: Determine and set appropriate presence ──────────────
|
# ── Convenience: Determine and set appropriate presence ──────────────
|
||||||
|
|
||||||
@@ -443,6 +409,12 @@ class PresenceEngine:
|
|||||||
self._set_presence("away", msg)
|
self._set_presence("away", msg)
|
||||||
return
|
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
|
# 4. Active tasks
|
||||||
with self._active_tasks_lock:
|
with self._active_tasks_lock:
|
||||||
active = self._active_tasks
|
active = self._active_tasks
|
||||||
@@ -454,9 +426,544 @@ class PresenceEngine:
|
|||||||
self._set_presence("online", "")
|
self._set_presence("online", "")
|
||||||
|
|
||||||
def shutdown(self) -> None:
|
def shutdown(self) -> None:
|
||||||
"""Clean shutdown: stop heartbeat, cancel coalesce timer."""
|
"""Clean shutdown: stop PulseController, DetectionTimer, cancel coalesce timer."""
|
||||||
self._stop_heartbeat()
|
self._pulse_controller.stop()
|
||||||
|
self._detection_timer.stop()
|
||||||
with self._coalesce_lock:
|
with self._coalesce_lock:
|
||||||
if self._coalesce_timer is not None:
|
if self._coalesce_timer is not None:
|
||||||
self._coalesce_timer.cancel()
|
self._coalesce_timer.cancel()
|
||||||
self._coalesce_timer = None
|
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
|
||||||
@@ -49,6 +49,9 @@ class RoutingTelemetry:
|
|||||||
self._enabled: bool = self._read_feature_flag()
|
self._enabled: bool = self._read_feature_flag()
|
||||||
self._records: List[Dict[str, object]] = []
|
self._records: List[Dict[str, object]] = []
|
||||||
self._start_time: float = 0.0
|
self._start_time: float = 0.0
|
||||||
|
# Heartbeat-Pulsierung Telemetrie
|
||||||
|
self.heartbeat_pulse: int = 0
|
||||||
|
self.heartbeat_detection: int = 0
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _read_feature_flag() -> bool:
|
def _read_feature_flag() -> bool:
|
||||||
|
|||||||
@@ -129,3 +129,74 @@ class TestDDPRoomEvents:
|
|||||||
|
|
||||||
client._handle_ddp_message(event_data)
|
client._handle_ddp_message(event_data)
|
||||||
assert len(received_events) == 0
|
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
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1092,3 +1092,142 @@ class TestCommandHandlersMocked:
|
|||||||
assert handler is not None
|
assert handler is not None
|
||||||
result = await handler("room1", "")
|
result = await handler("room1", "")
|
||||||
assert "hermes update" in result
|
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)
|
||||||
@@ -179,3 +179,274 @@ def test_room_map_summary_multiroom_disabled(mock_multiroom):
|
|||||||
assert summary == "", (
|
assert summary == "", (
|
||||||
f"Deaktiviertes Multiroom sollte leeren String zurückgeben, nicht:\n{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