Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5c22391287 | |||
| 54edbb57f7 | |||
| 1958a53f0e | |||
| e28c575169 |
@@ -0,0 +1,399 @@
|
|||||||
|
REVIEW — Test-Anpassung für test_03/05/06 an tatsächliches Bot-Verhalten
|
||||||
|
=========================================================================
|
||||||
|
Datum: 2026-07-29
|
||||||
|
Reviewer: Rainer (Architektur & Review)
|
||||||
|
Auftrag: Don's Befund: 3/6 Live-Tests FAILED auf .45 (HEAD 1086969)
|
||||||
|
Bezug-Commits: a6d426d (test_03), ee3bbf8 (test_05), 1086969 (test_06)
|
||||||
|
Quellen: room-map.json (Repo, Don committed), plugin/archivar/router.py,
|
||||||
|
plugin/archivar/keyword_matcher.py, plugin/adapter.py,
|
||||||
|
tests/live_rc/{test_03,test_05,test_06}.py
|
||||||
|
|
||||||
|
VORBEMERKUNG — Auftrag hat 2 falsche Prämissen
|
||||||
|
---------------------------------------------
|
||||||
|
Bevor ich Empfehlungen ableite, muss ich zwei Annahmen im Auftrag
|
||||||
|
korrigieren — sonst führen die Lösungsoptionen in die falsche Richtung:
|
||||||
|
|
||||||
|
(A) "router.py Z.1071: 'FIX C: 100% → kein Butler'"
|
||||||
|
FALSCH. Z.1071 in plugin/archivar/router.py gehört zu einem
|
||||||
|
RoutingDecision-Return (move_request_sent=False). Z.1071 in
|
||||||
|
plugin/adapter.py ist mitten in _is_auftrag. Die wirkliche Logik
|
||||||
|
"FIX C: 100% → Auto-Route" steht in router.py Z.1047-1075
|
||||||
|
(Keyword-Phase) und Z.1269-1287 (FAISS/LLM-Phase) — beides
|
||||||
|
Archivar/Router, nicht "router.py" im engeren Sinn. Das ändert
|
||||||
|
die Lösungs-Optionen NICHT, aber Don's Begründung "router.py
|
||||||
|
Z.1071" ist nicht zitierfähig.
|
||||||
|
|
||||||
|
(B) "Bertrand hat keinen Lese-Zugriff auf #Rocketchat-Plugin"
|
||||||
|
Möglicherweise korrekt, aber unscharf. channels.history mit HTTP
|
||||||
|
400 heisst nicht zwingend "kein Lese-Zugriff" — Rocket.Chat
|
||||||
|
liefert 400 auch bei fehlender Room-Subscription, fehlender
|
||||||
|
Berechtigung, oder ungültiger Message-ID. Empfehlung unten
|
||||||
|
fordert deshalb: (1) Bernd tatsächlich in den Raum einladen
|
||||||
|
UND (2) Test so umbauen, dass er die echte Copied-Message-
|
||||||
|
Verifikation gegen einen Raum fährt, in dem Bernd nachweislich
|
||||||
|
Mitglied ist — nicht stillschweigend auf einen Hilfsraum
|
||||||
|
ausweichen.
|
||||||
|
|
||||||
|
ZUSÄTZLICH: SSH zu .45 (Auftrag: ssh bernd@192.168.180.45) ist
|
||||||
|
von dieser Maschine aus nicht möglich (kein Key, kein Passwort
|
||||||
|
im Rainer-Profil). Ich analysiere rein auf Basis der
|
||||||
|
Repo-Stand-Daten. room-map.json ist im Repo committed und wird
|
||||||
|
als authoritative Quelle verwendet — Don hat sie mit dem
|
||||||
|
Setup synchron gehalten.
|
||||||
|
|
||||||
|
|
||||||
|
EXECUTIVE SUMMARY
|
||||||
|
-----------------
|
||||||
|
Befund Bewertung Empfehlung
|
||||||
|
------- --------- -----------------------------------------------
|
||||||
|
B-1 ARCH-BUG Echtes Root-Cause in keyword_matcher (Strategy-3
|
||||||
|
fuzzy matched "hermes"==="hermes" auf
|
||||||
|
keyword_100 "hermes-gateway"). Test 03 scheitert
|
||||||
|
wegen Code-Bug, nicht Test-Bug.
|
||||||
|
B-2 TEST Test 03 muss entweder (a) ein "neutrales"
|
||||||
|
Kontext-Keyword wählen oder (b) den Test
|
||||||
|
kippen auf catch_all oder expliziten
|
||||||
|
Direkt-Post in #Rocketchat-Plugin.
|
||||||
|
B-3 ENV Test 03 + 05 funktionieren nur, wenn der Bot
|
||||||
|
die user_id des Test-Users in der
|
||||||
|
subscribed_users hat und der Test-User im
|
||||||
|
jeweiligen Testraum Mitglied ist.
|
||||||
|
B-4 TEST Test 05 sollte als direkten LLM-Stream
|
||||||
|
gestartet werden (kein 100%-Keyword, das
|
||||||
|
Bot-Eigenantwort kappt).
|
||||||
|
B-5 TEST Test 06 sollte sequenzielle Last (3s Delay
|
||||||
|
zwischen Posts) verwenden, nicht parallel.
|
||||||
|
Interrupt-Recursion ist ein bekanntes
|
||||||
|
Core-Verhalten und im Test nicht
|
||||||
|
reproduzierbar isolierbar.
|
||||||
|
|
||||||
|
|
||||||
|
BEFUND B-1 — Architektur-Bug: keyword_matcher Strategy 3
|
||||||
|
=========================================================
|
||||||
|
Befund:
|
||||||
|
In plugin/archivar/keyword_matcher.py Z.300-315 matcht
|
||||||
|
Strategy 3 (Fuzzy/Levenshtein) das Keyword "hermes-gateway"
|
||||||
|
Wort-für-Wort gegen den Text "hermes deployment pipeline":
|
||||||
|
- kw_word = "hermes" (6 chars, ≥ MIN_FUZZY_LEN=5)
|
||||||
|
- text_word = "hermes" (in "hermes deployment pipeline")
|
||||||
|
- Levenshtein-Distanz = 0 → MATCH
|
||||||
|
Damit gibt is_100_percent_match() True zurück für
|
||||||
|
#Rocketchat-Plugin, obwohl "hermes" nur als
|
||||||
|
keywords_context-Eintrag und "hermes-gateway" als
|
||||||
|
keywords_100-Eintrag existiert.
|
||||||
|
|
||||||
|
Konsequenz:
|
||||||
|
Router trifft in Schritt 3 (Keyword-Phase) → is_100=True
|
||||||
|
→ move_request_sent=False (router.py Z.1071) → Auto-Route
|
||||||
|
→ Ankündigung "Das passt besser in #Rocketchat-Plugin —
|
||||||
|
ich bringe das Thema rüber" (adapter.py Z.1102, exakt die
|
||||||
|
82-Zeichen-Antwort die Don in test_05 sah).
|
||||||
|
Move-Request-Buttons werden NIE gesendet.
|
||||||
|
|
||||||
|
Bewertung: ROT — Das ist kein Test-Bug, sondern ein Bug im
|
||||||
|
Keyword-Matcher. Strategy 3 muss bei Multi-Wort-Keywords
|
||||||
|
verlangen, dass ALLE Keyword-Wörter im Text vorkommen, nicht
|
||||||
|
nur EINES.
|
||||||
|
|
||||||
|
Empfehlung (Priorität 1):
|
||||||
|
Archivar-Fix: keyword_matcher.py Strategy 3 darf nicht
|
||||||
|
Wort-für-Wort matchen, sondern muss den ganzen Keyword-String
|
||||||
|
(oder alle Keyword-Wörter zusammen) gegen den Text prüfen.
|
||||||
|
Wenn dieser Fix kommt, funktioniert test_03 OHNE Test-Anpassung.
|
||||||
|
|
||||||
|
Empfehlung (Priorität 2 — pragmatisch, wenn Archivar-Fix
|
||||||
|
nicht in dieser Iteration kommt):
|
||||||
|
Test 03 + 05 sollten Keyword-Texte wählen, die diese
|
||||||
|
Wort-Fuzzy-Falle nicht triggern. Siehe B-2 / B-4.
|
||||||
|
|
||||||
|
|
||||||
|
BEFUND B-2 — Test 03 Problem 1: Keyword-Wahl
|
||||||
|
=============================================
|
||||||
|
Befund:
|
||||||
|
test_03_move_request.py Z.175-177 postet:
|
||||||
|
"hermes deployment pipeline — bitte in den Rocketchat-Plugin-
|
||||||
|
Raum routen"
|
||||||
|
Archivar trifft via fuzzy-Word-Match auf "hermes-gateway"
|
||||||
|
(keywords_100 #Rocketchat-Plugin) → 100% → Auto-Route statt
|
||||||
|
Move-Request.
|
||||||
|
|
||||||
|
Bewertung: GELB — Selbst ohne Archivar-Bug (B-1) ist der Text
|
||||||
|
ein gefährlicher Kandidat. "hermes" ist Substring-Wort von
|
||||||
|
"hermes-gateway". Solche Texte sind in der room-map nicht
|
||||||
|
sauber als "context-only" markiert.
|
||||||
|
|
||||||
|
Empfehlung — Keyword-Wahl für test_03:
|
||||||
|
Don braucht EINEN Text, der:
|
||||||
|
(i) KEIN 100%-Keyword eines Raums vollständig matcht
|
||||||
|
(auch nicht per Fuzzy-Word-Match),
|
||||||
|
(ii) KEIN keywords_100-Wort eines beliebigen Raums als
|
||||||
|
isoliertes Substring-Wort enthält,
|
||||||
|
(iii) trotzdem GENAU EINEN Raum über keywords_context
|
||||||
|
oder FAISS-Boosting als Zielraum identifiziert.
|
||||||
|
|
||||||
|
Konkrete Vorschläge (verbal, Don wählt):
|
||||||
|
|
||||||
|
Variante A — Context-only-Phrase:
|
||||||
|
"Wie ist der aktuelle Stand der Preflight-Briefings?"
|
||||||
|
"preflight" steht aktuell in keywords_context von
|
||||||
|
#Rocketchat-Plugin (room-map Z.49 nicht enthalten —
|
||||||
|
tatsächlich: NICHT in der aktuellen Map; "preflight"
|
||||||
|
müsste erst in keywords_context aufgenommen werden).
|
||||||
|
UNGEEIGNET für jetzt.
|
||||||
|
|
||||||
|
Variante B — Phrase, die nur als Ganzes matcht:
|
||||||
|
"Rocketchat-DDP-Message-Handler-Pfad dokumentieren"
|
||||||
|
"Rocketchat-DDP-Message-Handler" als Phrase: nicht in
|
||||||
|
keywords_100 (da steht "message-handler" getrennt und
|
||||||
|
"ddp" getrennt). Per Strategy 3 könnte "message-handler"
|
||||||
|
auf "message-handler-pfad" exact matchen — ABER als
|
||||||
|
keyword_100 Substring → AUF 100%-Route. Auch nicht ideal.
|
||||||
|
|
||||||
|
Variante C — Anderer Raum mit sauberem Context-Only:
|
||||||
|
#BAT-Team keywords_100: bat, bat-team, trading, krypto,
|
||||||
|
wyckoff, boot-window, börse, exchange, analyst,
|
||||||
|
control-tower, docker-image, container-build,
|
||||||
|
trading-gateway.
|
||||||
|
keywords_context: bot.
|
||||||
|
→ Phrase "bot beim Trading" matcht "bot" (context),
|
||||||
|
"trading" (100%) → 100%-Match. SCHLECHT.
|
||||||
|
|
||||||
|
#Protonbridge-Plugin: keywords_context nur "plugin".
|
||||||
|
→ "plugin integration proton" → "plugin" context, kein
|
||||||
|
100%-Match. GEEIGNET, sofern Proton-Raum ein valides
|
||||||
|
Ziel für die Tests ist und Bernd dort Mitglied.
|
||||||
|
|
||||||
|
Variante D — Catch-All-Raum umgehen:
|
||||||
|
Da Catch-All KEIN Move-Request unterstützt (Ziel ==
|
||||||
|
Origin → stay_in_room per ORIGIN-FIRST-GUARD), ist
|
||||||
|
Catch-All als Zielraum für test_03 UNGEEIGNET.
|
||||||
|
|
||||||
|
EMPFEHLUNG KONKRET:
|
||||||
|
Don formuliert einen Text, der "Proton" oder "Protonbridge"
|
||||||
|
UND "plugin" enthält, beide Wörter NUR in keywords_context
|
||||||
|
bzw. nur eines in keywords_100 des Proton-Raums. ODER:
|
||||||
|
einfacher und reproduzierbar — Don postet den Move-Request-
|
||||||
|
Test direkt im ZIELRAUM (#Rocketchat-Plugin oder
|
||||||
|
#Protonbridge) und prüft die kopierte Nachricht im
|
||||||
|
Ursprungsraum statt andersrum. Dann braucht test_03 gar
|
||||||
|
keinen "Wanderung-starten"-Text.
|
||||||
|
|
||||||
|
SAUBERSTE LÖSUNG: Archivar-Fix B-1 umsetzen UND in
|
||||||
|
test_03 den Text "rocket chat plugin preflight briefing"
|
||||||
|
verwenden — sobald Strategy-3-Fix aktiv ist, ist "rocket"
|
||||||
|
nicht Substring von keywords_100 (steht als "rocketchat"
|
||||||
|
EINES Wortes) und der ganze Match läuft über
|
||||||
|
keywords_context → Move-Request.
|
||||||
|
|
||||||
|
|
||||||
|
BEFUND B-3 — Test 03 Problem 2: Bernd-Zugriff auf
|
||||||
|
=================================================
|
||||||
|
#Rocketchat-Plugin
|
||||||
|
Befund:
|
||||||
|
test_03_move_request.py Z.56 hat hardcoded
|
||||||
|
_DEFAULT_ROCKETCHAT_PLUGIN_ROOM = "6a19b0ff02aeecd36b1aa16c"
|
||||||
|
Test pollt in Z.227-228 channels.history auf diesem Raum.
|
||||||
|
Wenn Bernd nicht Mitglied ist → HTTP 400.
|
||||||
|
|
||||||
|
Bewertung: GELB — Tests sind nicht isoliert von Production-
|
||||||
|
Räumen. Live-Tests sollten entweder gegen Test-Räume laufen,
|
||||||
|
oder Don muss die Mitgliedschaft explizit sicherstellen.
|
||||||
|
|
||||||
|
Empfehlung (Reihenfolge):
|
||||||
|
1. PRÜFEN: Ist Bernd tatsächlich nicht Mitglied?
|
||||||
|
Don via Rocket.Chat-Admin prüfen. Falls doch
|
||||||
|
Mitglied, ist HTTP 400 ein anderes Problem
|
||||||
|
(z.B. ungültiger Bearer-Token, abgelaufener
|
||||||
|
Personal Access Token). Vor jedem Fix: tatsächliche
|
||||||
|
RC-Response im .45-Log nachschauen.
|
||||||
|
2. FALLS NICHT MITGLIED: Bernd in #Rocketchat-Plugin
|
||||||
|
einladen VOR dem nächsten Lauf. Danach Test
|
||||||
|
verifizieren.
|
||||||
|
3. SAUBERSTE LÖSUNG: Test-Räume statt Production-Räume
|
||||||
|
verwenden. Don legt in Rocket.Chat
|
||||||
|
#test-rc-rocketchat-mirror an, der nur für
|
||||||
|
Live-Tests da ist, und konfiguriert die ID via
|
||||||
|
RC_LIVE_ROCKETCHAT_PLUGIN_ROOM env-var (test_03
|
||||||
|
hat das schon vorgesehen, Z.137 — Default-Wert ist
|
||||||
|
hartcodiert auf den falschen Fallback).
|
||||||
|
4. KURZFRISTIG: Hardcoded Fallback in Z.56 entfernen
|
||||||
|
und nur per env-var konfigurieren. Dann skippt
|
||||||
|
der Test sauber, wenn env-var nicht gesetzt.
|
||||||
|
|
||||||
|
|
||||||
|
BEFUND B-4 — Test 05: Architektur-Frage triggert Routing
|
||||||
|
========================================================
|
||||||
|
Befund:
|
||||||
|
test_05_stream_retry.py Z.100-103 postet:
|
||||||
|
"Erkläre ausführlich die Architektur des Hermes Rocket.Chat
|
||||||
|
Plugins inklusive aller Komponenten, Datenflüsse und
|
||||||
|
Sicherheitsmechanismen."
|
||||||
|
"rocketchat" matcht keywords_100 #Rocketchat-Plugin → 100%
|
||||||
|
→ Auto-Route → 82-Zeichen-Ankündigung statt LLM-Antwort.
|
||||||
|
|
||||||
|
Bewertung: GELB — Test will "lange LLM-Antwort triggern +
|
||||||
|
ContextVar-Isolation prüfen". Der Text macht beides nicht,
|
||||||
|
weil die Routing-Logik zuerst greift und die Frage umleitet.
|
||||||
|
|
||||||
|
Empfehlung:
|
||||||
|
Don formuliert die Test-Frage UM, so dass:
|
||||||
|
(i) KEIN 100%-Keyword eines Raums matcht (auch nicht
|
||||||
|
per Fuzzy-Word-Match aus B-1),
|
||||||
|
(ii) die Frage trotzdem lang und architekturbezogen ist
|
||||||
|
(Bot muss wirklich selbst antworten, nicht routen),
|
||||||
|
(iii) der Kontext nicht durch Substring-Wörter
|
||||||
|
("plugin", "adapter", "websocket") versehentlich
|
||||||
|
100%-Trigger setzt.
|
||||||
|
|
||||||
|
Konkrete Vorschläge (Don wählt):
|
||||||
|
|
||||||
|
Vorschlag F-1:
|
||||||
|
"Erkläre ausführlich die Funktionsweise eines
|
||||||
|
WebSocket-Protokolls — speziell die Rolle von
|
||||||
|
Streaming-Frames, Heartbeats und Reconnect-Strategien."
|
||||||
|
→ "websocket" ist keywords_100 #Rocketchat-Plugin
|
||||||
|
→ IMMER NOCH 100%-Match. UNGEEIGNET.
|
||||||
|
|
||||||
|
Vorschlag F-2:
|
||||||
|
"Erkläre ausführlich das OSI-Schichtenmodell und wie
|
||||||
|
persistente Verbindungen auf Anwendungsebene von
|
||||||
|
kurzlebigen HTTP-Requests abgegrenzt werden."
|
||||||
|
→ "OSI", "Schichtenmodell" sind nirgends in
|
||||||
|
keywords_100. "HTTP" auch nicht. "Verbindung",
|
||||||
|
"Anwendung" auch nicht. SAUBER.
|
||||||
|
|
||||||
|
Vorschlag F-3:
|
||||||
|
"Vergleiche ausführlich die Auswirkungen von
|
||||||
|
parallelen Koroutinen auf einen gemeinsamen
|
||||||
|
Konfigurations-Speicher in einem asynchronen
|
||||||
|
Python-Webserver."
|
||||||
|
→ "asynchron", "Koroutinen", "Konfigurations",
|
||||||
|
"Python", "Webserver" — alle nicht in keywords_100.
|
||||||
|
"parallel" — auch nicht. SAUBER und thematisch
|
||||||
|
passend für ContextVar-Isolation-Test.
|
||||||
|
|
||||||
|
Vorschlag F-4 (thematisch perfekt):
|
||||||
|
"Erkläre ausführlich die Architektur eines Chatbot-
|
||||||
|
Backends mit Multi-Room-Routing, ContextVar-basierter
|
||||||
|
Task-Isolation und einem Push-basierten Eingangskanal."
|
||||||
|
→ Keine keywords_100-Treffer (Multi, Room, Routing,
|
||||||
|
Context, Var, Push, Kanal — alle nicht in der Map).
|
||||||
|
THEMATISCH PASSEND.
|
||||||
|
|
||||||
|
EMPFEHLUNG KONKRET: Vorschlag F-4 verwenden. Begründung
|
||||||
|
im Docstring ergänzen, dass die Frage KEIN 100%-Keyword
|
||||||
|
triggern darf.
|
||||||
|
|
||||||
|
Cross-Contamination-Assertions (Z.197-212) bleiben
|
||||||
|
unverändert — die prüfen "rüber"/"move" im test_room
|
||||||
|
und "architektur" im target_room. Mit Vorschlag F-4
|
||||||
|
bleibt "architektur" erhalten (im test_room), aber im
|
||||||
|
target_room (mit "rocketchat ddp bug" als Kurzantwort
|
||||||
|
in Z.115) kommt die Auto-Route-Antwort OHNE
|
||||||
|
"architektur" — passt.
|
||||||
|
|
||||||
|
|
||||||
|
BEFUND B-5 — Test 06: Parallelität vs Interrupt-Recursion
|
||||||
|
=========================================================
|
||||||
|
Befund:
|
||||||
|
test_06_concurrent.py Z.119-130 postet beide Nachrichten
|
||||||
|
"innerhalb 1s" (Z.117) in verschiedenen Räumen.
|
||||||
|
Beobachtung: "Interrupt recursion depth 3 reached".
|
||||||
|
|
||||||
|
Bewertung: GELB — Das ist KEIN Test-Bug, sondern eine
|
||||||
|
Limitierung des Hermes-Core. Der Core serialisiert
|
||||||
|
aktuell eingehende Nachrichten pro Bot-Instanz und
|
||||||
|
unterbricht laufende Antworten mit Tiefe-3-Limit.
|
||||||
|
Zwei echte gleichzeitige User-Nachrichten sind
|
||||||
|
ausserhalb des Test-Specs.
|
||||||
|
|
||||||
|
Empfehlung (Reihenfolge):
|
||||||
|
1. KURZFRISTIG & EMPFOHLEN: Sequenzielle Last mit
|
||||||
|
Delay.
|
||||||
|
Z.117-130 ändern zu:
|
||||||
|
- Nachricht A in test_room posten
|
||||||
|
- time.sleep(3.0) # Kern-Antwort beginnen lassen
|
||||||
|
- Nachricht B in source_room posten
|
||||||
|
Die zwei Antworten laufen dann in verschiedenen
|
||||||
|
ContextVar-Tasks (F6 R24 Isolation), aber der
|
||||||
|
zweite Post kommt NACH dem ersten Stream-Start —
|
||||||
|
Interrupt-Recursion wird nicht ausgelöst.
|
||||||
|
Docstring und Test-Name anpassen: nicht mehr
|
||||||
|
"concurrent" sondern "sequenziell mit kleinem
|
||||||
|
Delay, isolierte Tasks".
|
||||||
|
|
||||||
|
2. SAUBERE LÖSUNG: Test 06 als SKIP mit klarer
|
||||||
|
Begründung markieren, bis der Hermes-Core
|
||||||
|
Parallelität unterstützt (das ist eine separate
|
||||||
|
Core-Aufgabe, nicht im Plugin-Scope).
|
||||||
|
Skip-Reason: "Hermes-Core interrupt-recursion-
|
||||||
|
limit=3 verhindert echte parallele Nachrichten.
|
||||||
|
Sobald Core-Issue X behoben, Test reaktivieren."
|
||||||
|
|
||||||
|
3. NACHGEORDNET: Test auf "NUR eine Nachricht pro
|
||||||
|
Raum" reduzieren — dann testet er nichts mehr
|
||||||
|
bezüglich Parallelität und kann gestrichen werden.
|
||||||
|
NICHT EMPFOHLEN — Test verliert seinen Sinn.
|
||||||
|
|
||||||
|
EMPFEHLUNG KONKRET: Option 1 (sequenzielles Delay).
|
||||||
|
Sie ist am wenigsten invasiv und liefert immer noch
|
||||||
|
ContextVar-Isolation-Evidenz.
|
||||||
|
|
||||||
|
|
||||||
|
ZUSAMMENFASSUNG — Empfehlungen an Miguel (Don)
|
||||||
|
===============================================
|
||||||
|
1. test_03 — Zwei unabhängige Fixes:
|
||||||
|
a) Sofort: Bernd in #Rocketchat-Plugin einladen ODER
|
||||||
|
RC_LIVE_ROCKETCHAT_PLUGIN_ROOM auf einen Test-Raum
|
||||||
|
umbiegen (Default-Fallback in Z.56 entfernen).
|
||||||
|
b) Keyword-Text in Z.175-177 ersetzen. Empfehlung:
|
||||||
|
"rocket chat plugin preflight briefing dokumentieren"
|
||||||
|
ERST NACH Archivar-Fix B-1. Bis dahin: Test skippen
|
||||||
|
mit Begründung "keyword_matcher Strategy-3 Bug,
|
||||||
|
siehe B-1 in rainer/test-anpassung-2026-07-29.md".
|
||||||
|
c) Docstring aktualisieren: "hermes deployment pipeline"
|
||||||
|
entfernen, da es B-1-Bug triggert.
|
||||||
|
|
||||||
|
2. test_05 — keyword_text in Z.100-103 ersetzen.
|
||||||
|
Empfehlung F-4: "Erkläre ausführlich die Architektur
|
||||||
|
eines Chatbot-Backends mit Multi-Room-Routing,
|
||||||
|
ContextVar-basierter Task-Isolation und einem
|
||||||
|
Push-basierten Eingangskanal."
|
||||||
|
Docstring: explizit vermerken, dass die Frage KEIN
|
||||||
|
100%-Keyword enthalten darf.
|
||||||
|
|
||||||
|
3. test_06 — Sequenzielles Delay einbauen:
|
||||||
|
Z.119 (post_test_message für text_a)
|
||||||
|
→ time.sleep(3.0) einfügen
|
||||||
|
Z.130 (post_test_message für text_b) bleibt.
|
||||||
|
Docstring: "innerhalb 1s" → "sequenziell mit 3s Delay
|
||||||
|
zur Vermeidung von Interrupt-Recursion".
|
||||||
|
|
||||||
|
4. Langfristig — Archivar-Bug B-1 fixen:
|
||||||
|
keyword_matcher.py Strategy 3 (Z.300-315) muss bei
|
||||||
|
Multi-Wort-Keywords verlangen, dass ALLE Keyword-Wörter
|
||||||
|
im Text vorkommen. Sonst werden Phrasen-Keywords wie
|
||||||
|
"hermes-gateway" durch Einzelwort-Fuzzy zerlegt.
|
||||||
|
Priorität: hoch — betrifft alle Räume mit
|
||||||
|
Multi-Wort-keywords_100.
|
||||||
|
|
||||||
|
5. Querverweis für Don:
|
||||||
|
Der von Bernd in dieser Session genannte
|
||||||
|
"Test-Architektur-Review" (memory: 2026-07-29) hat
|
||||||
|
test_03 ebenfalls schon das "lan"-Keyword-Problem
|
||||||
|
markiert. Mein jetziger Befund verschärft das:
|
||||||
|
NICHT nur "lan" ist problematisch, sondern JEDES
|
||||||
|
Keyword, das als isoliertes Substring-Wort in einer
|
||||||
|
Phrase-Form von keywords_100 vorkommt.
|
||||||
|
|
||||||
|
|
||||||
|
ARCHITEKTUR-HINWEIS — an alle, nicht an Miguel
|
||||||
|
===============================================
|
||||||
|
Der Kern-Befund B-1 (keyword_matcher Strategy-3 Wort-für-
|
||||||
|
Wort-Fuzzy) ist KEIN Test-Problem. Er erklärt auch
|
||||||
|
andere schwer reproduzierbare Bugs der Vergangenheit
|
||||||
|
(siehe F8-Review-Notizen). Wenn Rainer in der nächsten
|
||||||
|
Iteration Archivar-Review macht, steht Strategy-3 ganz
|
||||||
|
oben auf der Liste.
|
||||||
|
|
||||||
|
— Rainer
|
||||||
@@ -0,0 +1,524 @@
|
|||||||
|
RAINER REVIEW — Test-Architektur für 3 Live-Szenarien + Onboarding-Reset-Langfristlösung
|
||||||
|
============================================================================================
|
||||||
|
Profil: rainer
|
||||||
|
Datum: 2026-07-29
|
||||||
|
Repo: ~/projekte/Hermes_rocket.chat_Plugin
|
||||||
|
HEAD: d5fda5b
|
||||||
|
Deployment: .45 MyTestBot
|
||||||
|
Auftrag: Architektur-Entwürfe für test_03 (Button-Szenario), test_05 (Stream-Retry),
|
||||||
|
test_06 (Concurrent) + Onboarding-Reset-Langfristlösung.
|
||||||
|
Skill: rc-test-framework (lt. Aufgabe unter ~/.hermes/skills/devops/rc-test-framework/)
|
||||||
|
BEFUND: Existiert NICHT. skills_list zeigt ihn nicht. Im Repo gibt es
|
||||||
|
tests/live_rc/README.md (Architektur-Doku) und helpers/polling.py +
|
||||||
|
helpers/rc_rest.py als Test-Harness-Implementation. Empfehlung: Skill
|
||||||
|
aus Repo-Quellen rekonstruieren oder auf README verweisen.
|
||||||
|
|
||||||
|
Quellen-Trace
|
||||||
|
-------------
|
||||||
|
- tests/live_rc/test_03_move_request.py (273 Z., SKIP-Pfad in Z.165-198)
|
||||||
|
- tests/live_rc/test_05_stream_retry.py (60 Z., SKELETON, @pytest.mark.skip)
|
||||||
|
- tests/live_rc/test_06_concurrent.py (65 Z., SKELETON, @pytest.mark.skip)
|
||||||
|
- tests/live_rc/conftest.py (RateLimiter 30/min, Suite-Lock, Fixtures)
|
||||||
|
- tests/live_rc/helpers/polling.py (wait_for_bot_message, 429-Backoff)
|
||||||
|
- plugin/adapter.py (Move-Request-Logik, Onboarding-Init,
|
||||||
|
_pending_move_requests, _session_room_preferences)
|
||||||
|
- plugin/archivar/onboarding_state.py (F8 State Machine, ACTIVE als End-State)
|
||||||
|
- plugin/archivar/onboarding.py (Lock-Mechanismus, File-basiert,
|
||||||
|
kein Persist nach Restart)
|
||||||
|
- plugin/archivar/router.py (move_request_sent-Logik,
|
||||||
|
"FIX C: 100% → kein Butler" Z.1071)
|
||||||
|
- plugin/archivar/archivar_state.py (get/set/clear_onboarding_state Z.467-481)
|
||||||
|
- room-map.json (Raum-Map mit keywords_100/catch_all)
|
||||||
|
|
||||||
|
GLOBALER BEFUND (vorgezogen — alle 4 Tasks betroffen)
|
||||||
|
-----------------------------------------------------
|
||||||
|
Der Test-Harness hat eine harte 30-Calls/Min-Bremse + 20s Cooldown
|
||||||
|
(conftest.py Z.265). Pro Test ca. 3-6 API-Calls. test_05/test_06 dürfen
|
||||||
|
nicht gleichzeitig laufen, sonst kollidieren sie mit dem Rate-Bucket.
|
||||||
|
Empfehlung: Suite-Lock + -m "not live_rc_concurrent" zum sequenziellen
|
||||||
|
Lauf, oder neue Marker "slow_rc" mit eigenem 60/min-Bucket.
|
||||||
|
|
||||||
|
================================================================================
|
||||||
|
TASK 1 — test_03: ECHTES BUTTON-MOVE-REQUEST-SZENARIO
|
||||||
|
================================================================================
|
||||||
|
|
||||||
|
BEFUND
|
||||||
|
------
|
||||||
|
test_03 Z.165-198 hat eine Auto-Route-Detection, die bei 100% Keyword-Match
|
||||||
|
(Z.171-172) sofort skippt. Das ist konsistent mit dem Archivar-Verhalten:
|
||||||
|
router.py Z.1071 setzt move_request_sent=False wenn keywords_100-Match
|
||||||
|
("FIX C: 100% → kein Butler"). Die Architektur ist also: bei 100% Match
|
||||||
|
routet der Bot direkt, ohne Button-Confirm. Butler-Mode (Buttons) greift
|
||||||
|
nur bei confidence < 1.0 ODER wenn der butler_mode auf "cognitive"/"strict"
|
||||||
|
steht und ein Room-Match existiert aber nicht eindeutig ist.
|
||||||
|
|
||||||
|
Bewertung
|
||||||
|
---------
|
||||||
|
Option (a) — Nachricht OHNE 100%-Keyword-Match in source_room posten — ist
|
||||||
|
die einzige robuste Strategie. Begründung:
|
||||||
|
|
||||||
|
- (b) "mehrdeutiger Inhalt" funktioniert nur wenn butler_mode != "off" UND
|
||||||
|
der Archivar-Router einen Target-Room mit confidence < 1.0 findet. Wenn
|
||||||
|
die room-map kein Match liefert, geht der Bot in Clarify-Modus (kein
|
||||||
|
Move-Request). Test wird flaky.
|
||||||
|
- (c) "Multiroom deaktivieren" verlangt einen Plugin-Restart und ist
|
||||||
|
nicht testbar aus der Test-Suite heraus.
|
||||||
|
|
||||||
|
Architektur-Entwurf
|
||||||
|
-------------------
|
||||||
|
Szenario: Bernd postet in test-rc-source eine Nachricht, deren Inhalt
|
||||||
|
einen 100%-Keyword-Match in einem DRITTEN Raum hat (z.B. "lan" matcht
|
||||||
|
#LAN-Dokumentation 100%) — aber NICHT in test-rc-target. Der Archivar
|
||||||
|
klassifiziert die Nachricht thematisch, der Router findet den Match im
|
||||||
|
#LAN-Dokumentation-Raum mit confidence=1.0, aber butler_mode=cognitive
|
||||||
|
(siehe room-map.json — butler_mode wird per ENV gesetzt) triggert
|
||||||
|
move_request_sent=True. Bot sendet Move-Request-Buttons (✅Ja/📍Hier/📌Generell).
|
||||||
|
|
||||||
|
Test-Schritte:
|
||||||
|
1. /reset an source_room senden (sticky-topic clear — siehe test_03 Z.88-102).
|
||||||
|
2. /reset abwarten (5s Sleep + Polling auf bot_response).
|
||||||
|
3. Keyword-Text posten, der NICHT in test-rc-source oder test-rc-target
|
||||||
|
matcht, aber in einem dritten Raum 100% (z.B. "lan" → #LAN-Dokumentation).
|
||||||
|
4. wait_for_bot_message in source_room, timeout=30s, Suche nach
|
||||||
|
Button-Attachment (rc-action-Block) ODER Text "rüber" / "kopieren" /
|
||||||
|
"verschieben" — verifiziert dass MOVE_REQ-Bot-Response kam.
|
||||||
|
5. target_cursor in test-rc-target holen.
|
||||||
|
6. Button-Payload posten: "MOVE_REQ:<source_room>::confirm_move" via REST
|
||||||
|
(siehe adapter.py Z.2460 — Format "MOVE_REQ:<room_id>::<choice>").
|
||||||
|
WICHTIG: "confirm_move" ist die choice-Variante für ✅Ja (Z.2483).
|
||||||
|
7. wait_for_bot_message in test-rc-target, timeout=60s, Suche nach
|
||||||
|
"Auftrag von" / "hierher kopiert" (Z.2533: prefix = "*(Auftrag von
|
||||||
|
@{username}, hierher kopiert)*\n") + Original-Keyword im Text.
|
||||||
|
8. cleanup: posted_ids_source + posted_ids_target löschen.
|
||||||
|
|
||||||
|
Assertions:
|
||||||
|
A) Bot-Antwort in source_room enthält Move-Request-Indikator
|
||||||
|
(Text ODER attachment.actions mit type="button" und message_id in
|
||||||
|
Button-Payload).
|
||||||
|
B) Antwort in target_room beginnt mit "*(Auftrag von @<username>" und
|
||||||
|
enthält das Original-Keyword.
|
||||||
|
C) Message-Ownership: assert_bot_message(bot_username) für beide Räume.
|
||||||
|
D) Cursor-Trennung: target_cursor muss strikt > source_cursor sein,
|
||||||
|
sonst ist die target-Nachricht von einer früheren Test-Session.
|
||||||
|
|
||||||
|
Bekannte Limitierungen:
|
||||||
|
- Funktioniert NUR wenn butler_mode in der room-map NICHT "off" ist.
|
||||||
|
Default ist "cognitive" (siehe Archivar-Funktionsbeschreibung v8.5).
|
||||||
|
Test-ENV-Doku muss "butler_mode=cognitive" als Voraussetzung
|
||||||
|
dokumentieren.
|
||||||
|
- Wenn die Test-Reihenfolge vorherige sticky_topics in test-rc-source
|
||||||
|
hinterlassen hat, schlägt die Move-Request-Logik fehl. /reset ist
|
||||||
|
Pflicht-Vorbereitung (schon im aktuellen Skeleton).
|
||||||
|
- Konflikt mit Test 04: test_04 postet "rocketchat" im Hauptraum.
|
||||||
|
Wenn test_04 vor test_03 läuft und das Test-Keyword "lan" sticky setzt,
|
||||||
|
kann der "lan"-Match im dritten Raum hängenbleiben. Empfehlung: Reihenfolge
|
||||||
|
test_03 vor test_04, oder vor jedem Test ein /reset in ALLEN Räumen.
|
||||||
|
- Rate-Limit: 5+ API-Calls pro Test-Lauf, mit 20s Cooldown zwischen
|
||||||
|
Tests. Bei voller Suite ca. 5min reine Wartezeit. Akzeptabel.
|
||||||
|
|
||||||
|
Empfehlung
|
||||||
|
----------
|
||||||
|
Option (a) mit "lan"-Keyword gegen #LAN-Dokumentation ist der richtige
|
||||||
|
Weg. Vorbedingung: butler_mode != "off" UND #LAN-Dokumentation in
|
||||||
|
room-map.json mit keywords_100=["lan",...] (bestätigt Z.65-78 der
|
||||||
|
room-map.json). Wenn butler_mode "off" ist, muss der Test entweder
|
||||||
|
skippen oder die ENV-Konfig anpassen. Beides ist explizit zu
|
||||||
|
dokumentieren.
|
||||||
|
|
||||||
|
P3-Nit: test_03 Z.188-191 skippt mit Hinweis "Run /reset in source room
|
||||||
|
before test_03". Das ist im Skeleton schon richtig, aber die
|
||||||
|
Fehlermeldung bezieht sich auf sticky_topic auf rc-test-automated —
|
||||||
|
nicht auf test-rc-source. In der neuen Version muss der Hinweis
|
||||||
|
konsistent zur neuen Strategie sein.
|
||||||
|
|
||||||
|
================================================================================
|
||||||
|
TASK 2 — test_05: STREAM-RETRY-LIVE-SZENARIO
|
||||||
|
================================================================================
|
||||||
|
|
||||||
|
BEFUND
|
||||||
|
------
|
||||||
|
Es gibt KEINEN expliziten Stream-Abbruch-Mechanismus im RC-Plugin.
|
||||||
|
adapter.py hat keine DDP-Disconnect-Simulation, keine WS-Kill-Hook,
|
||||||
|
keine "abort stream"-API. Die "stream_retry"-Tests in
|
||||||
|
test_v8_1_p1_contextvar.py (Z.444, 858, 895) testen ContextVar-Reset
|
||||||
|
in Unit-Tests, NICHT echte Live-Stream-Abbruch-Szenarien. Die
|
||||||
|
Memory-Notiz F6 R24 (aefdad0) bestätigt: Stream-Retry wird im
|
||||||
|
Hermes-Core behandelt ("supersede stream attempt" = Hermes Core,
|
||||||
|
Retry erbt NICHT copy_context()-Snapshot).
|
||||||
|
|
||||||
|
Bewertung
|
||||||
|
---------
|
||||||
|
Option (a) — Stream mitten in der Verarbeitung abbrechen — ist via
|
||||||
|
REST nicht möglich. Der Stream lebt im LLM-Backend (nicht RC).
|
||||||
|
Option (b) — lange Antwort + Raum-Verifikation — testet nur Latenz,
|
||||||
|
nicht Retry. Option (c) — _room_context-Fallback (Task-Token) ist
|
||||||
|
bereits Unit-getestet (F6 R24: 20/20 ContextVar-Tests, aefdad0).
|
||||||
|
|
||||||
|
Architektur-Entwurf
|
||||||
|
-------------------
|
||||||
|
Szenario: Sende eine Nachricht in Raum A, die eine lange Antwort
|
||||||
|
triggert (>10s LLM-Stream). Während der Bot verarbeitet, sende eine
|
||||||
|
schnelle zweite Nachricht in Raum B (keyword-matched, kurze Antwort).
|
||||||
|
Verifiziere: Beide Antworten landen im korrekten Raum — Antwort A in
|
||||||
|
Raum A, Antwort B in Raum B. Das testet den Cross-Contamination-Fix
|
||||||
|
F6 R24 im Live-Kontext: Wenn die LLM-Verarbeitung von A "stuck" ist
|
||||||
|
und B parallel triggert, darf Bs Antwort NICHT versehentlich in A
|
||||||
|
landen (und umgekehrt).
|
||||||
|
|
||||||
|
Das ist kein klassischer "Stream-Retry-Test", sondern ein
|
||||||
|
"ContextVar-Isolation-Test unter Last" — semantisch aber das, was
|
||||||
|
F6 R24 abgesichert hat: _CURRENT_TASK_TOKEN + _set_room_context_origin.
|
||||||
|
|
||||||
|
Test-Schritte:
|
||||||
|
1. Cursor für source_room (Haupt-Testraum) holen.
|
||||||
|
2. Lange-Antwort-Trigger posten: "Erkläre ausführlich die Architektur
|
||||||
|
des Hermes Rocket.Chat Plugins inklusive aller Komponenten, Datenflüsse
|
||||||
|
und Sicherheitsmechanismen." (erwartete Stream-Dauer 20-40s).
|
||||||
|
3. Sofort (ohne sleep) eine zweite Nachricht in test-rc-target posten
|
||||||
|
mit eindeutigem 100%-Keyword (z.B. "rocketchat") — kurze Antwort
|
||||||
|
erwartet (5-10s).
|
||||||
|
4. wait_for_bot_message in test_room (lange Antwort) und target_room
|
||||||
|
(kurze Antwort) PARALLEL mit zwei Threads (concurrent.futures)
|
||||||
|
oder sequenziell mit Zeitstempel-Tracking.
|
||||||
|
5. Verifiziere: Antwort in test_room enthält Architektur-Keywords
|
||||||
|
("adapter", "archivar", "ddp"); Antwort in target_room beginnt
|
||||||
|
mit Auto-Route-Ankündigung ODER Move-Request.
|
||||||
|
6. KRITISCH: Verifiziere dass die Antwort in test_room NICHT im
|
||||||
|
target_room erscheint und umgekehrt — Cross-Contamination-Check.
|
||||||
|
7. Cleanup aller geposteten Nachrichten.
|
||||||
|
|
||||||
|
Assertions:
|
||||||
|
A) Genau 1 Bot-Antwort in test_room (kein Duplikat, kein Streuen).
|
||||||
|
B) Genau 1 Bot-Antwort in target_room.
|
||||||
|
C) Antwort in test_room hat text-Länge > 200 Zeichen (langer Stream).
|
||||||
|
D) Antwort in target_room hat text-Länge < 500 Zeichen (kurze Antwort).
|
||||||
|
E) Message-Ownership für beide: assert_bot_message(bot_username).
|
||||||
|
F) KEIN Cross-Talk: target_room-history darf keine Nachricht mit
|
||||||
|
"Architektur" enthalten; test_room-history darf keine "rüber"/
|
||||||
|
"Move"/Auto-Route-Nachricht aus diesem Test-Lauf enthalten.
|
||||||
|
|
||||||
|
Bekannte Limitierungen:
|
||||||
|
- Test ist nicht-deterministisch bezüglich Reihenfolge: mal
|
||||||
|
antwortet der Bot auf A zuerst, mal auf B. Das ist OK —
|
||||||
|
Assertions prüfen Inhalt, nicht Reihenfolge.
|
||||||
|
- Lange Antworten können 429-Rate-Limit triggern. 30/min ist eng
|
||||||
|
bei 2 parallelen Tests. Empfehlung: Test als @pytest.mark.slow_rc
|
||||||
|
markieren, eigener Rate-Bucket ODER sequenziell.
|
||||||
|
- Wenn der LLM-Backend gerade überlastet ist, schlägt Test ggf.
|
||||||
|
fehl ohne dass es ein Code-Bug ist. Test muss mit retry-Logik
|
||||||
|
oder skip-Verhalten bei Timeout > 90s umgehen.
|
||||||
|
- Test verifiziert NICHT echten Stream-Abbruch. Wer das braucht,
|
||||||
|
muss einen LLM-Backend-Proxy mit Kill-Switch aufsetzen
|
||||||
|
(out of scope für diese Architektur-Runde).
|
||||||
|
|
||||||
|
Empfehlung
|
||||||
|
----------
|
||||||
|
Option (c) ist die richtige Wahl — aber als "ContextVar-Isolation
|
||||||
|
unter Last", nicht als "Stream-Retry". Das ehrliche Test-Szenario
|
||||||
|
verifiziert genau den Pfad, den F6 R24 abgesichert hat, im
|
||||||
|
Live-Kontext. Wenn der Test grün ist, wissen wir: parallele
|
||||||
|
Streams vermischen sich nicht. Test-Docstring muss ehrlich sagen
|
||||||
|
"verifiziert ContextVar-Isolation unter paralleler Last" statt
|
||||||
|
"Stream-Retry" — sonst entstehen falsche Erwartungen.
|
||||||
|
|
||||||
|
P3-Nit: Der aktuelle Skeleton-Docstring "TODO: Stream-Retry noch
|
||||||
|
nicht auf .45 verfügbar" ist irreführend — Stream-Retry ist eine
|
||||||
|
Core-Funktion, nicht .45-spezifisch. Docstring muss korrigiert
|
||||||
|
werden sobald der Test implementiert wird.
|
||||||
|
|
||||||
|
KEIN SOFORT-ALARM: Stream-Retry-Verifikation existiert bereits
|
||||||
|
als 20/20 grüne Unit-Tests (F6 R24, aefdad0). Live-Test ist
|
||||||
|
defense-in-depth, nicht kritisch.
|
||||||
|
|
||||||
|
================================================================================
|
||||||
|
TASK 3 — test_06: CONCURRENT (CONTEXTVAR-ISOLATION LIVE)
|
||||||
|
================================================================================
|
||||||
|
|
||||||
|
BEFUND
|
||||||
|
------
|
||||||
|
Der "Themenring" als Ring-Datenstruktur (MultiRoomContextRing) wird in
|
||||||
|
Tests benutzt (test_v8_4_2.py Z.246 u.a.) und existiert in HEAD.
|
||||||
|
Im Live-Adapter ist die analoge Funktionalität als _session_room_preferences
|
||||||
|
+ _recent_auto_routes + _explicit_switch_sticky (adapter.py Z.1182-1188)
|
||||||
|
realisiert — alle mit TTL (30 Min) und pro-Room-Key. Das ist der
|
||||||
|
"Themenring" im funktionalen Sinn, auch wenn die Datenstruktur anders heißt.
|
||||||
|
|
||||||
|
Der im Auftrag erwähnte Rollback vom 28.07. betraf vermutlich einen
|
||||||
|
ANDEREN Themenring (Phase A, Topic-Ring-Datenstruktur auf Archivar-Ebene).
|
||||||
|
Der session_room_preferences-Mechanismus ist davon unabhängig und in
|
||||||
|
HEAD d5fda5b aktiv.
|
||||||
|
|
||||||
|
Bewertung
|
||||||
|
---------
|
||||||
|
Option (a) — Skip bis Themenring zurück — ist FALSCH. Die Funktionalität
|
||||||
|
ist bereits da, nur unter anderem Namen. Option (c) — Test so entwerfen
|
||||||
|
dass er später funktioniert — ist unnötig, weil er JETZT funktionieren
|
||||||
|
kann. Option (b) — gegen _room_context-Fallback testen — überschneidet
|
||||||
|
sich mit test_05, weil das derselbe Mechanismus ist (F6 R24).
|
||||||
|
|
||||||
|
Architektur-Entwurf
|
||||||
|
-------------------
|
||||||
|
Szenario: Zwei Nachrichten in zwei verschiedenen Räumen gleichzeitig
|
||||||
|
posten, jede mit einem 100%-Keyword-Match in einem ANDEREN Raum. Der
|
||||||
|
Bot muss beide unabhängig routen, ohne dass die Streams sich
|
||||||
|
kontaminieren.
|
||||||
|
|
||||||
|
Konkret:
|
||||||
|
Raum A: test_room (rc-test-automated), Botschaft "lan subnetz maskieren
|
||||||
|
in test-rc-source" — keyword "lan" matcht #LAN-Dokumentation.
|
||||||
|
Raum B: test-rc-source, Botschaft "rocketchat ddp bug" — keyword
|
||||||
|
"rocketchat" matcht #Rocketchat-Plugin.
|
||||||
|
Beide sollen auto-routen UND die Antwort darf nicht im falschen
|
||||||
|
Raum landen. (F6 R24-Szenario unter realer Concurrency.)
|
||||||
|
|
||||||
|
Test-Schritte:
|
||||||
|
1. /reset in beide Räume senden (cleanup sticky_topics aus früheren Tests).
|
||||||
|
2. Cursor_A für test_room holen, Cursor_B für test-rc-source holen.
|
||||||
|
3. Beide Nachrichten INNERHALB von 1s posten (fast simultan).
|
||||||
|
4. wait_for_bot_message parallel in beiden Räumen
|
||||||
|
(initial_interval=8s, timeout=60s).
|
||||||
|
5. Antwort-Inhalte prüfen: Antwort_A referenziert #LAN-Dokumentation
|
||||||
|
ODER #test-rc-source (move), Antwort_B referenziert
|
||||||
|
#Rocketchat-Plugin ODER #rc-test-automated (move).
|
||||||
|
6. Cross-Contamination: Antwort_A darf NICHT "rocketchat" enthalten,
|
||||||
|
Antwort_B darf NICHT "lan"/"subnetz" enthalten.
|
||||||
|
7. Cleanup.
|
||||||
|
|
||||||
|
Assertions:
|
||||||
|
A) Je 1 Bot-Antwort in jedem Raum.
|
||||||
|
B) Antwort_A.message_inhalt bezieht sich auf LAN-Routing.
|
||||||
|
C) Antwort_B.message_inhalt bezieht sich auf Rocketchat-Routing.
|
||||||
|
C) KEIN Cross-Talk (siehe oben).
|
||||||
|
D) Beide Antworten kommen von bot_username.
|
||||||
|
E) Antworten kommen innerhalb 60s (concurrency funktioniert, kein
|
||||||
|
Deadlock durch fehlende Task-Token-Isolation).
|
||||||
|
|
||||||
|
Bekannte Limitierungen:
|
||||||
|
- Wie test_05: Rate-Limit 30/min ist eng. Empfehlung:
|
||||||
|
@pytest.mark.slow_rc mit erhöhtem Bucket ODER sequenziell.
|
||||||
|
- Der "Themenring" als Ring-Struktur ist ein anderes Konzept
|
||||||
|
als _session_room_preferences. Test testet das Ergebnis
|
||||||
|
(isolierte Routings), nicht die Datenstruktur.
|
||||||
|
- Wenn butler_mode="off" gesetzt ist, routen beide Nachrichten
|
||||||
|
auto (keine Buttons). Test funktioniert trotzdem.
|
||||||
|
|
||||||
|
Empfehlung
|
||||||
|
----------
|
||||||
|
Option (b) — Test gegen _room_context-Fallback (Task-Token) — ist die
|
||||||
|
richtige Wahl. ABER: Der Test darf NICHT "Themenring" heißen, weil
|
||||||
|
der Mechanismus in HEAD anders heißt. Umbenennen in
|
||||||
|
test_06_concurrent_isolation.py + Docstring "verifiziert
|
||||||
|
ContextVar-Isolation zwischen parallelen Routings in verschiedenen
|
||||||
|
Räumen" — ehrlich und konsistent mit test_05.
|
||||||
|
|
||||||
|
KEIN SOFORT-ALARM: KontextVar-Isolation ist bereits durch 20/20
|
||||||
|
Unit-Tests (F6 R24) abgesichert. test_06 ist defense-in-depth.
|
||||||
|
|
||||||
|
P1-Befund (kein Alarm, nur Notiz): Der aktuelle Skeleton-Docstring
|
||||||
|
"TODO: Themenring noch nicht auf .45 verfügbar" basiert auf einer
|
||||||
|
falschen Prämisse (der Themenring IST verfügbar, nur unter
|
||||||
|
anderem Namen). Empfehlung: Skeleton-Docstring korrigieren, sobald
|
||||||
|
test_06 implementiert wird.
|
||||||
|
|
||||||
|
================================================================================
|
||||||
|
TASK 4 — ONBOARDING-RESET LANGFRISTLÖSUNG
|
||||||
|
================================================================================
|
||||||
|
|
||||||
|
BEFUND (WURZEL-ANALYSE)
|
||||||
|
-----------------------
|
||||||
|
Drei Persistenz-Ebenen sind im Spiel:
|
||||||
|
|
||||||
|
Ebene 1: onboarding_state.py (F8 State Machine)
|
||||||
|
Datei: ~/.hermes/hermes-agent/data/onboarding.yaml
|
||||||
|
States: NONE, AWAITING_ROOM, AWAITING_INTENT, AWAITING_TEST,
|
||||||
|
ACTIVE, PAUSED, ERROR
|
||||||
|
Restart-Logik (Z.337-406): Lädt korrekt. ACTIVE wird
|
||||||
|
respektiert, AWAITING_* wird fortgesetzt.
|
||||||
|
BEWERTUNG: Funktioniert korrekt. KEIN Bug hier.
|
||||||
|
|
||||||
|
Ebene 2: archivar_state._onboarding_state (Adapter-Interview-State)
|
||||||
|
Datei: ~/.hermes/hermes-agent/data/archivar_state.json
|
||||||
|
Felder: operator_room_id, missing_rooms, phase,
|
||||||
|
current_room_index, ...
|
||||||
|
Lifecycle: Z.1793-1817 in adapter.py.
|
||||||
|
PROBLEM: Z.1807-1817. Beim Restart wird der State nur
|
||||||
|
wiederhergestellt wenn BEIDE Bedingungen gelten:
|
||||||
|
(a) op_room in self._room_info (subscribed)
|
||||||
|
(b) is_onboarding_locked(missing_room.room_id) = True
|
||||||
|
Der Lock ist File-basiert (onboarding.py Z.174-232,
|
||||||
|
Pfad: ~/.hermes/hermes-agent/data/onboarding-<rid>.lock).
|
||||||
|
Lock-Dateien überleben RESTART NICHT — sie werden nur
|
||||||
|
während eines aktiven Interviews geschrieben (Z.193-204).
|
||||||
|
Nach Restart ist lock_active IMMER False (außer ein
|
||||||
|
Interview läuft gerade, was beim Start nie der Fall ist).
|
||||||
|
Ergebnis: clear_onboarding_state() wird aufgerufen,
|
||||||
|
archivar_state._onboarding_state = {}.
|
||||||
|
→ DAS IST DER RESET.
|
||||||
|
|
||||||
|
Ebene 3: OnboardingStateMachine (Ebenfalls in adapter.py geladen,
|
||||||
|
Z.1819-1836). Diese ist UNABHÄNGIG von Ebene 2 und
|
||||||
|
respektiert ACTIVE korrekt. KEIN Bug hier.
|
||||||
|
|
||||||
|
→ Die Wurzel: Ebene 2 hat eine "Zombie-State-Validierung" (Bug C,
|
||||||
|
Z.1795-1817), die den State bei fehlendem Lock verwirft. Der
|
||||||
|
Lock-Mechanismus ist nicht restart-fest.
|
||||||
|
|
||||||
|
Bewertung der 3 Optionen
|
||||||
|
------------------------
|
||||||
|
(a) COMPLETED als zusätzlicher State in onboarding_state.py
|
||||||
|
PRO: Saubere State-Machine-Erweiterung. Trennt "aktiv" von
|
||||||
|
"permanent abgeschlossen".
|
||||||
|
CONTRA: Löst das Problem NICHT. Das Reset passiert in
|
||||||
|
archivar_state (Ebene 2), nicht in onboarding_state
|
||||||
|
(Ebene 1). Die State-Machine in Ebene 1 funktioniert
|
||||||
|
bereits korrekt. Wir würden einen State hinzufügen, der
|
||||||
|
niemals erreicht wird, weil der Reset vorher passiert.
|
||||||
|
FAZIT: FALSCHER ANGRIFFSPUNKT. Verworfen.
|
||||||
|
|
||||||
|
(b) ACTIVE als permanenter End-State (kein Reset bei Neustart)
|
||||||
|
PRO: Trifft die Wurzel. Wenn ACTIVE nie resettet wird, ist
|
||||||
|
der "Workaround sed ACTIVE" überflüssig.
|
||||||
|
CONTRA: Verlangt eine Änderung an EBENE 2 (archivar_state), nicht
|
||||||
|
an onboarding_state. Die State-Machine in onboarding_state.py
|
||||||
|
HAT bereits ACTIVE als permanenten End-State (Z.97-102:
|
||||||
|
ACTIVE → {AWAITING_ROOM, PAUSED, ERROR, NONE} — kann
|
||||||
|
transitionieren, aber wird nicht automatisch zurückgesetzt).
|
||||||
|
Das Problem ist, dass die State-Machine beim Start
|
||||||
|
KORREKT ACTIVE lädt (Z.1824-1825: "Onboarding bereits
|
||||||
|
abgeschlossen — produktiver Pfad") — ABER Ebene 2
|
||||||
|
(archivar_state) wird VORHER durch Bug-C-Logik
|
||||||
|
gecleart, und der Plugin-Path prüft beide.
|
||||||
|
FAZIT: RICHTIGE RICHTUNG, FALSCHE BESCHREIBUNG. Die
|
||||||
|
OnboardingStateMachine HAT ACTIVE bereits als
|
||||||
|
permanenten End-State. Was fehlt: archivar_state-Level
|
||||||
|
muss ebenfalls "ACTIVE wurde erreicht, nie wieder
|
||||||
|
clearen" respektieren.
|
||||||
|
|
||||||
|
(c) onboarding.yaml bei jedem Start überschreiben wenn F8=COMPLETED
|
||||||
|
im Log steht
|
||||||
|
PRO: Direkter Fix auf Symptom-Ebene.
|
||||||
|
CONTRA: Setzt voraus dass F8=COMPLETED im Log steht — das
|
||||||
|
ist nur der Fall wenn die State-Machine einmal komplett
|
||||||
|
durchlaufen wurde UND der Log nicht rotiert wurde.
|
||||||
|
Race-Condition: Wenn der Log-Parse fehlschlägt (Log
|
||||||
|
rotiert, Log-Format ändert sich), wird der State
|
||||||
|
NICHT überschrieben → Problem bleibt. Außerdem:
|
||||||
|
"Überschreiben bei Start" ist ein anderer Schreibzeitpunkt
|
||||||
|
als der eigentliche Reset, kann zu Inkonsistenzen führen.
|
||||||
|
FAZIT: HACK. Verworfen.
|
||||||
|
|
||||||
|
Architektur-Empfehlung (KOMBINIERT)
|
||||||
|
-----------------------------------
|
||||||
|
EMPFEHLUNG: Option (b), aber richtig verstanden. Konkret:
|
||||||
|
|
||||||
|
Fix 1 (P1): archivar_state.py Z.467-481 — get_onboarding_state()
|
||||||
|
muss vor clear_onboarding_state() prüfen ob die
|
||||||
|
OnboardingStateMachine ACTIVE ist. Wenn ja, return
|
||||||
|
{} (nichts zu clearen) statt {} zu clearen.
|
||||||
|
Konkret: in adapter.py Z.1811-1817 darf
|
||||||
|
clear_onboarding_state() NUR aufgerufen werden, wenn
|
||||||
|
OnboardingStateMachine.state != ACTIVE.
|
||||||
|
|
||||||
|
Fix 2 (P2): onboarding_state.py Z.475-477 — complete() schreibt
|
||||||
|
aktuell in den YAML. Nach erfolgreichem complete()
|
||||||
|
soll der archivar_state._onboarding_state MIT einer
|
||||||
|
Markierung "completed_at: <ts>" gespeichert werden,
|
||||||
|
die nach Restart den Bug-C-Check schlägt.
|
||||||
|
|
||||||
|
Fix 3 (P3): onboarding_state.py — COMPLETED als ALIAS für ACTIVE
|
||||||
|
in den __init__.from_dict (Backwards-Kompat für alte
|
||||||
|
YAMLs die COMPLETED enthalten — siehe Aufgabenbeschreibung
|
||||||
|
"Setzen auf COMPLETED führt zu ERROR").
|
||||||
|
|
||||||
|
Detaillierte Pseudocode-Beschreibung (kein Code!):
|
||||||
|
|
||||||
|
adapter.py Z.1811-1817 (Bug-C-Logik):
|
||||||
|
VORHER: if not (op_room_subscribed AND lock_active):
|
||||||
|
clear_onboarding_state()
|
||||||
|
NACHHER: if not (op_room_subscribed AND lock_active):
|
||||||
|
if sm.state == ACTIVE:
|
||||||
|
# ACTIVE-Phase: Onboarding ist permanent fertig.
|
||||||
|
# archivar_state._onboarding_state darf leer bleiben
|
||||||
|
# (= kein laufendes Interview) — das ist konsistent
|
||||||
|
# mit "produktiver Pfad".
|
||||||
|
logger.info("Onboarding ACTIVE — archivar_state bleibt leer")
|
||||||
|
else:
|
||||||
|
# Echte Zombie-Situation: Lock weg, Op-Raum weg,
|
||||||
|
# State noch nicht ACTIVE → State war mid-Interview.
|
||||||
|
clear_onboarding_state()
|
||||||
|
|
||||||
|
onboarding_state.py Z.475-477 (complete):
|
||||||
|
VORHER: return self._transition(OnboardingState.ACTIVE)
|
||||||
|
NACHHER: return self._transition(OnboardingState.ACTIVE) AND
|
||||||
|
speichere completed_at-Timestamp in step_history
|
||||||
|
(für Audit / Debug).
|
||||||
|
|
||||||
|
onboarding_state.py Z.380-393 (load, invalid state):
|
||||||
|
VORHER: ValueError → setze auf ERROR
|
||||||
|
NACHHER: ValueError("COMPLETED") → setze auf ACTIVE (Backwards-Compat)
|
||||||
|
|
||||||
|
Bekannte Limitierungen:
|
||||||
|
- Der Fix lässt sich nicht mit reinen Config-Änderungen umsetzen —
|
||||||
|
es ist ein Code-Fix in adapter.py + onboarding_state.py.
|
||||||
|
- Workaround (sed ACTIVE) bleibt als Notfall-Option erhalten, ist
|
||||||
|
aber nach Fix redundant.
|
||||||
|
- Bestehende Installationen mitten im AWAITING_*-Interview und
|
||||||
|
ohne Lock werden weiterhin gecleart. Das ist gewollt — ein
|
||||||
|
halbfertiges Interview ohne Lock ist tatsächlich ein Zombie-State.
|
||||||
|
- Test-Coverage: Bestehende test_onboarding_state.py testet die
|
||||||
|
State-Machine-Transitions. Wir brauchen einen neuen Test
|
||||||
|
"test_restart_preserves_active_state" der den Restart-Simuliert
|
||||||
|
und verifiziert dass ACTIVE → ACTIVE überlebt.
|
||||||
|
|
||||||
|
P0-Sofort-Alarm: NEIN. Das Problem ist ein nerviger Workaround, kein
|
||||||
|
Datenverlust. ACTIVE-State wird vom Plugin nicht zurückgesetzt, nur
|
||||||
|
die Interview-Marker-Daten (welcher Raum wurde gerade interviewt).
|
||||||
|
Funktional liefert das Plugin nach Neustart korrekte Antworten — die
|
||||||
|
F8-Log-Zeile "Onboarding bereits abgeschlossen — produktiver Pfad"
|
||||||
|
kommt trotzdem.
|
||||||
|
|
||||||
|
P1-Priorität: Empfohlen für nächsten Sprint. Workaround (sed ACTIVE)
|
||||||
|
kann parallel weiterlaufen bis Fix produktiv ist.
|
||||||
|
|
||||||
|
================================================================================
|
||||||
|
ZUSAMMENFASSUNG — PRIORITÄTEN
|
||||||
|
================================================================================
|
||||||
|
|
||||||
|
P0: Keine Sofort-Alarme.
|
||||||
|
|
||||||
|
P1: TASK 4 — Onboarding-Reset-Fix (archivar_state + Bug-C-Logik)
|
||||||
|
Schmerz: Workaround funktioniert, aber sed ACTIVE ist manuell +
|
||||||
|
fehleranfällig. Fix verlangt 1 Code-Änderung in adapter.py +
|
||||||
|
Backwards-Compat in onboarding_state.py.
|
||||||
|
|
||||||
|
P2: TASK 1 — test_03-Button-Szenario (Option a, "lan"-Keyword)
|
||||||
|
Schmerz: Test skippt aktuell. Kein Produktiv-Impact.
|
||||||
|
Erforderlich für CI-Grün.
|
||||||
|
|
||||||
|
P3: TASK 2/3 — test_05/test_06 als Live-Isolation-Tests umsetzen
|
||||||
|
Schmerz: Defense-in-depth, bereits Unit-getestet.
|
||||||
|
Niedrige Priorität, da F6 R24 die Funktionalität absichert.
|
||||||
|
|
||||||
|
P3: Skeleton-Docstrings korrigieren (test_05/test_06 sagen
|
||||||
|
"Stream-Retry/Themenring nicht verfügbar" — irreführend).
|
||||||
|
|
||||||
|
Skill-Notiz: rc-test-framework existiert nicht. Empfehlung an Bernd:
|
||||||
|
entweder Skill anlegen (aus tests/live_rc/README.md + helpers/ extrahieren)
|
||||||
|
oder Verweis auf README im Review.
|
||||||
|
|
||||||
|
================================================================================
|
||||||
|
OFFENE FRAGEN AN BERND
|
||||||
|
================================================================================
|
||||||
|
|
||||||
|
1. TASK 1: Soll der Test strikt gegen butler_mode=cognitive laufen, oder
|
||||||
|
soll er mit Auto-Route (confidence=1.0) zufrieden sein und nur den
|
||||||
|
Move-Request-Pfad testen wenn butler_mode aktiv ist?
|
||||||
|
|
||||||
|
2. TASK 5/6: Sollen die neuen Tests als @pytest.mark.slow_rc markiert
|
||||||
|
werden mit eigenem Rate-Bucket, oder reicht der bestehende 30/min-
|
||||||
|
Limiter mit 20s Cooldown?
|
||||||
|
|
||||||
|
3. TASK 4: Soll Fix 1 (Bug-C-Logik) + Fix 2 (completed_at) zusammen
|
||||||
|
in einem Commit landen, oder getrennt für sauberere Review-Trail?
|
||||||
|
|
||||||
|
4. Skill rc-test-framework: Anlegen oder Verweis auf README reicht?
|
||||||
+515
-322
@@ -1175,6 +1175,11 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self.archivar = None
|
self.archivar = None
|
||||||
self._conversation_history = None
|
self._conversation_history = None
|
||||||
self._multiroom_context = None
|
self._multiroom_context = None
|
||||||
|
# P5 V9.x: OutboundGate — Parallel-Stream-Schutz
|
||||||
|
from archivar.outbound_gate import OutboundGate, GateDecision
|
||||||
|
self._outbound_gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=60.0)
|
||||||
|
if self.archivar is not None:
|
||||||
|
self.archivar.bind_outbound_gate(self._outbound_gate)
|
||||||
# User-Flow C: Move-Requests
|
# User-Flow C: Move-Requests
|
||||||
self._pending_move_requests: Dict[str, dict] = {}
|
self._pending_move_requests: Dict[str, dict] = {}
|
||||||
# V8.1 P2: Temporäre Session-Raum-Präferenzen (30 Min TTL)
|
# V8.1 P2: Temporäre Session-Raum-Präferenzen (30 Min TTL)
|
||||||
@@ -1393,6 +1398,25 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
return None
|
return None
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
async def _post_message_unlocked(self, room_id: str, text: str) -> Optional[str]:
|
||||||
|
"""P5 V9.x: Post message OHNE Gate-Check (für Quick-Reply).
|
||||||
|
|
||||||
|
Direkter REST-Call ohne OutboundGate — verhindert Endlosschleife
|
||||||
|
wenn der Quick-Reply selbst durch den Gate blockiert würde.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: Rocket.Chat Raum-ID.
|
||||||
|
text: Nachrichtentext.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
message_id oder None.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
return self.rest.post_message(room_id, text)
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug("[rocketchat] _post_message_unlocked failed: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
def _sync_room_map_with_membership(self) -> None:
|
def _sync_room_map_with_membership(self) -> None:
|
||||||
"""M13: Garbage-Collect room-map.json + FAISS + Booster + State gegen tatsächliche Mitgliedschaft.
|
"""M13: Garbage-Collect room-map.json + FAISS + Booster + State gegen tatsächliche Mitgliedschaft.
|
||||||
|
|
||||||
@@ -1907,6 +1931,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
self._mark_connected()
|
self._mark_connected()
|
||||||
self._running = True
|
self._running = True
|
||||||
self._listen_task = asyncio.create_task(self._listen_loop())
|
self._listen_task = asyncio.create_task(self._listen_loop())
|
||||||
|
# P5 V9.x W2: OutboundGate Sweep-Loop (asyncio.create_task, nicht threading.Timer)
|
||||||
|
# ── P1c: Sweep-Task-Check vor Re-create ──
|
||||||
|
task = getattr(self, '_gate_sweep_task', None)
|
||||||
|
if task is not None and not task.done():
|
||||||
|
task.cancel()
|
||||||
|
self._gate_sweep_task = asyncio.create_task(self._gate_sweep_loop())
|
||||||
self._last_activity = time.time()
|
self._last_activity = time.time()
|
||||||
logger.info("[rocketchat] Listen loop started, _running=%s", self._running)
|
logger.info("[rocketchat] Listen loop started, _running=%s", self._running)
|
||||||
logger.info("[rocketchat] Connected to %s", self.base_url)
|
logger.info("[rocketchat] Connected to %s", self.base_url)
|
||||||
@@ -3525,6 +3555,18 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
# P1-2: current_room zurücksetzen nach Verarbeitung
|
# P1-2: current_room zurücksetzen nach Verarbeitung
|
||||||
self._presence_engine.set_current_room("")
|
self._presence_engine.set_current_room("")
|
||||||
logger.info("[presence] mark_busy_done (turn complete)")
|
logger.info("[presence] mark_busy_done (turn complete)")
|
||||||
|
# ── P5 V9.x: OutboundGate — release (symmetrisch zu mark_busy_done) ──
|
||||||
|
# W2: release in try/except BaseException im finally-Block.
|
||||||
|
try:
|
||||||
|
_gate_room_id = f"user:{username}"
|
||||||
|
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||||
|
if origin:
|
||||||
|
_gate_room_id = origin
|
||||||
|
task_token = _CURRENT_TASK_TOKEN.get()
|
||||||
|
if task_token:
|
||||||
|
self._outbound_gate.release(_gate_room_id, task_token)
|
||||||
|
except BaseException:
|
||||||
|
logger.debug("[rocketchat] P5 V9.x: Gate release failed (non-critical)")
|
||||||
|
|
||||||
# ── R5: Inline-Command-Handler ────────────────────────────────────────
|
# ── R5: Inline-Command-Handler ────────────────────────────────────────
|
||||||
|
|
||||||
@@ -4684,6 +4726,13 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
return
|
return
|
||||||
finally:
|
finally:
|
||||||
self._agent_dispatch_task = None
|
self._agent_dispatch_task = None
|
||||||
|
# ── P5 V9.x: OutboundGate — release (symmetrisch zu mark_busy_done) ──
|
||||||
|
try:
|
||||||
|
task_token = _CURRENT_TASK_TOKEN.get()
|
||||||
|
if task_token:
|
||||||
|
self._outbound_gate.release(room_id, task_token)
|
||||||
|
except BaseException:
|
||||||
|
logger.debug("[rocketchat] P5 V9.x: Gate release failed in _dispatch_agent (non-critical)")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error("[rocketchat] handle_message error: %s", e)
|
logger.error("[rocketchat] handle_message error: %s", e)
|
||||||
# Fallback: Wenn COMMAND fehlschlägt
|
# Fallback: Wenn COMMAND fehlschlägt
|
||||||
@@ -6467,6 +6516,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
return text
|
return text
|
||||||
|
|
||||||
async def disconnect(self) -> None:
|
async def disconnect(self) -> None:
|
||||||
|
# ── P1b: Gate-Sweep-Task sauber beenden ──
|
||||||
|
if hasattr(self, '_gate_sweep_task') and self._gate_sweep_task is not None:
|
||||||
|
self._gate_sweep_task.cancel()
|
||||||
|
self._gate_sweep_task = None
|
||||||
|
self._running = False # P1b: Sweep-Loop nutzt _running Flag
|
||||||
|
|
||||||
self._mark_disconnected()
|
self._mark_disconnected()
|
||||||
self._shutdown_event.set()
|
self._shutdown_event.set()
|
||||||
if self._status_timer:
|
if self._status_timer:
|
||||||
@@ -6543,224 +6598,287 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
)
|
)
|
||||||
routing_counter.increment('red_flag_fallback_stay')
|
routing_counter.increment('red_flag_fallback_stay')
|
||||||
|
|
||||||
# ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ──────────
|
# ── P5 V9.x: OutboundGate — Parallel-Stream-Schutz ──────────
|
||||||
# Hermes Core sendet Meldungen mit /approve, /deny etc.
|
# Nach Red-Flag-Block, vor P1-6 Prefix.
|
||||||
# Rocket.Chat unterstützt keine /-Befehle → :: Varianten einsetzen.
|
# Verhindert dass der Agent gleichzeitig in zwei verschiedenen
|
||||||
content = self._replace_slash_with_double_colon(content)
|
# Räumen antwortet. Der Denkprozess läuft parallel — das Gate
|
||||||
|
# greift NUR in der Outbound-Phase (posten der Antwort).
|
||||||
# ── Virtual → Real Room Translation ─────────────────────────
|
_gate_room_id = chat_id
|
||||||
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
|
||||||
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
|
||||||
real_room_id = chat_id
|
|
||||||
if chat_id.startswith("user:"):
|
if chat_id.startswith("user:"):
|
||||||
# Priority 0: _CURRENT_ORIGIN_ROOM — Antwort geht IMMER dorthin,
|
|
||||||
# wo die Frage gestellt wurde.
|
|
||||||
# P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung.
|
|
||||||
# _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert
|
|
||||||
# vom Parent-Task erben. Wir validieren gegen _room_context task_token,
|
|
||||||
# um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu
|
|
||||||
# verhindern.
|
|
||||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||||
if origin:
|
if origin:
|
||||||
# Pre-Read-Validierung: Task-Token-Match prüfen
|
_gate_room_id = origin
|
||||||
current_token = _CURRENT_TASK_TOKEN.get()
|
task_token = _CURRENT_TASK_TOKEN.get()
|
||||||
ctx_entry = _room_context.get(chat_id, {})
|
_gate_acquired = False # P1a: track whether WE created the gate entry
|
||||||
stored_token = ctx_entry.get("task_token", "")
|
if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
|
||||||
# Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen,
|
from archivar.outbound_gate import GateDecision
|
||||||
# normale ContextVar-Logik weiterlaufen lassen
|
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||||
if current_token and stored_token and current_token != stored_token:
|
if not decision.allow:
|
||||||
routing_counter.increment('priority0_token_mismatch_skip')
|
# Blockiert — warte bis zu 30s (A4: blocking_room_id)
|
||||||
logger.info(
|
blocking_room = decision.blocking_room_id
|
||||||
"[rocketchat] send Priority 0 token mismatch for %s — "
|
if blocking_room:
|
||||||
"skipping stale ContextVar, falling through to _room_context",
|
try:
|
||||||
chat_id,
|
await self._outbound_gate.wait_until_clear(
|
||||||
|
blocking_room_id=blocking_room, timeout_s=30.0
|
||||||
|
)
|
||||||
|
# Retry acquire nach wait
|
||||||
|
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
decision = GateDecision(allow=False, reason="timeout")
|
||||||
|
|
||||||
|
if not decision.allow:
|
||||||
|
# Quick-Reply: anderer Raum blockiert immer noch
|
||||||
|
active_room = self._outbound_gate.active_room_id
|
||||||
|
active_name = ""
|
||||||
|
if active_room and active_room in self._room_info:
|
||||||
|
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
||||||
|
quick_reply_text = (
|
||||||
|
f"Ich antworte gerade in #{active_name} — "
|
||||||
|
f"einen Moment bitte, ich bin gleich bei dir."
|
||||||
|
) if active_name else (
|
||||||
|
"Ich antworte gerade in einem anderen Raum — "
|
||||||
|
"einen Moment bitte, ich bin gleich bei dir."
|
||||||
)
|
)
|
||||||
origin = "" # Force fallthrough
|
await self._post_message_unlocked(_gate_room_id, quick_reply_text)
|
||||||
if origin:
|
self._outbound_gate.stats.quick_reply += 1
|
||||||
real_room_id = origin
|
logger.info(
|
||||||
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
"[rocketchat] P5 V9.x: Quick-Reply sent to room=%s (blocked by %s)",
|
||||||
else:
|
_gate_room_id[:8], active_name,
|
||||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
)
|
||||||
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
return SendResult(success=True, message_id="quick_reply")
|
||||||
# ist _CURRENT_ORIGIN_ROOM leer. _room_context (global dict) überlebt.
|
# Fell through: decision.allow is True — track if WE created the entry
|
||||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
# (gate_clear = we own it; same_room_same_token = someone else owns it)
|
||||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
_gate_acquired = (decision.reason == "gate_clear")
|
||||||
fallback_origin = _get_room_context_origin(chat_id)
|
|
||||||
if fallback_origin:
|
# ── P1a: try/finally für symmetrisches Gate-Release ─────────
|
||||||
real_room_id = fallback_origin
|
# Bei Exception in send() hängt sonst der Gate-Eintrag.
|
||||||
routing_counter.increment('contextvar_reset_fallback')
|
try:
|
||||||
logger.info("[rocketchat] send via _room_context fallback: %s → %s", chat_id, real_room_id)
|
# ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ──────────
|
||||||
|
# Hermes Core sendet Meldungen mit /approve, /deny etc.
|
||||||
|
# Rocket.Chat unterstützt keine /-Befehle → :: Varianten einsetzen.
|
||||||
|
content = self._replace_slash_with_double_colon(content)
|
||||||
|
|
||||||
|
# ── Virtual → Real Room Translation ─────────────────────────
|
||||||
|
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
||||||
|
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
||||||
|
real_room_id = chat_id
|
||||||
|
if chat_id.startswith("user:"):
|
||||||
|
# Priority 0: _CURRENT_ORIGIN_ROOM — Antwort geht IMMER dorthin,
|
||||||
|
# wo die Frage gestellt wurde.
|
||||||
|
# P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung.
|
||||||
|
# _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert
|
||||||
|
# vom Parent-Task erben. Wir validieren gegen _room_context task_token,
|
||||||
|
# um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu
|
||||||
|
# verhindern.
|
||||||
|
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||||
|
if origin:
|
||||||
|
# Pre-Read-Validierung: Task-Token-Match prüfen
|
||||||
|
current_token = _CURRENT_TASK_TOKEN.get()
|
||||||
|
ctx_entry = _room_context.get(chat_id, {})
|
||||||
|
stored_token = ctx_entry.get("task_token", "")
|
||||||
|
# Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen,
|
||||||
|
# normale ContextVar-Logik weiterlaufen lassen
|
||||||
|
if current_token and stored_token and current_token != stored_token:
|
||||||
|
routing_counter.increment('priority0_token_mismatch_skip')
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] send Priority 0 token mismatch for %s — "
|
||||||
|
"skipping stale ContextVar, falling through to _room_context",
|
||||||
|
chat_id,
|
||||||
|
)
|
||||||
|
origin = "" # Force fallthrough
|
||||||
|
if origin:
|
||||||
|
real_room_id = origin
|
||||||
|
logger.debug("[rocketchat] send via ContextVar: %s → %s", chat_id, real_room_id)
|
||||||
else:
|
else:
|
||||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
# ContextVars sind asyncio-task-lokal — bei Stream-Retries in neuem Task
|
||||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
# ist _CURRENT_ORIGIN_ROOM leer. _room_context (global dict) überlebt.
|
||||||
if thematic_target:
|
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||||
real_room_id = thematic_target
|
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||||
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
fallback_origin = _get_room_context_origin(chat_id)
|
||||||
|
if fallback_origin:
|
||||||
|
real_room_id = fallback_origin
|
||||||
|
routing_counter.increment('contextvar_reset_fallback')
|
||||||
|
logger.info("[rocketchat] send via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||||
else:
|
else:
|
||||||
# Priority 2: proaktive Nachricht — use most recent room for this user
|
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||||
rooms = self._user_rooms.get(chat_id, [])
|
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||||
if rooms:
|
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||||
real_room_id = rooms[-1] # last room user was active in
|
if thematic_target:
|
||||||
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
real_room_id = thematic_target
|
||||||
|
logger.debug("[rocketchat] send via Archivar target: %s → %s", chat_id, real_room_id)
|
||||||
else:
|
else:
|
||||||
# Fallback: try to find any room with recent activity involving this user
|
# Priority 2: proaktive Nachricht — use most recent room for this user
|
||||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
rooms = self._user_rooms.get(chat_id, [])
|
||||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
if rooms:
|
||||||
if fallback_room:
|
real_room_id = rooms[-1] # last room user was active in
|
||||||
real_room_id = fallback_room
|
logger.debug("[rocketchat] send via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
|
||||||
else:
|
else:
|
||||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
# Fallback: try to find any room with recent activity involving this user
|
||||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||||
|
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||||
|
if fallback_room:
|
||||||
|
real_room_id = fallback_room
|
||||||
|
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||||
|
else:
|
||||||
|
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||||
|
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||||
|
|
||||||
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
|
# ── Minimal-Fix: Parse [[BUTTONS:...]] markup from agent response text ──
|
||||||
# This allows the agent to request buttons by embedding markup in its
|
# This allows the agent to request buttons by embedding markup in its
|
||||||
# response text, without requiring the gateway to pass metadata.
|
# response text, without requiring the gateway to pass metadata.
|
||||||
# Syntax: [[BUTTONS:yes_no]]Your question here[[/BUTTONS]]
|
# Syntax: [[BUTTONS:yes_no]]Your question here[[/BUTTONS]]
|
||||||
# [[BUTTONS:custom]]Option A|Option B|Option C[[/BUTTONS]]
|
# [[BUTTONS:custom]]Option A|Option B|Option C[[/BUTTONS]]
|
||||||
_btn_re = re.compile(
|
_btn_re = re.compile(
|
||||||
r'\[\[BUTTONS:(?P<template>[a-zA-Z0-9_]+)\]\]'
|
r'\[\[BUTTONS:(?P<template>[a-zA-Z0-9_]+)\]\]'
|
||||||
r'(?P<text>.*?)'
|
r'(?P<text>.*?)'
|
||||||
r'\[\[/BUTTONS\]\]',
|
r'\[\[/BUTTONS\]\]',
|
||||||
re.DOTALL | re.IGNORECASE,
|
re.DOTALL | re.IGNORECASE,
|
||||||
)
|
|
||||||
_match = _btn_re.search(content or "")
|
|
||||||
if _match:
|
|
||||||
_template_name = _match.group("template").lower()
|
|
||||||
_inner_text = _match.group("text").strip()
|
|
||||||
# Strip the markup from content, keep the inner text
|
|
||||||
content = _btn_re.sub(_inner_text, content).strip()
|
|
||||||
# Build synthetic metadata so the existing template path below handles it
|
|
||||||
_valid_templates = {"yes_no", "confirm_cancel", "ok", "multi_choice_3"}
|
|
||||||
if _template_name == "custom" or "|" in _inner_text:
|
|
||||||
# Custom buttons: labels separated by pipe
|
|
||||||
_labels = [l.strip() for l in _inner_text.split("|") if l.strip()]
|
|
||||||
metadata = dict(metadata or {})
|
|
||||||
metadata["template"] = "custom"
|
|
||||||
metadata["custom_buttons"] = _labels
|
|
||||||
metadata["question_id"] = metadata.get("question_id", "custom_btn")
|
|
||||||
metadata.setdefault("button_title", "Wähle eine Option:")
|
|
||||||
elif _template_name in _valid_templates:
|
|
||||||
metadata = dict(metadata or {})
|
|
||||||
metadata["template"] = _template_name
|
|
||||||
metadata["question_id"] = metadata.get("question_id", f"btn_{_template_name}")
|
|
||||||
|
|
||||||
# Handle interaction templates via metadata
|
|
||||||
attachments = None
|
|
||||||
if metadata and metadata.get("template"):
|
|
||||||
# Use sys.modules to access __init__ symbols (plugin loaded as flat module)
|
|
||||||
import sys as _sys
|
|
||||||
_init = _sys.modules.get(__name__.rsplit('.', 1)[0] if '.' in __name__ else __name__)
|
|
||||||
if _init is None:
|
|
||||||
_init = _sys.modules.get('rocketchat')
|
|
||||||
_TEMPLATE_MAP = getattr(_init, '_TEMPLATE_MAP', {})
|
|
||||||
_build_custom_buttons = getattr(_init, '_build_custom_buttons', lambda labels, prefix='', style='default': [])
|
|
||||||
template_name = metadata.get("template")
|
|
||||||
question_id = metadata.get("question_id", "")
|
|
||||||
if template_name == "custom" and metadata.get("custom_buttons"):
|
|
||||||
buttons = _build_custom_buttons(metadata["custom_buttons"], prefix=question_id)
|
|
||||||
if buttons:
|
|
||||||
attachments = [{
|
|
||||||
"color": "#1d74f5",
|
|
||||||
"title": metadata.get("button_title", "Wähle eine Option:"),
|
|
||||||
"actions": buttons,
|
|
||||||
}]
|
|
||||||
elif template_name in _TEMPLATE_MAP:
|
|
||||||
tmpl = _TEMPLATE_MAP[template_name]
|
|
||||||
attachment = dict(tmpl.get("attachment", {}))
|
|
||||||
raw_buttons = tmpl.get("buttons", [])
|
|
||||||
buttons = []
|
|
||||||
for btn in raw_buttons:
|
|
||||||
msg_payload = btn.get("msg", "")
|
|
||||||
if question_id:
|
|
||||||
msg_payload = f"{question_id}::{msg_payload}"
|
|
||||||
buttons.append({
|
|
||||||
"type": "button",
|
|
||||||
"text": btn.get("text", "?"),
|
|
||||||
"msg": msg_payload,
|
|
||||||
"msg_in_chat_window": True,
|
|
||||||
"style": btn.get("style", "default"),
|
|
||||||
})
|
|
||||||
attachment["actions"] = buttons
|
|
||||||
attachments = [attachment]
|
|
||||||
|
|
||||||
# Bug 3 fix: Fallback wenn button_template nicht gerendert werden kann.
|
|
||||||
# Falls metadata ein Template anfordert, aber attachments None bleibt
|
|
||||||
# (z.B. _TEMPLATE_MAP leer, _build_custom_buttons nicht verfügbar),
|
|
||||||
# hänge Text-Fallback an, damit der User weiß, wie er antworten soll.
|
|
||||||
if attachments is None:
|
|
||||||
fallback_lines = []
|
|
||||||
if template_name == "custom" and metadata.get("custom_buttons"):
|
|
||||||
opts = metadata["custom_buttons"]
|
|
||||||
fallback_lines.append("Bitte antworte mit einer der folgenden Optionen:")
|
|
||||||
for i, opt in enumerate(opts, 1):
|
|
||||||
fallback_lines.append(f" {i}. {opt}")
|
|
||||||
elif template_name == "yes_no":
|
|
||||||
fallback_lines.append("Antworte mit 1 (Ja) oder 2 (Nein)")
|
|
||||||
elif template_name == "confirm_cancel":
|
|
||||||
fallback_lines.append("Antworte mit 1 (Bestätigen) oder 2 (Abbrechen)")
|
|
||||||
elif template_name == "ok":
|
|
||||||
fallback_lines.append("Antworte mit 1 (OK)")
|
|
||||||
elif template_name == "multi_choice_3":
|
|
||||||
fallback_lines.append("Antworte mit 1, 2 oder 3")
|
|
||||||
if fallback_lines:
|
|
||||||
content = content + "\n\n" + "\n".join(fallback_lines)
|
|
||||||
logger.debug("[rocketchat] Button template '%s' could not be rendered — using text fallback", template_name)
|
|
||||||
|
|
||||||
# ── Clarify-Queue: remember pending button question ──
|
|
||||||
if metadata and metadata.get("template") and attachments:
|
|
||||||
_tmpl = metadata.get("template")
|
|
||||||
_qid = metadata.get("question_id", "")
|
|
||||||
_expected = []
|
|
||||||
if _tmpl == "yes_no":
|
|
||||||
_expected = ["ja", "nein", "yes", "no"]
|
|
||||||
elif _tmpl == "confirm_cancel":
|
|
||||||
_expected = ["bestätigen", "confirm", "abbrechen", "cancel"]
|
|
||||||
elif _tmpl == "ok":
|
|
||||||
_expected = ["ok", "okay", "verstanden", "alles klar"]
|
|
||||||
elif _tmpl == "custom" and metadata.get("custom_buttons"):
|
|
||||||
_expected = [b.lower() for b in metadata["custom_buttons"]]
|
|
||||||
self._pending_clarifies[real_room_id] = {
|
|
||||||
"question_id": _qid,
|
|
||||||
"template": _tmpl,
|
|
||||||
"expected": _expected,
|
|
||||||
"timestamp": time.time(),
|
|
||||||
"original_text": content,
|
|
||||||
}
|
|
||||||
|
|
||||||
# ── P1-7: Proactive message splitting ────────────────────────
|
|
||||||
# Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen).
|
|
||||||
# Lange Antworten (Tabellen, Listen) werden abgeschnitten mit
|
|
||||||
# "(Response formatting failed, plain text:)" — aber die API
|
|
||||||
# meldet trotzdem success. Daher MÜSSEN wir VOR dem Senden
|
|
||||||
# splitten, nicht erst nach einem Fehlschlag.
|
|
||||||
if len(content) > 3000 and attachments is None:
|
|
||||||
logger.info(
|
|
||||||
"[rocketchat] P1-7: Message too long (%d chars) — proactive split",
|
|
||||||
len(content),
|
|
||||||
)
|
)
|
||||||
return await self._send_split(real_room_id, content)
|
_match = _btn_re.search(content or "")
|
||||||
|
if _match:
|
||||||
|
_template_name = _match.group("template").lower()
|
||||||
|
_inner_text = _match.group("text").strip()
|
||||||
|
# Strip the markup from content, keep the inner text
|
||||||
|
content = _btn_re.sub(_inner_text, content).strip()
|
||||||
|
# Build synthetic metadata so the existing template path below handles it
|
||||||
|
_valid_templates = {"yes_no", "confirm_cancel", "ok", "multi_choice_3"}
|
||||||
|
if _template_name == "custom" or "|" in _inner_text:
|
||||||
|
# Custom buttons: labels separated by pipe
|
||||||
|
_labels = [l.strip() for l in _inner_text.split("|") if l.strip()]
|
||||||
|
metadata = dict(metadata or {})
|
||||||
|
metadata["template"] = "custom"
|
||||||
|
metadata["custom_buttons"] = _labels
|
||||||
|
metadata["question_id"] = metadata.get("question_id", "custom_btn")
|
||||||
|
metadata.setdefault("button_title", "Wähle eine Option:")
|
||||||
|
elif _template_name in _valid_templates:
|
||||||
|
metadata = dict(metadata or {})
|
||||||
|
metadata["template"] = _template_name
|
||||||
|
metadata["question_id"] = metadata.get("question_id", f"btn_{_template_name}")
|
||||||
|
|
||||||
success = await self._post_message_with_retry(real_room_id, content, attachments=attachments)
|
# Handle interaction templates via metadata
|
||||||
if success:
|
attachments = None
|
||||||
# If this message has buttons, mark the room so the next user
|
if metadata and metadata.get("template"):
|
||||||
# message from here stays put (no Archivar routing). Button
|
# Use sys.modules to access __init__ symbols (plugin loaded as flat module)
|
||||||
# responses must be answered in the same room the question was
|
import sys as _sys
|
||||||
# asked, otherwise the user sees "Ich antworte im Zielraum"
|
_init = _sys.modules.get(__name__.rsplit('.', 1)[0] if '.' in __name__ else __name__)
|
||||||
# and the agent loses context.
|
if _init is None:
|
||||||
if attachments:
|
_init = _sys.modules.get('rocketchat')
|
||||||
self._rooms_with_pending_questions.add(real_room_id)
|
_TEMPLATE_MAP = getattr(_init, '_TEMPLATE_MAP', {})
|
||||||
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
|
_build_custom_buttons = getattr(_init, '_build_custom_buttons', lambda labels, prefix='', style='default': [])
|
||||||
# ── B5v6.5: Conversation History — Agent-Antwort aufzeichnen ──
|
template_name = metadata.get("template")
|
||||||
if _MULTIROOM() and self._conversation_history is not None:
|
question_id = metadata.get("question_id", "")
|
||||||
await self._conversation_history.add(real_room_id, "agent", content)
|
if template_name == "custom" and metadata.get("custom_buttons"):
|
||||||
# ── V8.6 P1-3: PresenceEngine — KEIN decrement in send()! ──
|
buttons = _build_custom_buttons(metadata["custom_buttons"], prefix=question_id)
|
||||||
# Der Counter wird NUR im finally-Block von _process_incoming
|
if buttons:
|
||||||
# dekrementiert (line 2794). send() kann mehrfach pro Turn
|
attachments = [{
|
||||||
# aufgerufen werden (Multi-Message, Split) — ein decrement hier
|
"color": "#1d74f5",
|
||||||
# würde den Agenten vorzeitig auf "online" setzen.
|
"title": metadata.get("button_title", "Wähle eine Option:"),
|
||||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
"actions": buttons,
|
||||||
|
}]
|
||||||
|
elif template_name in _TEMPLATE_MAP:
|
||||||
|
tmpl = _TEMPLATE_MAP[template_name]
|
||||||
|
attachment = dict(tmpl.get("attachment", {}))
|
||||||
|
raw_buttons = tmpl.get("buttons", [])
|
||||||
|
buttons = []
|
||||||
|
for btn in raw_buttons:
|
||||||
|
msg_payload = btn.get("msg", "")
|
||||||
|
if question_id:
|
||||||
|
msg_payload = f"{question_id}::{msg_payload}"
|
||||||
|
buttons.append({
|
||||||
|
"type": "button",
|
||||||
|
"text": btn.get("text", "?"),
|
||||||
|
"msg": msg_payload,
|
||||||
|
"msg_in_chat_window": True,
|
||||||
|
"style": btn.get("style", "default"),
|
||||||
|
})
|
||||||
|
attachment["actions"] = buttons
|
||||||
|
attachments = [attachment]
|
||||||
|
|
||||||
|
# Bug 3 fix: Fallback wenn button_template nicht gerendert werden kann.
|
||||||
|
# Falls metadata ein Template anfordert, aber attachments None bleibt
|
||||||
|
# (z.B. _TEMPLATE_MAP leer, _build_custom_buttons nicht verfügbar),
|
||||||
|
# hänge Text-Fallback an, damit der User weiß, wie er antworten soll.
|
||||||
|
if attachments is None:
|
||||||
|
fallback_lines = []
|
||||||
|
if template_name == "custom" and metadata.get("custom_buttons"):
|
||||||
|
opts = metadata["custom_buttons"]
|
||||||
|
fallback_lines.append("Bitte antworte mit einer der folgenden Optionen:")
|
||||||
|
for i, opt in enumerate(opts, 1):
|
||||||
|
fallback_lines.append(f" {i}. {opt}")
|
||||||
|
elif template_name == "yes_no":
|
||||||
|
fallback_lines.append("Antworte mit 1 (Ja) oder 2 (Nein)")
|
||||||
|
elif template_name == "confirm_cancel":
|
||||||
|
fallback_lines.append("Antworte mit 1 (Bestätigen) oder 2 (Abbrechen)")
|
||||||
|
elif template_name == "ok":
|
||||||
|
fallback_lines.append("Antworte mit 1 (OK)")
|
||||||
|
elif template_name == "multi_choice_3":
|
||||||
|
fallback_lines.append("Antworte mit 1, 2 oder 3")
|
||||||
|
if fallback_lines:
|
||||||
|
content = content + "\n\n" + "\n".join(fallback_lines)
|
||||||
|
logger.debug("[rocketchat] Button template '%s' could not be rendered — using text fallback", template_name)
|
||||||
|
|
||||||
|
# ── Clarify-Queue: remember pending button question ──
|
||||||
|
if metadata and metadata.get("template") and attachments:
|
||||||
|
_tmpl = metadata.get("template")
|
||||||
|
_qid = metadata.get("question_id", "")
|
||||||
|
_expected = []
|
||||||
|
if _tmpl == "yes_no":
|
||||||
|
_expected = ["ja", "nein", "yes", "no"]
|
||||||
|
elif _tmpl == "confirm_cancel":
|
||||||
|
_expected = ["bestätigen", "confirm", "abbrechen", "cancel"]
|
||||||
|
elif _tmpl == "ok":
|
||||||
|
_expected = ["ok", "okay", "verstanden", "alles klar"]
|
||||||
|
elif _tmpl == "custom" and metadata.get("custom_buttons"):
|
||||||
|
_expected = [b.lower() for b in metadata["custom_buttons"]]
|
||||||
|
self._pending_clarifies[real_room_id] = {
|
||||||
|
"question_id": _qid,
|
||||||
|
"template": _tmpl,
|
||||||
|
"expected": _expected,
|
||||||
|
"timestamp": time.time(),
|
||||||
|
"original_text": content,
|
||||||
|
}
|
||||||
|
|
||||||
|
# ── P1-7: Proactive message splitting ────────────────────────
|
||||||
|
# Rocket.Chat REST-API hat ein Message-Limit (~4000 Zeichen).
|
||||||
|
# Lange Antworten (Tabellen, Listen) werden abgeschnitten mit
|
||||||
|
# "(Response formatting failed, plain text:)" — aber die API
|
||||||
|
# meldet trotzdem success. Daher MÜSSEN wir VOR dem Senden
|
||||||
|
# splitten, nicht erst nach einem Fehlschlag.
|
||||||
|
if len(content) > 3000 and attachments is None:
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] P1-7: Message too long (%d chars) — proactive split",
|
||||||
|
len(content),
|
||||||
|
)
|
||||||
|
return await self._send_split(real_room_id, content)
|
||||||
|
|
||||||
|
success = await self._post_message_with_retry(real_room_id, content, attachments=attachments)
|
||||||
|
if success:
|
||||||
|
# If this message has buttons, mark the room so the next user
|
||||||
|
# message from here stays put (no Archivar routing). Button
|
||||||
|
# responses must be answered in the same room the question was
|
||||||
|
# asked, otherwise the user sees "Ich antworte im Zielraum"
|
||||||
|
# and the agent loses context.
|
||||||
|
if attachments:
|
||||||
|
self._rooms_with_pending_questions.add(real_room_id)
|
||||||
|
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
|
||||||
|
# ── B5v6.5: Conversation History — Agent-Antwort aufzeichnen ──
|
||||||
|
if _MULTIROOM() and self._conversation_history is not None:
|
||||||
|
await self._conversation_history.add(real_room_id, "agent", content)
|
||||||
|
# ── V8.6 P1-3: PresenceEngine — KEIN decrement in send()! ──
|
||||||
|
# Der Counter wird NUR im finally-Block von _process_incoming
|
||||||
|
# dekrementiert (line 2794). send() kann mehrfach pro Turn
|
||||||
|
# aufgerufen werden (Multi-Message, Split) — ein decrement hier
|
||||||
|
# würde den Agenten vorzeitig auf "online" setzen.
|
||||||
|
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||||
|
|
||||||
|
finally:
|
||||||
|
# ── P1a: Symmetrisches Gate-Release ──
|
||||||
|
if _gate_acquired and task_token:
|
||||||
|
try:
|
||||||
|
self._outbound_gate.release(_gate_room_id, task_token)
|
||||||
|
except BaseException:
|
||||||
|
logger.debug("[rocketchat] P5 V9.x: Gate release in send() finally failed (non-critical)")
|
||||||
return SendResult(success=False, error="chat.postMessage failed")
|
return SendResult(success=False, error="chat.postMessage failed")
|
||||||
|
|
||||||
# ── P1-4: Message Splitting ─────────────────────────────────────────
|
# ── P1-4: Message Splitting ─────────────────────────────────────────
|
||||||
@@ -6942,127 +7060,180 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
if not self.rest.auth_token:
|
if not self.rest.auth_token:
|
||||||
return SendResult(success=False, error="Not authenticated")
|
return SendResult(success=False, error="Not authenticated")
|
||||||
|
|
||||||
# ── Virtual → Real Room Translation ─────────────────────────
|
# ── P5 V9.x: OutboundGate — Parallel-Stream-Schutz ──────────
|
||||||
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
# Gleicher Gate-Check wie in send().
|
||||||
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
_gate_room_id = chat_id
|
||||||
real_room_id = chat_id
|
|
||||||
if chat_id.startswith("user:"):
|
if chat_id.startswith("user:"):
|
||||||
# Priority 0: ContextVar from the message that triggered this turn
|
|
||||||
# P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung.
|
|
||||||
# _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert
|
|
||||||
# vom Parent-Task erben. Wir validieren gegen _room_context task_token,
|
|
||||||
# um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu
|
|
||||||
# verhindern.
|
|
||||||
origin = _CURRENT_ORIGIN_ROOM.get()
|
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||||
if origin:
|
if origin:
|
||||||
# Pre-Read-Validierung: Task-Token-Match prüfen
|
_gate_room_id = origin
|
||||||
current_token = _CURRENT_TASK_TOKEN.get()
|
task_token = _CURRENT_TASK_TOKEN.get()
|
||||||
ctx_entry = _room_context.get(chat_id, {})
|
_gate_acquired = False # P1a: track whether WE created the gate entry
|
||||||
stored_token = ctx_entry.get("task_token", "")
|
if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
|
||||||
# Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen,
|
from archivar.outbound_gate import GateDecision
|
||||||
# normale ContextVar-Logik weiterlaufen lassen
|
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||||
if current_token and stored_token and current_token != stored_token:
|
if not decision.allow:
|
||||||
routing_counter.increment('priority0_token_mismatch_skip')
|
blocking_room = decision.blocking_room_id
|
||||||
logger.info(
|
if blocking_room:
|
||||||
"[rocketchat] send_clarify Priority 0 token mismatch for %s — "
|
try:
|
||||||
"skipping stale ContextVar, falling through to _room_context",
|
await self._outbound_gate.wait_until_clear(
|
||||||
chat_id,
|
blocking_room_id=blocking_room, timeout_s=30.0
|
||||||
|
)
|
||||||
|
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
decision = GateDecision(allow=False, reason="timeout")
|
||||||
|
if not decision.allow:
|
||||||
|
active_room = self._outbound_gate.active_room_id
|
||||||
|
active_name = ""
|
||||||
|
if active_room and active_room in self._room_info:
|
||||||
|
active_name = self._room_info[active_room].get("name", active_room[:12] + "…")
|
||||||
|
quick_reply_text = (
|
||||||
|
f"Ich antworte gerade in #{active_name} — "
|
||||||
|
f"einen Moment bitte, ich bin gleich bei dir."
|
||||||
|
) if active_name else (
|
||||||
|
"Ich antworte gerade in einem anderen Raum — "
|
||||||
|
"einen Moment bitte, ich bin gleich bei dir."
|
||||||
)
|
)
|
||||||
origin = "" # Force fallthrough
|
await self._post_message_unlocked(_gate_room_id, quick_reply_text)
|
||||||
if origin:
|
self._outbound_gate.stats.quick_reply += 1
|
||||||
real_room_id = origin
|
return SendResult(success=True, message_id="quick_reply")
|
||||||
logger.debug("[rocketchat] send_clarify via ContextVar: %s → %s", chat_id, real_room_id)
|
# Fell through: decision.allow is True — track if WE created the entry
|
||||||
else:
|
# (gate_clear = we own it; same_room_same_token = someone else owns it)
|
||||||
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
_gate_acquired = (decision.reason == "gate_clear")
|
||||||
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
|
||||||
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
|
||||||
fallback_origin = _get_room_context_origin(chat_id)
|
|
||||||
if fallback_origin:
|
|
||||||
real_room_id = fallback_origin
|
|
||||||
routing_counter.increment('contextvar_reset_fallback')
|
|
||||||
logger.info("[rocketchat] send_clarify via _room_context fallback: %s → %s", chat_id, real_room_id)
|
|
||||||
else:
|
|
||||||
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
|
||||||
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
|
||||||
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
|
||||||
if thematic_target:
|
|
||||||
real_room_id = thematic_target
|
|
||||||
logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id)
|
|
||||||
else:
|
|
||||||
# Priority 2: proactive message — use most recent room for this user
|
|
||||||
rooms = self._user_rooms.get(chat_id, [])
|
|
||||||
if rooms:
|
|
||||||
real_room_id = rooms[-1] # last room user was active in
|
|
||||||
logger.debug("[rocketchat] send_clarify via user_map (proactive): %s → %s", chat_id, real_room_id)
|
|
||||||
else:
|
|
||||||
# Fallback: try to find any room with recent activity involving this user
|
|
||||||
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
|
||||||
fallback_room = self._find_fallback_room_for_user(chat_id)
|
|
||||||
if fallback_room:
|
|
||||||
real_room_id = fallback_room
|
|
||||||
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
|
||||||
else:
|
|
||||||
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
|
||||||
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
|
||||||
|
|
||||||
# Render full option text in the message body so users
|
|
||||||
# can read long choices that would be truncated in buttons.
|
# ── P1a: try/finally für symmetrisches Gate-Release ─────────
|
||||||
# Buttons keep short numeric labels (1, 2, …, Other).
|
# Bei Exception in send_clarify() hängt sonst der Gate-Eintrag.
|
||||||
text = f"❓ {question}"
|
try:
|
||||||
option_lines = "\n".join(
|
# ── Virtual → Real Room Translation ─────────────────────────
|
||||||
f"{i + 1}. {choice}"
|
# chat_id from Hermes session is virtual (e.g. "user:alice").
|
||||||
for i, choice in enumerate(choices)
|
# We must resolve it to a real Rocket.Chat room_id for REST API.
|
||||||
)
|
real_room_id = chat_id
|
||||||
text += f"\n\n{option_lines}"
|
if chat_id.startswith("user:"):
|
||||||
|
# Priority 0: ContextVar from the message that triggered this turn
|
||||||
# Build buttons with short labels to avoid truncation
|
# P1 Cross-Contamination-Fix: Task-Token-Validierung VOR Verwendung.
|
||||||
button_labels = [str(i + 1) for i in range(len(choices))]
|
# _CURRENT_ORIGIN_ROOM kann in neuen asyncio-Tasks einen stale Wert
|
||||||
buttons = _build_custom_buttons(button_labels, prefix=f"CLARIFY:{clarify_id}")
|
# vom Parent-Task erben. Wir validieren gegen _room_context task_token,
|
||||||
|
# um Cross-Contamination (Auto-Route → Widerspruch → falscher Raum) zu
|
||||||
# Add "Other" button with special handling
|
# verhindern.
|
||||||
buttons.append({
|
origin = _CURRENT_ORIGIN_ROOM.get()
|
||||||
"type": "button",
|
if origin:
|
||||||
"text": "✏️ Other",
|
# Pre-Read-Validierung: Task-Token-Match prüfen
|
||||||
"msg": f"CLARIFY:{clarify_id}:other",
|
current_token = _CURRENT_TASK_TOKEN.get()
|
||||||
"msg_in_chat_window": True,
|
ctx_entry = _room_context.get(chat_id, {})
|
||||||
"style": "default",
|
stored_token = ctx_entry.get("task_token", "")
|
||||||
})
|
# Token-Mismatch: _CURRENT_ORIGIN_ROOM ist stale → skippen,
|
||||||
|
# normale ContextVar-Logik weiterlaufen lassen
|
||||||
# Create attachment with buttons
|
if current_token and stored_token and current_token != stored_token:
|
||||||
attachments = [{
|
routing_counter.increment('priority0_token_mismatch_skip')
|
||||||
"color": "#1d74f5",
|
logger.info(
|
||||||
"title": "Please choose an option:",
|
"[rocketchat] send_clarify Priority 0 token mismatch for %s — "
|
||||||
"actions": buttons,
|
"skipping stale ContextVar, falling through to _room_context",
|
||||||
}]
|
chat_id,
|
||||||
|
)
|
||||||
# Send message with buttons
|
origin = "" # Force fallthrough
|
||||||
success = await self._post_message_with_retry(real_room_id, text, attachments=attachments)
|
if origin:
|
||||||
|
real_room_id = origin
|
||||||
if success:
|
logger.debug("[rocketchat] send_clarify via ContextVar: %s → %s", chat_id, real_room_id)
|
||||||
# Store clarify state for gateway identification
|
else:
|
||||||
self._clarify_state = getattr(self, '_clarify_state', {})
|
# P1: _room_context als persistenter Fallback (Stream-Retry ContextVar-Reset)
|
||||||
self._clarify_state[clarify_id] = session_key
|
# P1 Cross-Contamination-Fix: _get_room_context_origin validiert
|
||||||
|
# Task-Token + TTL, verhindert Cross-Contamination zwischen Räumen.
|
||||||
# For "Other" button, we need to enable text capture mode
|
fallback_origin = _get_room_context_origin(chat_id)
|
||||||
# This is done by calling mark_awaiting_text when the user clicks "Other"
|
if fallback_origin:
|
||||||
# The actual implementation will be in the message handling logic
|
real_room_id = fallback_origin
|
||||||
|
routing_counter.increment('contextvar_reset_fallback')
|
||||||
# Mark room for button response handling (no Archivar routing)
|
logger.info("[rocketchat] send_clarify via _room_context fallback: %s → %s", chat_id, real_room_id)
|
||||||
self._rooms_with_pending_questions.add(real_room_id)
|
else:
|
||||||
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
|
# Priority 1: Archivar-Kontext — nur für proaktive Nachrichten
|
||||||
|
# ohne vorherige Frage (kein _CURRENT_ORIGIN_ROOM gesetzt).
|
||||||
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
thematic_target = _THEMATIC_TARGET_ROOM.get()
|
||||||
else:
|
if thematic_target:
|
||||||
# Fallback to text-based clarify if REST call fails
|
real_room_id = thematic_target
|
||||||
logger.warning("[rocketchat] Failed to send clarify with buttons, falling back to text")
|
logger.debug("[rocketchat] send_clarify via Archivar target: %s → %s", chat_id, real_room_id)
|
||||||
return await super().send_clarify(
|
else:
|
||||||
chat_id=chat_id,
|
# Priority 2: proactive message — use most recent room for this user
|
||||||
question=question,
|
rooms = self._user_rooms.get(chat_id, [])
|
||||||
choices=choices,
|
if rooms:
|
||||||
clarify_id=clarify_id,
|
real_room_id = rooms[-1] # last room user was active in
|
||||||
session_key=session_key,
|
logger.debug("[rocketchat] send_clarify via user_map (proactive): %s → %s", chat_id, real_room_id)
|
||||||
metadata=metadata,
|
else:
|
||||||
|
# Fallback: try to find any room with recent activity involving this user
|
||||||
|
logger.warning("[rocketchat] No mapped room for %s, attempting fallback", chat_id)
|
||||||
|
fallback_room = self._find_fallback_room_for_user(chat_id)
|
||||||
|
if fallback_room:
|
||||||
|
real_room_id = fallback_room
|
||||||
|
logger.info("[rocketchat] Using fallback room %s for %s", fallback_room, chat_id)
|
||||||
|
else:
|
||||||
|
logger.error("[rocketchat] No real room for %s, cannot send", chat_id)
|
||||||
|
return SendResult(success=False, error=f"No real room for virtual chat_id {chat_id}")
|
||||||
|
|
||||||
|
# Render full option text in the message body so users
|
||||||
|
# can read long choices that would be truncated in buttons.
|
||||||
|
# Buttons keep short numeric labels (1, 2, …, Other).
|
||||||
|
text = f"❓ {question}"
|
||||||
|
option_lines = "\n".join(
|
||||||
|
f"{i + 1}. {choice}"
|
||||||
|
for i, choice in enumerate(choices)
|
||||||
)
|
)
|
||||||
|
text += f"\n\n{option_lines}"
|
||||||
|
|
||||||
|
# Build buttons with short labels to avoid truncation
|
||||||
|
button_labels = [str(i + 1) for i in range(len(choices))]
|
||||||
|
buttons = _build_custom_buttons(button_labels, prefix=f"CLARIFY:{clarify_id}")
|
||||||
|
|
||||||
|
# Add "Other" button with special handling
|
||||||
|
buttons.append({
|
||||||
|
"type": "button",
|
||||||
|
"text": "✏️ Other",
|
||||||
|
"msg": f"CLARIFY:{clarify_id}:other",
|
||||||
|
"msg_in_chat_window": True,
|
||||||
|
"style": "default",
|
||||||
|
})
|
||||||
|
|
||||||
|
# Create attachment with buttons
|
||||||
|
attachments = [{
|
||||||
|
"color": "#1d74f5",
|
||||||
|
"title": "Please choose an option:",
|
||||||
|
"actions": buttons,
|
||||||
|
}]
|
||||||
|
|
||||||
|
# Send message with buttons
|
||||||
|
success = await self._post_message_with_retry(real_room_id, text, attachments=attachments)
|
||||||
|
|
||||||
|
if success:
|
||||||
|
# Store clarify state for gateway identification
|
||||||
|
self._clarify_state = getattr(self, '_clarify_state', {})
|
||||||
|
self._clarify_state[clarify_id] = session_key
|
||||||
|
|
||||||
|
# For "Other" button, we need to enable text capture mode
|
||||||
|
# This is done by calling mark_awaiting_text when the user clicks "Other"
|
||||||
|
# The actual implementation will be in the message handling logic
|
||||||
|
|
||||||
|
# Mark room for button response handling (no Archivar routing)
|
||||||
|
self._rooms_with_pending_questions.add(real_room_id)
|
||||||
|
logger.debug("[rocketchat] Room %s marked for button response", real_room_id)
|
||||||
|
|
||||||
|
return SendResult(success=True, message_id=str(int(time.time() * 1000)))
|
||||||
|
else:
|
||||||
|
# Fallback to text-based clarify if REST call fails
|
||||||
|
logger.warning("[rocketchat] Failed to send clarify with buttons, falling back to text")
|
||||||
|
|
||||||
|
finally:
|
||||||
|
# ── P1a: Symmetrisches Gate-Release ──
|
||||||
|
if _gate_acquired and task_token:
|
||||||
|
try:
|
||||||
|
self._outbound_gate.release(_gate_room_id, task_token)
|
||||||
|
except BaseException:
|
||||||
|
logger.debug("[rocketchat] P5 V9.x: Gate release in send_clarify() finally failed (non-critical)")
|
||||||
|
return await super().send_clarify(
|
||||||
|
chat_id=chat_id,
|
||||||
|
question=question,
|
||||||
|
choices=choices,
|
||||||
|
clarify_id=clarify_id,
|
||||||
|
session_key=session_key,
|
||||||
|
metadata=metadata,
|
||||||
|
)
|
||||||
|
|
||||||
async def send_typing(self, chat_id: str, metadata=None) -> None:
|
async def send_typing(self, chat_id: str, metadata=None) -> None:
|
||||||
pass
|
pass
|
||||||
@@ -7143,3 +7314,25 @@ class RocketChatAdapter(BasePlatformAdapter):
|
|||||||
return self.ddp._msg_queue.get(timeout=timeout)
|
return self.ddp._msg_queue.get(timeout=timeout)
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
async def _gate_sweep_loop(self) -> None:
|
||||||
|
"""P5 V9.x W2: Periodischer Sweep stale Gate-Einträge.
|
||||||
|
|
||||||
|
Läuft als asyncio.create_task (nicht threading.Timer).
|
||||||
|
Sweept alle 30s — entfernt Einträge die älter als
|
||||||
|
max_entry_age_s (60s) sind.
|
||||||
|
"""
|
||||||
|
while self._running and not self._shutdown_event.is_set():
|
||||||
|
try:
|
||||||
|
await asyncio.sleep(30.0)
|
||||||
|
if hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
|
||||||
|
swept = self._outbound_gate._sweep_stale_entries()
|
||||||
|
if swept > 0:
|
||||||
|
logger.info(
|
||||||
|
"[rocketchat] P5 V9.x: Gate sweep removed %d stale entries",
|
||||||
|
swept,
|
||||||
|
)
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
break
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug("[rocketchat] P5 V9.x: Gate sweep error: %s", e)
|
||||||
|
|||||||
@@ -18,7 +18,8 @@ date: 2026-06-03
|
|||||||
## Übersicht
|
## Übersicht
|
||||||
|
|
||||||
Der Archivar ist ein Submodul des Rocket.Chat-Plugins, das eingehende Nachrichten
|
Der Archivar ist ein Submodul des Rocket.Chat-Plugins, das eingehende Nachrichten
|
||||||
automatisch klassifiziert und optional in konfigurierte Zielräume weiterleitet.
|
automatisch klassifiziert und optional in konfigurierte Zielräume weiterleitet,
|
||||||
|
und ausgehende Nachrichten über ein opt-in Outbound Gate vor Parallel-Antworten schützt (V9.x).
|
||||||
|
|
||||||
**Kernfunktion:**
|
**Kernfunktion:**
|
||||||
- **Embedding-basierte Klassifikation** via nomic-embed-text (Ollama, localhost:11434)
|
- **Embedding-basierte Klassifikation** via nomic-embed-text (Ollama, localhost:11434)
|
||||||
@@ -105,3 +106,42 @@ Bei Ollama-Ausfall greift diese Heuristik:
|
|||||||
|---|---|---|
|
|---|---|---|
|
||||||
| FRAGE | frage, wie, was ist, warum, hilfe, problem, funktioniert nicht, kaputt, erklären | question, how, why, help, problem, explain |
|
| FRAGE | frage, wie, was ist, warum, hilfe, problem, funktioniert nicht, kaputt, erklären | question, how, why, help, problem, explain |
|
||||||
| ALARM | alarm, hilfe, dringend, sofort, notfall, ausfall, absturz, kritisch | alarm, emergency, urgent, critical, crash, sos |
|
| ALARM | alarm, hilfe, dringend, sofort, notfall, ausfall, absturz, kritisch | alarm, emergency, urgent, critical, crash, sos |
|
||||||
|
|
||||||
|
## Outbound-Sicht V9.x
|
||||||
|
|
||||||
|
Der Archivar schützt seit V9.x auch ausgehende Nachrichten vor Parallel-Antworten
|
||||||
|
in verschiedenen Räumen (Cross-Contamination). Das **OutboundGate** (`outbound_gate.py`)
|
||||||
|
ist eine reine asyncio-Datenstruktur ohne LLM/Embedding-Logik.
|
||||||
|
|
||||||
|
**Funktionsweise:**
|
||||||
|
- `try_acquire(room_id, task_token)`: Async, nicht-blockierend — prüft ob ein anderer Raum sendet.
|
||||||
|
Gibt `GateDecision` zurück mit `allow`, `reason`, `blocking_room_id`.
|
||||||
|
- `release(room_id, task_token)`: Idempotent — gibt den Slot frei.
|
||||||
|
- `wait_until_clear(blocking_room_id, timeout_s)`: Async wait mit Timeout (default 30s).
|
||||||
|
A4: Per-Raum `_waiters` Dict — kein False-Wake-Bug.
|
||||||
|
- `_sweep_stale_entries()`: Räumt hängende Einträge auf (max_entry_age_s=60s).
|
||||||
|
|
||||||
|
**Regeln:**
|
||||||
|
- Leeres Gate → allow (reason="gate_clear")
|
||||||
|
- Gleicher Raum + gleicher Token → allow (Multi-Turn, W3, reason="same_room_same_token")
|
||||||
|
- Gleicher Raum + anderer Token → block (reason="same_room_different_token")
|
||||||
|
- Anderer Raum busy → block (reason="different_room_busy") → wait_until_clear(30s) → Quick-Reply bei Timeout
|
||||||
|
|
||||||
|
**Quick-Reply:** "Ich antworte gerade in #RaumA — einen Moment bitte, ich bin gleich bei dir."
|
||||||
|
Geht über `_post_message_unlocked` (NICHT durch den Gate, sonst Endlosschleife).
|
||||||
|
|
||||||
|
**Integration:**
|
||||||
|
- `adapter.py __init__`: `self._outbound_gate = OutboundGate()`
|
||||||
|
- `adapter.py send()`: Gate-Check nach Red-Flag-Block, vor P1-6 Prefix
|
||||||
|
- `adapter.py send_clarify()`: Gleicher Gate-Check wie send()
|
||||||
|
- `adapter.py _process_incoming finally`: release symmetrisch zu mark_busy_done
|
||||||
|
- `adapter.py _dispatch_agent finally`: release im finally-Block
|
||||||
|
- `archivar.adapter_integration`: `bind_outbound_gate()` Hook
|
||||||
|
|
||||||
|
**Warn-Signale:**
|
||||||
|
- W1: Gate blockiert NIEMALS synchron, nur asyncio.wait_for
|
||||||
|
- W2: release in try/except BaseException im finally-Block
|
||||||
|
- W3: Multi-Turn gleicher Raum gleicher Token = allowed, KEIN neuer Eintrag
|
||||||
|
- W4: Vor Live-Schaltung alle Tests GRÜN
|
||||||
|
|
||||||
|
**Tests:** `plugin/archivar/tests/test_outbound_gate.py` (7 Tests, Marker `@pytest.mark.outbound_gate`)
|
||||||
|
|||||||
@@ -134,6 +134,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._presence_engine = None # P2-2: via set_presence_engine() gesetzt
|
||||||
|
self._outbound_gate = None # P5 V9.x: via bind_outbound_gate() 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
|
||||||
@@ -1185,6 +1186,15 @@ class ArchivarMessageHandler:
|
|||||||
"""
|
"""
|
||||||
self._presence_engine = engine
|
self._presence_engine = engine
|
||||||
|
|
||||||
|
def bind_outbound_gate(self, gate) -> None:
|
||||||
|
"""P5 V9.x: Bindet das OutboundGate für Parallel-Stream-Schutz.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
gate: OutboundGate-Instanz.
|
||||||
|
"""
|
||||||
|
self._outbound_gate = gate
|
||||||
|
logger.info("[archivar] OutboundGate gebunden (V9.x)")
|
||||||
|
|
||||||
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.
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,377 @@
|
|||||||
|
"""
|
||||||
|
P5 V9.x: OutboundGate — Parallel-Stream-Schutz für ausgehende Nachrichten.
|
||||||
|
|
||||||
|
Verhindert dass der Agent gleichzeitig in zwei verschiedenen Räumen
|
||||||
|
antwortet (Cross-Contamination). Mechanisches Gate im Adapter-Layer:
|
||||||
|
- try_acquire: async, nicht-blockierend, prüft ob ein anderer Raum gerade sendet
|
||||||
|
- release: idempotent, gibt den Slot frei
|
||||||
|
- wait_until_clear: async wait mit Timeout für blockierte Streams
|
||||||
|
|
||||||
|
Reine asyncio-Datenstruktur — keine LLM/Embedding-Logik.
|
||||||
|
Zero external dependencies — stdlib only.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Dict, List, Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# ── GateDecision: Rückgabetyp von try_acquire ──────────────────────────────
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class GateDecision:
|
||||||
|
"""Entscheidung des OutboundGate nach try_acquire.
|
||||||
|
|
||||||
|
Felder:
|
||||||
|
allow: True wenn der Slot akquiriert wurde, False wenn blockiert.
|
||||||
|
reason: Grund für die Entscheidung (gate_clear, same_room_same_token,
|
||||||
|
same_room_different_token, different_room_busy).
|
||||||
|
blocking_room_id: Wenn blockiert durch anderen Raum, dessen ID (sonst None).
|
||||||
|
"""
|
||||||
|
|
||||||
|
allow: bool
|
||||||
|
reason: str
|
||||||
|
blocking_room_id: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
# ── TurnHandle: Eintrag im _in_flight Dict ────────────────────────────────
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class _TurnHandle:
|
||||||
|
"""Eintrag im _in_flight Dict — ein aktiver Sendevorgang.
|
||||||
|
|
||||||
|
Felder:
|
||||||
|
task_token: UUID4 Task-Token (aus _CURRENT_TASK_TOKEN).
|
||||||
|
started_at: monotonic timestamp des Eintrags.
|
||||||
|
real_room_id: Rocket.Chat Raum-ID.
|
||||||
|
task: asyncio.Task Referenz (für Cancel/Diagnose).
|
||||||
|
chat_id: Virtuelle Chat-ID (z.B. "user:alice").
|
||||||
|
"""
|
||||||
|
|
||||||
|
task_token: str
|
||||||
|
started_at: float
|
||||||
|
real_room_id: str
|
||||||
|
task: Optional[asyncio.Task] = None
|
||||||
|
chat_id: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
# ── GateStats: 9 Counter für Monitoring ───────────────────────────────────
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class GateStats:
|
||||||
|
"""Statistik-Counter für das OutboundGate.
|
||||||
|
|
||||||
|
Alle Counter starten bei 0 und werden monoton inkrementiert.
|
||||||
|
"""
|
||||||
|
|
||||||
|
acquired_total: int = 0
|
||||||
|
"""Gesamtzahl erfolgreicher try_acquire (neue Einträge)."""
|
||||||
|
|
||||||
|
same_room_same_token: int = 0
|
||||||
|
"""Multi-Turn: gleicher Raum + gleicher Token → allowed, KEIN neuer Eintrag."""
|
||||||
|
|
||||||
|
same_room_different_token: int = 0
|
||||||
|
"""Gleicher Raum, anderer Token → blocked (Stream-Retry-Mismatch)."""
|
||||||
|
|
||||||
|
different_room_blocked: int = 0
|
||||||
|
"""Anderer Raum busy → sofort blocked."""
|
||||||
|
|
||||||
|
different_room_waited: int = 0
|
||||||
|
"""Anderer Raum busy → wait_until_clear erfolgreich (Slot wurde frei)."""
|
||||||
|
|
||||||
|
different_room_timeout: int = 0
|
||||||
|
"""Anderer Raum busy → wait_until_clear Timeout → Quick-Reply."""
|
||||||
|
|
||||||
|
quick_reply: int = 0
|
||||||
|
"""Quick-Reply-Nachrichten gesendet („Ich antworte gerade in #RaumA...“)."""
|
||||||
|
|
||||||
|
stale_swept: int = 0
|
||||||
|
"""Stale Einträge durch _sweep_stale_entries entfernt."""
|
||||||
|
|
||||||
|
released_total: int = 0
|
||||||
|
"""Gesamtzahl release()-Aufrufe (inkl. idempotente)."""
|
||||||
|
|
||||||
|
|
||||||
|
# ── OutboundGate ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
class OutboundGate:
|
||||||
|
"""Mechanisches Gate für ausgehende Nachrichten — Parallel-Stream-Schutz.
|
||||||
|
|
||||||
|
Verhindert dass der Agent gleichzeitig in zwei verschiedenen Räumen
|
||||||
|
antwortet. Der Denkprozess (LLM-Stream) läuft parallel — das Gate
|
||||||
|
greift NUR in der Outbound-Phase (posten der Antwort).
|
||||||
|
|
||||||
|
Architektur:
|
||||||
|
- _in_flight: Dict[room_id → _TurnHandle] — aktuell sendender Raum
|
||||||
|
- _lock: asyncio.Lock für Thread-Safety
|
||||||
|
- _waiters: Dict[room_id → List[asyncio.Event]] — per-Raum wartende Streams
|
||||||
|
(A4: per-Raum Dict statt flat List → kein False-Wake-Bug)
|
||||||
|
|
||||||
|
Warn-Signale:
|
||||||
|
- W1: Gate blockiert NIEMALS synchron, nur asyncio.wait_for
|
||||||
|
- W2: release in try/except BaseException im finally-Block
|
||||||
|
- W3: Multi-Turn gleicher Raum gleicher Token = allowed, KEIN neuer Eintrag
|
||||||
|
- W4: Vor Live-Schaltung alle Tests GRÜN
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
default_timeout_s: float = 30.0,
|
||||||
|
max_entry_age_s: float = 60.0,
|
||||||
|
):
|
||||||
|
"""Initialisiert das OutboundGate.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
default_timeout_s: Default-Timeout für wait_until_clear (30s).
|
||||||
|
max_entry_age_s: Maximales Alter eines Eintrags bevor er als stale gilt (60s).
|
||||||
|
"""
|
||||||
|
self._in_flight: Dict[str, _TurnHandle] = {}
|
||||||
|
self._lock = asyncio.Lock()
|
||||||
|
# A4: Per-Raum Dict statt flat List — kein False-Wake-Bug
|
||||||
|
self._waiters: Dict[str, List[asyncio.Event]] = {}
|
||||||
|
self.default_timeout_s = default_timeout_s
|
||||||
|
self.max_entry_age_s = max_entry_age_s
|
||||||
|
self.stats = GateStats()
|
||||||
|
|
||||||
|
# ── try_acquire (async, nicht-blockierend) ────────────────────────────
|
||||||
|
|
||||||
|
@property
|
||||||
|
def active_room_id(self) -> Optional[str]:
|
||||||
|
"""Gibt die ID des aktuell aktiven Raums zurück (oder None)."""
|
||||||
|
if self._in_flight:
|
||||||
|
return next(iter(self._in_flight))
|
||||||
|
return None
|
||||||
|
|
||||||
|
async def try_acquire(self, room_id: str, task_token: str) -> GateDecision:
|
||||||
|
"""Versucht den Gate-Slot für einen Raum zu akquirieren.
|
||||||
|
|
||||||
|
ASYNC — verwendet asyncio.Lock für Thread-Safety.
|
||||||
|
NICHT-blockierend — gibt sofort GateDecision zurück.
|
||||||
|
|
||||||
|
Logik:
|
||||||
|
- _in_flight leer → allow (neuer Eintrag), reason="gate_clear"
|
||||||
|
- gleicher Raum + gleicher Token → allow (W3: Multi-Turn, KEIN neuer Eintrag),
|
||||||
|
reason="same_room_same_token"
|
||||||
|
- gleicher Raum + anderer Token → block (same_room_different_token)
|
||||||
|
- anderer Raum in _in_flight → block (different_room_busy)
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: Rocket.Chat Raum-ID.
|
||||||
|
task_token: UUID4 Task-Token (aus _CURRENT_TASK_TOKEN).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
GateDecision mit allow, reason, blocking_room_id.
|
||||||
|
"""
|
||||||
|
async with self._lock:
|
||||||
|
if room_id in self._in_flight:
|
||||||
|
existing = self._in_flight[room_id]
|
||||||
|
if existing.task_token == task_token:
|
||||||
|
# W3: Multi-Turn — gleicher Raum, gleicher Token
|
||||||
|
self.stats.same_room_same_token += 1
|
||||||
|
logger.debug(
|
||||||
|
"[outbound_gate] Multi-Turn allowed: room=%s token=%s",
|
||||||
|
room_id[:8], task_token[:8],
|
||||||
|
)
|
||||||
|
return GateDecision(
|
||||||
|
allow=True,
|
||||||
|
reason="same_room_same_token",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# Gleicher Raum, anderer Token → Stream-Retry-Mismatch
|
||||||
|
self.stats.same_room_different_token += 1
|
||||||
|
logger.info(
|
||||||
|
"[outbound_gate] Same room, different token blocked: "
|
||||||
|
"room=%s existing_token=%s new_token=%s",
|
||||||
|
room_id[:8], existing.task_token[:8], task_token[:8],
|
||||||
|
)
|
||||||
|
return GateDecision(
|
||||||
|
allow=False,
|
||||||
|
reason="same_room_different_token",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Prüfe ob ein anderer Raum aktiv ist
|
||||||
|
if self._in_flight:
|
||||||
|
# Ein anderer Raum sendet gerade → block
|
||||||
|
active_room = next(iter(self._in_flight))
|
||||||
|
self.stats.different_room_blocked += 1
|
||||||
|
logger.info(
|
||||||
|
"[outbound_gate] Different room blocked: "
|
||||||
|
"requested=%s active=%s",
|
||||||
|
room_id[:8], active_room[:8],
|
||||||
|
)
|
||||||
|
return GateDecision(
|
||||||
|
allow=False,
|
||||||
|
reason="different_room_busy",
|
||||||
|
blocking_room_id=active_room,
|
||||||
|
)
|
||||||
|
|
||||||
|
# _in_flight ist leer → allow
|
||||||
|
handle = _TurnHandle(
|
||||||
|
task_token=task_token,
|
||||||
|
started_at=time.monotonic(),
|
||||||
|
real_room_id=room_id,
|
||||||
|
)
|
||||||
|
self._in_flight[room_id] = handle
|
||||||
|
self.stats.acquired_total += 1
|
||||||
|
logger.debug(
|
||||||
|
"[outbound_gate] Acquired: room=%s token=%s",
|
||||||
|
room_id[:8], task_token[:8],
|
||||||
|
)
|
||||||
|
return GateDecision(
|
||||||
|
allow=True,
|
||||||
|
reason="gate_clear",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── release (idempotent) ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
def release(self, room_id: str, task_token: str) -> None:
|
||||||
|
"""Gibt den Gate-Slot für einen Raum frei.
|
||||||
|
|
||||||
|
Idempotent: kein Fehler wenn der Raum nicht in _in_flight ist.
|
||||||
|
Token-Check: nur releasen wenn der Token matched.
|
||||||
|
|
||||||
|
Setzt alle wartenden Events für diesen Raum (_waiters[room_id])
|
||||||
|
damit blockierte Streams ihren wait_until_clear auflösen können.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
room_id: Rocket.Chat Raum-ID.
|
||||||
|
task_token: UUID4 Task-Token (muss mit _in_flight übereinstimmen).
|
||||||
|
"""
|
||||||
|
if room_id not in self._in_flight:
|
||||||
|
logger.debug(
|
||||||
|
"[outbound_gate] Release on non-existent room: %s (idempotent)",
|
||||||
|
room_id[:8],
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
existing = self._in_flight[room_id]
|
||||||
|
if existing.task_token != task_token:
|
||||||
|
logger.warning(
|
||||||
|
"[outbound_gate] Release token mismatch: "
|
||||||
|
"room=%s expected=%s got=%s — skipping",
|
||||||
|
room_id[:8], existing.task_token[:8], task_token[:8],
|
||||||
|
)
|
||||||
|
return
|
||||||
|
|
||||||
|
del self._in_flight[room_id]
|
||||||
|
self.stats.released_total += 1
|
||||||
|
logger.debug(
|
||||||
|
"[outbound_gate] Released: room=%s token=%s",
|
||||||
|
room_id[:8], task_token[:8],
|
||||||
|
)
|
||||||
|
|
||||||
|
# Alle wartenden Streams für diesen Raum aufwecken (A4: per-Raum)
|
||||||
|
self._notify_waiters(room_id)
|
||||||
|
|
||||||
|
def _notify_waiters(self, room_id: str) -> None:
|
||||||
|
"""Setzt alle wartenden Events für einen Raum und leert die Liste.
|
||||||
|
|
||||||
|
A4: Per-Raum Notification — nur Streams die auf DIESEN Raum warten
|
||||||
|
werden aufgeweckt. Kein False-Wake-Bug.
|
||||||
|
"""
|
||||||
|
if room_id not in self._waiters:
|
||||||
|
return
|
||||||
|
waiters = self._waiters.pop(room_id)
|
||||||
|
for event in waiters:
|
||||||
|
event.set()
|
||||||
|
logger.debug(
|
||||||
|
"[outbound_gate] Notified %d waiters for room=%s",
|
||||||
|
len(waiters), room_id[:8],
|
||||||
|
)
|
||||||
|
|
||||||
|
# ── wait_until_clear (async mit Timeout) ─────────────────────────────
|
||||||
|
|
||||||
|
async def wait_until_clear(
|
||||||
|
self,
|
||||||
|
blocking_room_id: str,
|
||||||
|
timeout_s: Optional[float] = None,
|
||||||
|
) -> None:
|
||||||
|
"""Wartet asynchron bis der Gate-Slot frei wird.
|
||||||
|
|
||||||
|
W1: NIEMALS synchron blockieren — nur asyncio.wait_for.
|
||||||
|
|
||||||
|
A4: blocking_room_id Parameter — der Stream wartet spezifisch darauf
|
||||||
|
dass DIESER Raum released wird. Events werden per-Raum registriert
|
||||||
|
(_waiters[blocking_room_id]), kein False-Wake-Bug.
|
||||||
|
|
||||||
|
Erzeugt ein asyncio.Event, registriert es in _waiters[blocking_room_id]
|
||||||
|
und wartet mit Timeout. Wenn der aktive Stream release() aufruft,
|
||||||
|
werden die Events für diesen Raum gesetzt.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
blocking_room_id: ID des Raums der gerade sendet (aus
|
||||||
|
GateDecision.blocking_room_id).
|
||||||
|
timeout_s: Timeout in Sekunden. None = default_timeout_s.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
asyncio.TimeoutError: Wenn der Timeout erreicht wird bevor
|
||||||
|
der Slot frei wird.
|
||||||
|
"""
|
||||||
|
if timeout_s is None:
|
||||||
|
timeout_s = self.default_timeout_s
|
||||||
|
|
||||||
|
# Prüfe ob bereits frei (Race-Condition-Schutz)
|
||||||
|
if blocking_room_id not in self._in_flight:
|
||||||
|
return
|
||||||
|
|
||||||
|
event = asyncio.Event()
|
||||||
|
self._waiters.setdefault(blocking_room_id, []).append(event)
|
||||||
|
|
||||||
|
try:
|
||||||
|
await asyncio.wait_for(event.wait(), timeout=timeout_s)
|
||||||
|
# Event wurde gesetzt → Slot wurde frei
|
||||||
|
self.stats.different_room_waited += 1
|
||||||
|
logger.info("[outbound_gate] Wait resolved: slot became free")
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
# Timeout → Quick-Reply
|
||||||
|
self.stats.different_room_timeout += 1
|
||||||
|
# Cleanup: Event aus _waiters[blocking_room_id] entfernen
|
||||||
|
if blocking_room_id in self._waiters:
|
||||||
|
if event in self._waiters[blocking_room_id]:
|
||||||
|
self._waiters[blocking_room_id].remove(event)
|
||||||
|
if not self._waiters[blocking_room_id]:
|
||||||
|
del self._waiters[blocking_room_id]
|
||||||
|
logger.info(
|
||||||
|
"[outbound_gate] Wait timeout after %.1fs → Quick-Reply",
|
||||||
|
timeout_s,
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
|
||||||
|
# ── _sweep_stale_entries ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _sweep_stale_entries(self) -> int:
|
||||||
|
"""Entfernt Einträge die älter als max_entry_age_s sind.
|
||||||
|
|
||||||
|
Wird periodisch (alle 30s) aufgerufen um hängende Einträge
|
||||||
|
zu bereinigen (z.B. wenn release() nie aufgerufen wurde).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Anzahl der entfernten Einträge.
|
||||||
|
"""
|
||||||
|
now = time.monotonic()
|
||||||
|
stale_rooms = []
|
||||||
|
|
||||||
|
for room_id, handle in self._in_flight.items():
|
||||||
|
age = now - handle.started_at
|
||||||
|
if age > self.max_entry_age_s:
|
||||||
|
stale_rooms.append(room_id)
|
||||||
|
logger.warning(
|
||||||
|
"[outbound_gate] Stale entry: room=%s age=%.1fs token=%s",
|
||||||
|
room_id[:8], age, handle.task_token[:8],
|
||||||
|
)
|
||||||
|
|
||||||
|
for room_id in stale_rooms:
|
||||||
|
del self._in_flight[room_id]
|
||||||
|
|
||||||
|
if stale_rooms:
|
||||||
|
self.stats.stale_swept += len(stale_rooms)
|
||||||
|
# Alle wartenden Streams für stale Räume aufwecken
|
||||||
|
for room_id in stale_rooms:
|
||||||
|
self._notify_waiters(room_id)
|
||||||
|
|
||||||
|
return len(stale_rooms)
|
||||||
@@ -16,6 +16,13 @@ from pathlib import Path
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
# P5 V9.x: OutboundGate Marker registrieren
|
||||||
|
def pytest_configure(config):
|
||||||
|
config.addinivalue_line(
|
||||||
|
"markers", "outbound_gate: P5 V9.x OutboundGate Parallel-Stream-Schutz Tests"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def temp_room_map_path():
|
def temp_room_map_path():
|
||||||
"""Erzeugt eine temporäre room-map.json mit minimalem Test-Setup.
|
"""Erzeugt eine temporäre room-map.json mit minimalem Test-Setup.
|
||||||
|
|||||||
@@ -0,0 +1,282 @@
|
|||||||
|
"""
|
||||||
|
P5 V9.x: OutboundGate — Unit-Tests für Parallel-Stream-Schutz.
|
||||||
|
|
||||||
|
Testet die OutboundGate-Klasse isoliert (keine Live-RC-Abhängigkeit).
|
||||||
|
Verwendet asyncio für synthetische Streams.
|
||||||
|
|
||||||
|
Marker: @pytest.mark.outbound_gate
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
# Ensure plugin package is importable (same pattern as other archivar tests)
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||||
|
|
||||||
|
from plugin.archivar.outbound_gate import OutboundGate, GateStats, GateDecision
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# 5.1: Zwei synthetische Streams — A blockiert B, B wartet, A released, B sendet
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
@pytest.mark.outbound_gate
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_outbound_gate_waits_then_releases():
|
||||||
|
"""5.1: Stream A acquires gate, B waits, A releases, B acquires and sends.
|
||||||
|
|
||||||
|
Szenario:
|
||||||
|
- Raum A (room_a) startet Stream mit Token A
|
||||||
|
- Raum B (room_b) versucht zu senden → blocked, wartet
|
||||||
|
- Raum A released → B kann senden
|
||||||
|
"""
|
||||||
|
gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=60.0)
|
||||||
|
|
||||||
|
room_a = "ROOM_A_ID_123456789"
|
||||||
|
room_b = "ROOM_B_ID_987654321"
|
||||||
|
token_a = "token-aaaa-bbbb-cccc"
|
||||||
|
token_b = "token-xxxx-yyyy-zzzz"
|
||||||
|
|
||||||
|
# Stream A acquires the gate (A3: async, returns GateDecision)
|
||||||
|
decision_a = await gate.try_acquire(room_a, token_a)
|
||||||
|
assert decision_a.allow is True, "Stream A should acquire the gate (empty)"
|
||||||
|
assert decision_a.reason == "gate_clear"
|
||||||
|
|
||||||
|
# Stream B tries to acquire — should be blocked (different room)
|
||||||
|
decision_b = await gate.try_acquire(room_b, token_b)
|
||||||
|
assert decision_b.allow is False, "Stream B should be blocked (different room busy)"
|
||||||
|
assert decision_b.reason == "different_room_busy"
|
||||||
|
assert decision_b.blocking_room_id == room_a
|
||||||
|
|
||||||
|
# Verify stats
|
||||||
|
assert gate.stats.acquired_total == 1
|
||||||
|
assert gate.stats.different_room_blocked == 1
|
||||||
|
|
||||||
|
# B waits for gate to clear (A4: blocking_room_id parameter)
|
||||||
|
wait_task = asyncio.create_task(
|
||||||
|
gate.wait_until_clear(blocking_room_id=room_a, timeout_s=5.0)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Give B a moment to start waiting
|
||||||
|
await asyncio.sleep(0.05)
|
||||||
|
|
||||||
|
# A releases
|
||||||
|
gate.release(room_a, token_a)
|
||||||
|
assert gate.stats.released_total == 1
|
||||||
|
|
||||||
|
# B's wait should resolve
|
||||||
|
await asyncio.wait_for(wait_task, timeout=2.0)
|
||||||
|
|
||||||
|
# Now B can acquire
|
||||||
|
decision_b_retry = await gate.try_acquire(room_b, token_b)
|
||||||
|
assert decision_b_retry.allow is True, "Stream B should acquire after A released"
|
||||||
|
assert decision_b_retry.reason == "gate_clear"
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
gate.release(room_b, token_b)
|
||||||
|
assert gate.stats.released_total == 2
|
||||||
|
assert gate.stats.different_room_waited == 1
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# 5.2: Timeout triggert Quick-Reply
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
@pytest.mark.outbound_gate
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_outbound_gate_timeout_triggers_quick_reply():
|
||||||
|
"""5.2: Stream A hängt, B timeout nach 1s → Quick-Reply.
|
||||||
|
|
||||||
|
Szenario:
|
||||||
|
- Raum A hält das Gate (simuliert hängenden Stream)
|
||||||
|
- Raum B wartet mit 1s Timeout
|
||||||
|
- Timeout tritt ein → B bekommt Timeout, Quick-Reply wird getriggert
|
||||||
|
"""
|
||||||
|
gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=60.0)
|
||||||
|
|
||||||
|
room_a = "ROOM_A_HANGING"
|
||||||
|
room_b = "ROOM_B_QUICKREPLY"
|
||||||
|
token_a = "token-hang-aaaa"
|
||||||
|
token_b = "token-qr-bbbb"
|
||||||
|
|
||||||
|
# Stream A acquires
|
||||||
|
await gate.try_acquire(room_a, token_a)
|
||||||
|
|
||||||
|
# Stream B tries to acquire → blocked
|
||||||
|
decision_b = await gate.try_acquire(room_b, token_b)
|
||||||
|
assert decision_b.allow is False
|
||||||
|
assert decision_b.blocking_room_id == room_a
|
||||||
|
|
||||||
|
# B waits with short timeout (1s) — A4: blocking_room_id
|
||||||
|
try:
|
||||||
|
await gate.wait_until_clear(blocking_room_id=room_a, timeout_s=1.0)
|
||||||
|
# Should not reach here — timeout expected
|
||||||
|
timeout_occurred = False
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
timeout_occurred = True
|
||||||
|
|
||||||
|
assert timeout_occurred is True, "B should timeout after 1s"
|
||||||
|
assert gate.stats.different_room_timeout == 1
|
||||||
|
|
||||||
|
# Quick-Reply counter should be incremented
|
||||||
|
gate.stats.quick_reply += 1
|
||||||
|
assert gate.stats.quick_reply == 1
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
gate.release(room_a, token_a)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# 5.3: Multi-Turn gleicher Raum gleicher Token = allowed
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
@pytest.mark.outbound_gate
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_outbound_gate_multi_turn_same_room_allowed():
|
||||||
|
"""5.3: Gleicher Raum + gleicher Token = allowed (Multi-Turn).
|
||||||
|
|
||||||
|
Szenario (W3):
|
||||||
|
- Raum A sendet erste Antwort (Token A) → acquire
|
||||||
|
- Raum A sendet zweite Antwort (gleicher Token A) VOR release
|
||||||
|
→ allowed, KEIN neuer Eintrag (same_room_same_token)
|
||||||
|
- Raum A sendet dritte Antwort (gleicher Token A) VOR release
|
||||||
|
→ allowed again
|
||||||
|
- Release → Slot wird frei
|
||||||
|
"""
|
||||||
|
gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=60.0)
|
||||||
|
|
||||||
|
room_a = "ROOM_A_MULTITURN"
|
||||||
|
token_a = "token-multi-a"
|
||||||
|
|
||||||
|
# First turn: acquire (creates entry)
|
||||||
|
decision_1 = await gate.try_acquire(room_a, token_a)
|
||||||
|
assert decision_1.allow is True
|
||||||
|
assert decision_1.reason == "gate_clear"
|
||||||
|
assert gate.stats.acquired_total == 1
|
||||||
|
|
||||||
|
# Second turn: same room, same token, BEFORE release → allowed (W3)
|
||||||
|
decision_2 = await gate.try_acquire(room_a, token_a)
|
||||||
|
assert decision_2.allow is True, "Multi-Turn same room same token should be allowed"
|
||||||
|
assert decision_2.reason == "same_room_same_token"
|
||||||
|
assert gate.stats.same_room_same_token == 1
|
||||||
|
# acquired_total should NOT increment for same_room_same_token (W3: KEIN neuer Eintrag)
|
||||||
|
assert gate.stats.acquired_total == 1, "Multi-Turn should NOT create new entry"
|
||||||
|
|
||||||
|
# Third turn: same room, same token, BEFORE release → allowed again
|
||||||
|
decision_3 = await gate.try_acquire(room_a, token_a)
|
||||||
|
assert decision_3.allow is True
|
||||||
|
assert decision_3.reason == "same_room_same_token"
|
||||||
|
assert gate.stats.same_room_same_token == 2
|
||||||
|
assert gate.stats.acquired_total == 1 # Still 1 — no new entries
|
||||||
|
|
||||||
|
# Release (once — only one entry exists)
|
||||||
|
gate.release(room_a, token_a)
|
||||||
|
assert gate.stats.released_total == 1
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# 5.4: Stream-Retry Mismatch — Token X angelegt, Token Y abgelehnt
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
@pytest.mark.outbound_gate
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_outbound_gate_stream_retry_mismatch():
|
||||||
|
"""5.4: Token X im Gate, Token Y (anderer Task) wird abgelehnt.
|
||||||
|
|
||||||
|
Szenario:
|
||||||
|
- Raum A hat Token X im Gate (Stream läuft)
|
||||||
|
- Gleicher Raum A, aber Token Y (anderer asyncio-Task, Stream-Retry)
|
||||||
|
→ blocked (same_room_different_token)
|
||||||
|
"""
|
||||||
|
gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=60.0)
|
||||||
|
|
||||||
|
room_a = "ROOM_A_RETRY"
|
||||||
|
token_x = "token-original-x"
|
||||||
|
token_y = "token-retry-y"
|
||||||
|
|
||||||
|
# Token X acquires
|
||||||
|
decision_x = await gate.try_acquire(room_a, token_x)
|
||||||
|
assert decision_x.allow is True
|
||||||
|
assert decision_x.reason == "gate_clear"
|
||||||
|
assert gate.stats.acquired_total == 1
|
||||||
|
|
||||||
|
# Token Y (same room, different token) → blocked
|
||||||
|
decision_y = await gate.try_acquire(room_a, token_y)
|
||||||
|
assert decision_y.allow is False, "Different token in same room should be blocked"
|
||||||
|
assert decision_y.reason == "same_room_different_token"
|
||||||
|
assert gate.stats.same_room_different_token == 1
|
||||||
|
|
||||||
|
# Verify _in_flight still has token_x
|
||||||
|
assert room_a in gate._in_flight
|
||||||
|
assert gate._in_flight[room_a].task_token == token_x
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
gate.release(room_a, token_x)
|
||||||
|
assert gate.stats.released_total == 1
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Zusatz: release Idempotenz
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
@pytest.mark.outbound_gate
|
||||||
|
def test_outbound_gate_release_idempotent():
|
||||||
|
"""Release auf nicht-existierendem Raum ist idempotent (kein Fehler)."""
|
||||||
|
gate = OutboundGate()
|
||||||
|
# Release on empty gate — should not raise
|
||||||
|
gate.release("NONEXISTENT", "token-xyz")
|
||||||
|
assert gate.stats.released_total == 0 # Nothing to release
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Zusatz: Stale Entry Sweep
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
@pytest.mark.outbound_gate
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_outbound_gate_sweep_stale_entries():
|
||||||
|
"""Stale Einträge (älter als max_entry_age_s) werden aufgeräumt."""
|
||||||
|
gate = OutboundGate(default_timeout_s=30.0, max_entry_age_s=0.1) # 100ms TTL
|
||||||
|
|
||||||
|
room_a = "ROOM_STALE"
|
||||||
|
token_a = "token-stale"
|
||||||
|
|
||||||
|
await gate.try_acquire(room_a, token_a)
|
||||||
|
assert room_a in gate._in_flight
|
||||||
|
|
||||||
|
# Wait for entry to become stale
|
||||||
|
await asyncio.sleep(0.2)
|
||||||
|
|
||||||
|
# Sweep
|
||||||
|
swept = gate._sweep_stale_entries()
|
||||||
|
assert swept >= 1
|
||||||
|
assert gate.stats.stale_swept >= 1
|
||||||
|
assert room_a not in gate._in_flight
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# Zusatz: GateStats Defaults
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
@pytest.mark.outbound_gate
|
||||||
|
def test_outbound_gate_stats_defaults():
|
||||||
|
"""GateStats initialisiert alle 9 Counter auf 0."""
|
||||||
|
stats = GateStats()
|
||||||
|
assert stats.acquired_total == 0
|
||||||
|
assert stats.same_room_same_token == 0
|
||||||
|
assert stats.same_room_different_token == 0
|
||||||
|
assert stats.different_room_blocked == 0
|
||||||
|
assert stats.different_room_waited == 0
|
||||||
|
assert stats.different_room_timeout == 0
|
||||||
|
assert stats.quick_reply == 0
|
||||||
|
assert stats.stale_swept == 0
|
||||||
|
assert stats.released_total == 0
|
||||||
@@ -803,3 +803,79 @@ class TestPriority0MismatchTelemetry:
|
|||||||
f"routing_counter 'priority0_token_mismatch_skip' should increment on "
|
f"routing_counter 'priority0_token_mismatch_skip' should increment on "
|
||||||
f"mismatch. Before: {counter_before}, After: {counter_after}"
|
f"mismatch. Before: {counter_before}, After: {counter_after}"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
# P1c: connect() auf frischem Adapter wirft kein AttributeError
|
||||||
|
# ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
|
@pytest.mark.outbound_gate
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_connect_fresh_adapter_no_attribute_error():
|
||||||
|
"""P1c: connect() auf frischem Adapter (ohne _gate_sweep_task) wirft kein AttributeError.
|
||||||
|
|
||||||
|
Beim ersten connect()-Aufruf nach Adapter-Instanziierung existiert
|
||||||
|
_gate_sweep_task noch nicht als Attribut. Der getattr-Schutz in connect()
|
||||||
|
muss das abfangen (Konsistenz mit disconnect() Z.6519).
|
||||||
|
|
||||||
|
Regression: Vor P1c-Fix griff connect() direkt auf self._gate_sweep_task
|
||||||
|
zu (Z.1936), was beim ersten Aufruf AttributeError warf.
|
||||||
|
"""
|
||||||
|
import asyncio
|
||||||
|
import threading
|
||||||
|
from unittest.mock import AsyncMock, MagicMock, patch
|
||||||
|
|
||||||
|
from plugin.adapter import RocketChatAdapter
|
||||||
|
|
||||||
|
# Adapter ohne __init__ (Pattern wie andere Tests in dieser Datei)
|
||||||
|
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||||
|
|
||||||
|
# Minimal-Mocks für connect()-Pfad
|
||||||
|
adapter.base_url = "https://rc.example.com"
|
||||||
|
adapter.user = "testuser"
|
||||||
|
adapter.password = "testpass"
|
||||||
|
adapter.rest = MagicMock()
|
||||||
|
adapter.rest.login = MagicMock(return_value=True)
|
||||||
|
adapter.rest.auth_token = "mock-token"
|
||||||
|
adapter.rest.user_id = "mock-user-id"
|
||||||
|
adapter.rest.get_rooms = MagicMock(return_value=[])
|
||||||
|
adapter._rooms = []
|
||||||
|
adapter._subscribed_rooms = set()
|
||||||
|
adapter._room_info = {}
|
||||||
|
adapter._user_rooms = {}
|
||||||
|
adapter._excluded_room_ids = set()
|
||||||
|
adapter._shutdown_event = threading.Event()
|
||||||
|
adapter._running = False
|
||||||
|
adapter.archivar = None
|
||||||
|
adapter._outbound_gate = MagicMock()
|
||||||
|
|
||||||
|
# Mock _mark_connected (BasePlatformAdapter-Methode)
|
||||||
|
adapter._mark_connected = MagicMock()
|
||||||
|
# Mock _listen_loop und _gate_sweep_loop (AsyncMock für create_task)
|
||||||
|
adapter._listen_loop = AsyncMock()
|
||||||
|
adapter._gate_sweep_loop = AsyncMock()
|
||||||
|
# Mock _sync_room_map_with_membership
|
||||||
|
adapter._sync_room_map_with_membership = MagicMock()
|
||||||
|
|
||||||
|
# Precondition: _gate_sweep_task existiert NICHT (das ist der Bug-Fall)
|
||||||
|
assert not hasattr(adapter, '_gate_sweep_task'), \
|
||||||
|
"Precondition: _gate_sweep_task must not exist on fresh adapter"
|
||||||
|
|
||||||
|
mock_ddp = MagicMock()
|
||||||
|
mock_ddp.connect_and_login = MagicMock(return_value=True)
|
||||||
|
mock_ddp.connected = True
|
||||||
|
mock_ddp.get_logged_in_username = MagicMock(return_value="testuser")
|
||||||
|
mock_ddp.subscribe_room_events = MagicMock(return_value="sub-1")
|
||||||
|
mock_ddp.subscribe_room = MagicMock(return_value="sub-room-1")
|
||||||
|
mock_ddp.bind_loop = MagicMock()
|
||||||
|
|
||||||
|
with patch("plugin.adapter.DDPClient", return_value=mock_ddp), \
|
||||||
|
patch("archivar.onboarding.cleanup_stale_locks", return_value=0), \
|
||||||
|
patch("plugin.adapter._MULTIROOM", return_value=False):
|
||||||
|
result = await adapter.connect(is_reconnect=False)
|
||||||
|
|
||||||
|
assert result is True, "connect() should return True"
|
||||||
|
assert hasattr(adapter, '_gate_sweep_task'), \
|
||||||
|
"connect() should create _gate_sweep_task"
|
||||||
|
assert adapter._gate_sweep_task is not None, \
|
||||||
|
"_gate_sweep_task should be a valid asyncio.Task"
|
||||||
|
|||||||
Reference in New Issue
Block a user