P5 V9.x: P1a/P1b/P1c — Gate-Release-Symmetrie, Sweep-Cancel, Re-create-Guard

P1a: try/finally in send() und send_clarify() für symmetrisches Gate-Release
- _gate_acquired Flag trackt ob try_acquire den Eintrag erstellt hat
- finally-Block released nur wenn _gate_acquired=True und task_token gesetzt
- Verhindert hängende Gate-Einträge bei Exceptions in send()/send_clarify()

P1b: _gate_sweep_task.cancel() in disconnect()
- Sweep-Loop wird vor _mark_disconnected() gecancelled
- self._running = False gesetzt (Sweep-Loop prüft _running Flag)
- Verhindert dass Sweep-Task nach disconnect() weiterläuft

P1c: Sweep-Task-Check vor Re-create in connect()
- Prüft ob _gate_sweep_task existiert und nicht done() ist
- Cancelled alten Task vor create_task() des neuen
- Verhindert doppelte Sweep-Tasks bei Reconnect
This commit is contained in:
Bernd (Hermes)
2026-07-30 08:59:19 +02:00
parent 1958a53f0e
commit 54edbb57f7
+40
View File
@@ -1932,6 +1932,9 @@ class RocketChatAdapter(BasePlatformAdapter):
self._running = True
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 ──
if self._gate_sweep_task is not None and not self._gate_sweep_task.done():
self._gate_sweep_task.cancel()
self._gate_sweep_task = asyncio.create_task(self._gate_sweep_loop())
self._last_activity = time.time()
logger.info("[rocketchat] Listen loop started, _running=%s", self._running)
@@ -6512,6 +6515,12 @@ class RocketChatAdapter(BasePlatformAdapter):
return text
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._shutdown_event.set()
if self._status_timer:
@@ -6599,6 +6608,7 @@ class RocketChatAdapter(BasePlatformAdapter):
if origin:
_gate_room_id = origin
task_token = _CURRENT_TASK_TOKEN.get()
_gate_acquired = False # P1a: track whether WE created the gate entry
if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
from archivar.outbound_gate import GateDecision
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
@@ -6635,7 +6645,13 @@ class RocketChatAdapter(BasePlatformAdapter):
_gate_room_id[:8], active_name,
)
return SendResult(success=True, message_id="quick_reply")
# Fell through: decision.allow is True — track if WE created the entry
# (gate_clear = we own it; same_room_same_token = someone else owns it)
_gate_acquired = (decision.reason == "gate_clear")
# ── P1a: try/finally für symmetrisches Gate-Release ─────────
# Bei Exception in send() hängt sonst der Gate-Eintrag.
try:
# ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ──────────
# Hermes Core sendet Meldungen mit /approve, /deny etc.
# Rocket.Chat unterstützt keine /-Befehle → :: Varianten einsetzen.
@@ -6854,6 +6870,14 @@ class RocketChatAdapter(BasePlatformAdapter):
# 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")
# ── P1-4: Message Splitting ─────────────────────────────────────────
@@ -7043,6 +7067,7 @@ class RocketChatAdapter(BasePlatformAdapter):
if origin:
_gate_room_id = origin
task_token = _CURRENT_TASK_TOKEN.get()
_gate_acquired = False # P1a: track whether WE created the gate entry
if task_token and hasattr(self, '_outbound_gate') and self._outbound_gate is not None:
from archivar.outbound_gate import GateDecision
decision = await self._outbound_gate.try_acquire(_gate_room_id, task_token)
@@ -7071,7 +7096,14 @@ class RocketChatAdapter(BasePlatformAdapter):
await self._post_message_unlocked(_gate_room_id, quick_reply_text)
self._outbound_gate.stats.quick_reply += 1
return SendResult(success=True, message_id="quick_reply")
# Fell through: decision.allow is True — track if WE created the entry
# (gate_clear = we own it; same_room_same_token = someone else owns it)
_gate_acquired = (decision.reason == "gate_clear")
# ── P1a: try/finally für symmetrisches Gate-Release ─────────
# Bei Exception in send_clarify() hängt sonst der Gate-Eintrag.
try:
# ── 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.
@@ -7185,6 +7217,14 @@ class RocketChatAdapter(BasePlatformAdapter):
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,