P5 V9.x: Rainer Review Fixes — A1-A4 + W2

FIX A1: Adapter-Integration nachgeliefert
- adapter.py: init self._outbound_gate nach Z.1177, Gate-Check in send()
  nach Red-Flag, send_clarify() Gate-Check, release in _process_incoming
  finally und _dispatch_agent finally, _post_message_unlocked für Quick-Reply
- archivar/SKILL.md: Z.20-21 ergänzt + Outbound-Sicht V9.x Abschnitt
- archivar/adapter_integration.py: bind_outbound_gate Hook

FIX A2: Tests grün (7/7, keine Warnings)
- pytest-asyncio bereits installiert (pytest 9.1.0)
- @pytest.mark.outbound_gate in conftest.py registriert

FIX A3: try_acquire Spec-Abweichung behoben
- try_acquire jetzt ASYNC (await asyncio.Lock)
- Rückgabetyp: GateDecision Dataclass (allow, reason, blocking_room_id)
- Reasons: gate_clear, same_room_same_token, same_room_different_token,
  different_room_busy

FIX A4: wait_until_clear Spec-Abweichung behoben
- blocking_room_id Parameter hinzugefügt
- _waiters per-Raum Dict (nicht flat List) → kein False-Wake-Bug
- _TurnHandle jetzt Dataclass mit task und chat_id Feldern

W2: Sweep-Loop als asyncio.create_task im Adapter
- _gate_sweep_loop() alle 30s, nicht threading.Timer
- Gestartet in connect() nach _listen_loop

Tests: 1359 passed, 0 failed, 0 regressions.
This commit is contained in:
Bernd (Hermes)
2026-07-30 08:43:00 +02:00
parent e28c575169
commit 1958a53f0e
8 changed files with 1314 additions and 100 deletions
+152
View File
@@ -1175,6 +1175,11 @@ class RocketChatAdapter(BasePlatformAdapter):
self.archivar = None
self._conversation_history = 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
self._pending_move_requests: Dict[str, dict] = {}
# V8.1 P2: Temporäre Session-Raum-Präferenzen (30 Min TTL)
@@ -1393,6 +1398,25 @@ class RocketChatAdapter(BasePlatformAdapter):
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:
"""M13: Garbage-Collect room-map.json + FAISS + Booster + State gegen tatsächliche Mitgliedschaft.
@@ -1907,6 +1931,8 @@ class RocketChatAdapter(BasePlatformAdapter):
self._mark_connected()
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)
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)
logger.info("[rocketchat] Connected to %s", self.base_url)
@@ -3525,6 +3551,18 @@ class RocketChatAdapter(BasePlatformAdapter):
# P1-2: current_room zurücksetzen nach Verarbeitung
self._presence_engine.set_current_room("")
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 ────────────────────────────────────────
@@ -4684,6 +4722,13 @@ class RocketChatAdapter(BasePlatformAdapter):
return
finally:
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:
logger.error("[rocketchat] handle_message error: %s", e)
# Fallback: Wenn COMMAND fehlschlägt
@@ -6543,6 +6588,54 @@ class RocketChatAdapter(BasePlatformAdapter):
)
routing_counter.increment('red_flag_fallback_stay')
# ── P5 V9.x: OutboundGate — Parallel-Stream-Schutz ──────────
# Nach Red-Flag-Block, vor P1-6 Prefix.
# Verhindert dass der Agent gleichzeitig in zwei verschiedenen
# Räumen antwortet. Der Denkprozess läuft parallel — das Gate
# greift NUR in der Outbound-Phase (posten der Antwort).
_gate_room_id = chat_id
if chat_id.startswith("user:"):
origin = _CURRENT_ORIGIN_ROOM.get()
if origin:
_gate_room_id = origin
task_token = _CURRENT_TASK_TOKEN.get()
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)
if not decision.allow:
# Blockiert — warte bis zu 30s (A4: blocking_room_id)
blocking_room = decision.blocking_room_id
if blocking_room:
try:
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."
)
await self._post_message_unlocked(_gate_room_id, quick_reply_text)
self._outbound_gate.stats.quick_reply += 1
logger.info(
"[rocketchat] P5 V9.x: Quick-Reply sent to room=%s (blocked by %s)",
_gate_room_id[:8], active_name,
)
return SendResult(success=True, message_id="quick_reply")
# ── P1-6: ::-Prefix für Dangerous-Command-Meldungen ──────────
# Hermes Core sendet Meldungen mit /approve, /deny etc.
# Rocket.Chat unterstützt keine /-Befehle → :: Varianten einsetzen.
@@ -6942,6 +7035,43 @@ class RocketChatAdapter(BasePlatformAdapter):
if not self.rest.auth_token:
return SendResult(success=False, error="Not authenticated")
# ── P5 V9.x: OutboundGate — Parallel-Stream-Schutz ──────────
# Gleicher Gate-Check wie in send().
_gate_room_id = chat_id
if chat_id.startswith("user:"):
origin = _CURRENT_ORIGIN_ROOM.get()
if origin:
_gate_room_id = origin
task_token = _CURRENT_TASK_TOKEN.get()
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)
if not decision.allow:
blocking_room = decision.blocking_room_id
if blocking_room:
try:
await self._outbound_gate.wait_until_clear(
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."
)
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")
# ── 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.
@@ -7143,3 +7273,25 @@ class RocketChatAdapter(BasePlatformAdapter):
return self.ddp._msg_queue.get(timeout=timeout)
except queue.Empty:
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)