Compare commits
21 Commits
f9e4760f58
...
v8.6.1
| Author | SHA1 | Date | |
|---|---|---|---|
| c0ae37f79a | |||
| c942968328 | |||
| b6a9c9d8c3 | |||
| 42cb259bce | |||
| 9098a760dc | |||
| d964d7d5b5 | |||
| 573335cc8d | |||
| 342a1cddbb | |||
| c0c505e73d | |||
| 48471a8024 | |||
| 6825ba9149 | |||
| 6b16381818 | |||
| 7657cd3665 | |||
| 2019630144 | |||
| 131b11d07d | |||
| e72a5adb57 | |||
| a07ca22ca8 | |||
| 9f33fd3ee8 | |||
| c748c71ea9 | |||
| 37d6c10e45 | |||
| ce4789fe30 |
+117
-3
@@ -1234,7 +1234,8 @@ if $CHECK_ONLY; then
|
||||
fi
|
||||
|
||||
if $UPDATE_ONLY; then
|
||||
# P1-9: Update-Only — Plugin-Code aktualisieren (git pull) + deployen.
|
||||
# V8.6: Update-Only — Plugin-Code aktualisieren (git pull) + deployen
|
||||
# + __pycache__-Cleanup + Service-Restart + Post-Deploy-Verifikation.
|
||||
# Keine Konfigurationsänderungen, keine System-Dependencies, keine Secrets.
|
||||
banner "Update-Only (Plugin-Code aktualisieren)"
|
||||
|
||||
@@ -1256,19 +1257,132 @@ if $UPDATE_ONLY; then
|
||||
PIPX_VENV="$(find_pipx_venv 2>/dev/null)" \
|
||||
|| die "pipx-venv nicht gefunden — vorher Normal-Install ausführen"
|
||||
VENV_PY="$PIPX_VENV/bin/python"
|
||||
|
||||
# Ziel-Pfad ermitteln
|
||||
if [ "$PIPX_VENV" = "$HOME/.hermes/hermes-agent/venv" ]; then
|
||||
_update_dst="$HOME/.hermes/hermes-agent/plugins/platforms/rocketchat"
|
||||
else
|
||||
_update_site_packages="$(find_site_packages "$PIPX_VENV")"
|
||||
[ -n "$_update_site_packages" ] || die "site-packages-Pfad konnte nicht ermittelt werden"
|
||||
_update_dst="$_update_site_packages/plugins/platforms/rocketchat"
|
||||
fi
|
||||
|
||||
# ── Schritt 1: __pycache__ VOR dem Kopieren löschen ──
|
||||
log "Lösche __pycache__ im Ziel VOR Deployment..."
|
||||
if ! $DRY_RUN; then
|
||||
find "$_update_dst" -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
|
||||
find "$_update_dst" -name '*.pyc' -delete 2>/dev/null || true
|
||||
ok "__pycache__ vor Deployment gelöscht"
|
||||
else
|
||||
printf '%s[dry]%s find %s -type d -name __pycache__ -exec rm -rf {} +\n' "$C_YELLOW" "$C_RESET" "$_update_dst"
|
||||
fi
|
||||
|
||||
# ── Schritt 2: Plugin deployen ──
|
||||
deploy_plugin
|
||||
|
||||
# ── Schritt 3: __pycache__ NACH dem Kopieren NOCHMAL löschen ──
|
||||
log "Lösche __pycache__ im Ziel NACH Deployment..."
|
||||
if ! $DRY_RUN; then
|
||||
find "$_update_dst" -type d -name __pycache__ -exec rm -rf {} + 2>/dev/null || true
|
||||
find "$_update_dst" -name '*.pyc' -delete 2>/dev/null || true
|
||||
ok "__pycache__ nach Deployment gelöscht"
|
||||
else
|
||||
printf '%s[dry]%s find %s -type d -name __pycache__ -exec rm -rf {} +\n' "$C_YELLOW" "$C_RESET" "$_update_dst"
|
||||
fi
|
||||
|
||||
# ── Schritt 4: Gateway-Dienst neu starten ──
|
||||
if ! $DRY_RUN; then
|
||||
systemctl --user daemon-reload 2>/dev/null || true
|
||||
rm -f "$HOME/.hermes/gateway_state.json" "$HOME/.hermes/gateway.lock" 2>/dev/null || true
|
||||
systemctl --user reset-failed hermes-gateway 2>/dev/null || true
|
||||
# P1-9(c): --no-restart überspringt den Gateway-Neustart
|
||||
|
||||
if $NO_RESTART; then
|
||||
ok "Gateway-Neustart übersprungen (--no-restart)"
|
||||
else
|
||||
log "Starte Gateway neu..."
|
||||
systemctl --user restart hermes-gateway 2>/dev/null || true
|
||||
ok "Gateway neugestartet"
|
||||
|
||||
# Warte bis active (max 30s)
|
||||
_update_wait=0
|
||||
while ! systemctl --user is-active hermes-gateway >/dev/null 2>&1 && [ $_update_wait -lt 30 ]; do
|
||||
sleep 1
|
||||
_update_wait=$((_update_wait + 1))
|
||||
done
|
||||
if systemctl --user is-active hermes-gateway >/dev/null 2>&1; then
|
||||
ok "Gateway neugestartet und aktiv (nach ${_update_wait}s)"
|
||||
else
|
||||
err "Gateway nach 30s nicht aktiv — prüfe: journalctl --user -u hermes-gateway -n 20"
|
||||
fi
|
||||
fi
|
||||
else
|
||||
printf '%s[dry]%s systemctl --user restart hermes-gateway\n' "$C_YELLOW" "$C_RESET"
|
||||
fi
|
||||
|
||||
# ── Schritt 5: Post-Deployment-Verifikation ──
|
||||
if ! $DRY_RUN && ! $NO_RESTART; then
|
||||
banner "Post-Deployment-Verifikation"
|
||||
_update_verify_fail=0
|
||||
|
||||
if command -v journalctl >/dev/null 2>&1; then
|
||||
# Präziser Zeitstempel für journalctl --since (statt relativem Zeitfenster)
|
||||
_verify_since="$(date '+%Y-%m-%d %H:%M:%S')"
|
||||
# Warte 12s: Gateway braucht ~5-7s für PresenceEngine, ~8-10s für Archivar/Connected
|
||||
sleep 12
|
||||
|
||||
# Retry-Schleife: bis zu 3 Versuche im Abstand von 5s
|
||||
for _check_attempt in 1 2 3; do
|
||||
_all_ok=true
|
||||
|
||||
# Prüfe auf PresenceEngine/presence
|
||||
_update_presence_hits="$(journalctl --user -u hermes-gateway --since "$_verify_since" --no-pager 2>/dev/null | grep -c -i 'PresenceEngine\|presence' || true)"
|
||||
if [ "${_update_presence_hits:-0}" -gt 0 ]; then
|
||||
ok "PresenceEngine im Log gefunden ($_update_presence_hits Treffer)"
|
||||
else
|
||||
err "FAIL: PresenceEngine NICHT im Gateway-Log (Versuch $_check_attempt/3) — Plugin-Code wurde möglicherweise nicht geladen (stale __pycache__?)"
|
||||
_all_ok=false
|
||||
fi
|
||||
|
||||
# Prüfe auf 'Archivar initialisiert'
|
||||
_update_archivar_hits="$(journalctl --user -u hermes-gateway --since "$_verify_since" --no-pager 2>/dev/null | grep -c 'Archivar initialisiert' || true)"
|
||||
if [ "${_update_archivar_hits:-0}" -gt 0 ]; then
|
||||
ok "'Archivar initialisiert' im Log gefunden ($_update_archivar_hits Treffer)"
|
||||
else
|
||||
err "FAIL: 'Archivar initialisiert' NICHT im Gateway-Log (Versuch $_check_attempt/3)"
|
||||
_all_ok=false
|
||||
fi
|
||||
|
||||
# Prüfe auf 'Connected to'
|
||||
_update_connected_hits="$(journalctl --user -u hermes-gateway --since "$_verify_since" --no-pager 2>/dev/null | grep -c 'Connected to' || true)"
|
||||
if [ "${_update_connected_hits:-0}" -gt 0 ]; then
|
||||
ok "'Connected to' im Log gefunden ($_update_connected_hits Treffer)"
|
||||
else
|
||||
err "FAIL: 'Connected to' NICHT im Gateway-Log (Versuch $_check_attempt/3) — Gateway hat keine Verbindung"
|
||||
_all_ok=false
|
||||
fi
|
||||
|
||||
if $_all_ok; then
|
||||
ok "Post-Deployment-Verifikation: ALLE CHECKS BESTANDEN (Versuch $_check_attempt/3)"
|
||||
break
|
||||
fi
|
||||
|
||||
if [ "$_check_attempt" -lt 3 ]; then
|
||||
warn "Warte 5s vor nächstem Verifikations-Versuch..."
|
||||
sleep 5
|
||||
else
|
||||
_update_verify_fail=1
|
||||
fi
|
||||
done
|
||||
else
|
||||
warn "journalctl nicht verfügbar — Post-Deployment-Verifikation übersprungen"
|
||||
fi
|
||||
|
||||
if [ $_update_verify_fail -ne 0 ]; then
|
||||
die "Post-Deployment-Verifikation FEHLGESCHLAGEN — siehe Fehler oben. Prüfe: journalctl --user -u hermes-gateway -n 50"
|
||||
fi
|
||||
elif $DRY_RUN; then
|
||||
printf '%s[dry]%s Post-Deployment-Verifikation (journalctl Checks)\n' "$C_YELLOW" "$C_RESET"
|
||||
fi
|
||||
|
||||
exit 0
|
||||
fi
|
||||
|
||||
|
||||
+385
-22
@@ -9,6 +9,7 @@ Zero external dependencies — stdlib only.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import concurrent.futures
|
||||
import contextvars
|
||||
import json
|
||||
import logging
|
||||
@@ -50,6 +51,9 @@ if _MULTIROOM():
|
||||
from archivar.routing_counter import routing_counter
|
||||
from archivar.routing_telemetry import routing_telemetry
|
||||
|
||||
# P0: Reply-Quote-Stripping — verhindert Fehl-Routing durch zitierte Parent-Nachrichten
|
||||
from archivar.reply_quote_stripper import strip_reply_quote_for_routing
|
||||
|
||||
# ── Access __init__ symbols (plugin loaded as flat module, no relative imports) ──
|
||||
import sys as _sys
|
||||
_init_module = _sys.modules.get('rocketchat')
|
||||
@@ -267,6 +271,24 @@ class RocketChatREST:
|
||||
return bool(r and r.get("success"))
|
||||
|
||||
|
||||
class DDPTimeout(Exception):
|
||||
"""Raised when a DDP method call times out waiting for a result message."""
|
||||
pass
|
||||
|
||||
|
||||
class DDPServerError(Exception):
|
||||
"""Raised when the DDP server returns an error for a method call."""
|
||||
|
||||
def __init__(self, error_data: dict):
|
||||
self.error_data = error_data
|
||||
super().__init__(f"DDP server error: {error_data}")
|
||||
|
||||
|
||||
class DDPNotConnected(Exception):
|
||||
"""Raised when a DDP method is called but the client is not connected."""
|
||||
pass
|
||||
|
||||
|
||||
class DDPClient:
|
||||
PING_INTERVAL = 8.0
|
||||
|
||||
@@ -287,6 +309,11 @@ class DDPClient:
|
||||
self._session: Optional[str] = None
|
||||
self._reconnect_attempt = 0
|
||||
self._last_rx_time = 0.0
|
||||
# P1-2 O-2: Future-Store für await-Semantik
|
||||
self._pending_results: Dict[str, concurrent.futures.Future] = {}
|
||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||
self._result_lock = threading.Lock()
|
||||
self._msg_seq: int = 0
|
||||
|
||||
def _create_socket(self) -> socket.socket:
|
||||
ctx = ssl.create_default_context()
|
||||
@@ -344,6 +371,7 @@ class DDPClient:
|
||||
import select
|
||||
self.sock.settimeout(1.0)
|
||||
last_ping = time.time()
|
||||
last_sweep = time.time()
|
||||
while self._running:
|
||||
try:
|
||||
if time.time() - last_ping >= self.PING_INTERVAL:
|
||||
@@ -352,6 +380,10 @@ class DDPClient:
|
||||
last_ping = time.time()
|
||||
except Exception:
|
||||
break
|
||||
# P1-2 O-2: Periodic sweep of stale pending results (every 5s)
|
||||
if time.time() - last_sweep >= 5.0:
|
||||
self._sweep_pending_results()
|
||||
last_sweep = time.time()
|
||||
readable, _, _ = select.select([self.sock], [], [], 1.0)
|
||||
if not readable:
|
||||
continue
|
||||
@@ -393,6 +425,15 @@ class DDPClient:
|
||||
self._on_connected()
|
||||
elif msg_type == "ping":
|
||||
self._send_json({"msg": "pong"})
|
||||
# P1-2 O-2: Handle DDP result messages (resolve pending Futures)
|
||||
elif msg_type == "result":
|
||||
self._handle_result_message(data)
|
||||
# P1-2 O-2: Handle DDP updated messages (log only, result follows)
|
||||
elif msg_type == "updated":
|
||||
logger.debug(
|
||||
"DDP: updated message received (id=%s)",
|
||||
data.get("id", "?"),
|
||||
)
|
||||
elif msg_type in ("changed", "added") and data.get("collection") == "stream-room-messages":
|
||||
fields = data.get("fields", {})
|
||||
args = fields.get("args", [])
|
||||
@@ -538,13 +579,171 @@ class DDPClient:
|
||||
room_id[:12], event["name"], event["type"])
|
||||
self._on_room_event(event)
|
||||
|
||||
def _handle_result_message(self, data: dict) -> None:
|
||||
"""P1-2 O-2: Resolve pending Futures when a DDP result message arrives.
|
||||
|
||||
Called from the reader thread (PURE SYNC — no asyncio calls here).
|
||||
Looks up the msg_id in _pending_results and resolves the Future
|
||||
with the result or error.
|
||||
|
||||
Args:
|
||||
data: The parsed DDP JSON message with msg='result'.
|
||||
"""
|
||||
msg_id = data.get("id", "")
|
||||
if not msg_id:
|
||||
return
|
||||
|
||||
with self._result_lock:
|
||||
future = self._pending_results.pop(msg_id, None)
|
||||
|
||||
if future is None:
|
||||
# No pending future for this msg_id — likely a result for
|
||||
# a fire-and-forget call (legacy set_status) or already timed out
|
||||
return
|
||||
|
||||
if future.done():
|
||||
# Already resolved (e.g., by timeout sweep)
|
||||
return
|
||||
|
||||
if "error" in data:
|
||||
future.set_exception(DDPServerError(data["error"]))
|
||||
else:
|
||||
future.set_result(data.get("result", True))
|
||||
|
||||
def set_status(self, status: str) -> bool:
|
||||
"""Set the user presence status via DDP (fire-and-forget, no await).
|
||||
|
||||
.. deprecated::
|
||||
Use :meth:`set_status_async` for await-semantics with timeout
|
||||
and error handling. This method remains for legacy callers
|
||||
(on_connected callback, idle timer) that don't need the result.
|
||||
|
||||
Returns:
|
||||
True if the frame was sent, False if not connected.
|
||||
"""
|
||||
if not self.connected:
|
||||
return False
|
||||
method = f"UserPresence:{status}"
|
||||
self._send_json({"msg": "method", "method": method, "params": [], "id": f"st{int(time.time()*1000)}"})
|
||||
method = "UserPresence:setDefaultStatus"
|
||||
self._send_json({"msg": "method", "method": method, "params": [status], "id": f"st{int(time.time()*1000)}"})
|
||||
return True
|
||||
|
||||
def bind_loop(self, loop: asyncio.AbstractEventLoop) -> None:
|
||||
"""Bind the asyncio event loop for async operations.
|
||||
|
||||
Called by the adapter after the event loop is running.
|
||||
The loop reference is used by set_status_async to bridge
|
||||
between the DDP reader thread and the asyncio world.
|
||||
|
||||
Args:
|
||||
loop: The running asyncio event loop.
|
||||
"""
|
||||
self._loop = loop
|
||||
|
||||
async def set_status_async(self, status: str, timeout: float = 2.0) -> bool:
|
||||
"""Set the user presence status via DDP with await-semantics.
|
||||
|
||||
Sends a DDP method call and waits for the corresponding result
|
||||
message from the server. Uses a Future registered in
|
||||
_pending_results that the reader thread resolves when the
|
||||
result message arrives.
|
||||
|
||||
Args:
|
||||
status: Rocket.Chat status ('online', 'away', 'busy').
|
||||
timeout: Maximum seconds to wait for the result (default 2.0).
|
||||
|
||||
Returns:
|
||||
True if the server confirmed the status change.
|
||||
|
||||
Raises:
|
||||
DDPNotConnected: If the DDP client is not connected.
|
||||
DDPTimeout: If no result message arrives within timeout.
|
||||
DDPServerError: If the server returns an error for the call.
|
||||
"""
|
||||
if not self.connected:
|
||||
raise DDPNotConnected("DDP client is not connected")
|
||||
|
||||
# Generate unique msg_id with sequence counter to prevent collisions
|
||||
with self._result_lock:
|
||||
self._msg_seq += 1
|
||||
msg_id = f"st{int(time.time() * 1000)}_{self._msg_seq}"
|
||||
|
||||
# Create Future and register it
|
||||
future: concurrent.futures.Future = concurrent.futures.Future()
|
||||
with self._result_lock:
|
||||
self._pending_results[msg_id] = future
|
||||
|
||||
try:
|
||||
# Send the DDP method call
|
||||
method = "UserPresence:setDefaultStatus"
|
||||
self._send_json({
|
||||
"msg": "method",
|
||||
"method": method,
|
||||
"params": [status],
|
||||
"id": msg_id,
|
||||
})
|
||||
|
||||
# Await the future — bridge concurrent.Future to asyncio with timeout
|
||||
result = await asyncio.wait_for(
|
||||
asyncio.wrap_future(future),
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
# If we get here, the reader thread resolved the future
|
||||
if result is False:
|
||||
raise DDPServerError({"error": "server returned false"})
|
||||
return True
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
# Clean up the pending future
|
||||
with self._result_lock:
|
||||
self._pending_results.pop(msg_id, None)
|
||||
raise DDPTimeout(
|
||||
f"setDefaultStatus('{status}') timed out after {timeout}s"
|
||||
)
|
||||
except (DDPTimeout, DDPServerError, DDPNotConnected):
|
||||
# Re-raise our own exceptions without wrapping
|
||||
with self._result_lock:
|
||||
self._pending_results.pop(msg_id, None)
|
||||
raise
|
||||
except Exception:
|
||||
# Clean up on any other exception
|
||||
with self._result_lock:
|
||||
self._pending_results.pop(msg_id, None)
|
||||
raise
|
||||
|
||||
def _sweep_pending_results(self) -> None:
|
||||
"""Sweep through _pending_results and cancel Futures older than 2s.
|
||||
|
||||
Called periodically from the reader loop to prevent memory leaks
|
||||
from method calls whose result messages never arrive.
|
||||
"""
|
||||
now = time.time()
|
||||
stale_ids = []
|
||||
with self._result_lock:
|
||||
for msg_id, future in list(self._pending_results.items()):
|
||||
# msg_id format: st<TIMESTAMP_MS>_<SEQ>
|
||||
# Extract timestamp from msg_id
|
||||
try:
|
||||
ts_part = msg_id[2:].split("_")[0] # strip 'st' prefix
|
||||
ts_ms = int(ts_part)
|
||||
ts_s = ts_ms / 1000.0
|
||||
if now - ts_s > 2.0:
|
||||
stale_ids.append(msg_id)
|
||||
except (ValueError, IndexError):
|
||||
# Malformed msg_id — clean it up
|
||||
stale_ids.append(msg_id)
|
||||
|
||||
for msg_id in stale_ids:
|
||||
future = self._pending_results.pop(msg_id, None)
|
||||
if future is not None and not future.done():
|
||||
future.cancel()
|
||||
|
||||
if stale_ids:
|
||||
logger.debug(
|
||||
"DDP: Swept %d stale pending results (age > 2s)",
|
||||
len(stale_ids),
|
||||
)
|
||||
|
||||
def disconnect(self):
|
||||
self._running = False
|
||||
if self.sock:
|
||||
@@ -800,16 +999,36 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._register_inline_commands()
|
||||
|
||||
# V8.6: PresenceEngine — Aktivitäts-Indikator
|
||||
try:
|
||||
from archivar.presence_engine import PresenceEngine
|
||||
_presence_enabled = os.getenv("ROCKETCHAT_PRESENCE_ENABLED", "true").strip().lower() not in ("false", "0", "no", "off")
|
||||
_coalesce_ms = int(os.getenv("ROCKETCHAT_PRESENCE_COALESCE_MS", "2000"))
|
||||
_pulse_interval = int(os.getenv("ROCKETCHAT_PRESENCE_PULSE_INTERVAL", "10"))
|
||||
_pulse_interval = float(os.getenv("ROCKETCHAT_PRESENCE_PULSE_INTERVAL", "1.5"))
|
||||
self._presence_engine = PresenceEngine(
|
||||
rest=self.rest,
|
||||
enabled=_presence_enabled,
|
||||
coalesce_ms=_coalesce_ms,
|
||||
pulse_interval=_pulse_interval,
|
||||
)
|
||||
# P0-1: PulseController mit REST und DDP verdrahten
|
||||
self._presence_engine._pulse_controller.bind_rest(self.rest)
|
||||
if self.ddp:
|
||||
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||||
# P2-2: PresenceEngine an ArchivarMessageHandler weiterreichen
|
||||
if self.archivar is not None:
|
||||
self.archivar.set_presence_engine(self._presence_engine)
|
||||
logger.info(
|
||||
"[rocketchat] V8.6: PresenceEngine initialisiert (enabled=%s, coalesce_ms=%s, pulse_interval=%.1fs)",
|
||||
_presence_enabled,
|
||||
_coalesce_ms,
|
||||
_pulse_interval,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"[rocketchat] V8.6: PresenceEngine-Initialisierung FEHLGESCHLAGEN: %s",
|
||||
e,
|
||||
)
|
||||
self._presence_engine = None # Graceful degradation -> alter Idle-Timer greift
|
||||
|
||||
def _build_room_map_summary(self) -> str:
|
||||
"""Baut eine menschenlesbare Raum-Map-Übersicht für den System-Prompt.
|
||||
@@ -844,6 +1063,22 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
lines.append(f" Keywords Kontext: {kwctx}")
|
||||
return "\n".join(lines)
|
||||
|
||||
def _on_ddp_connected(self) -> None:
|
||||
"""Callback when DDP connection is established.
|
||||
|
||||
Sets initial online status and binds DDP to PulseController
|
||||
if PresenceEngine is active (EC-1: on_connected_cb race).
|
||||
"""
|
||||
if self.ddp:
|
||||
self.ddp.set_status("online")
|
||||
# V8.6: PulseController DDP-Bindung nach Connect (EC-1)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||
try:
|
||||
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||||
logger.debug("[rocketchat] V8.6: PulseController DDP gebunden (on_connected_cb)")
|
||||
except Exception as e:
|
||||
logger.debug("[rocketchat] V8.6: PulseController bind_ddp failed: %s", e)
|
||||
|
||||
def _on_ddp_room_event(self, event: dict) -> None:
|
||||
"""A1b: Callback für DDP rooms-changed Events.
|
||||
|
||||
@@ -1202,7 +1437,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
||||
self.ddp = DDPClient(
|
||||
host=host,
|
||||
on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None,
|
||||
on_connected_cb=self._on_ddp_connected,
|
||||
on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events
|
||||
)
|
||||
if not self.ddp.connect_and_login(self._auth_token):
|
||||
@@ -1211,6 +1446,24 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self._rooms = self.rest.get_rooms()
|
||||
logger.info("[rocketchat] REST get_rooms returned %d rooms", len(self._rooms))
|
||||
|
||||
# P1-2 O-2: Bind asyncio loop to DDPClient and PulseController
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
self.ddp.bind_loop(loop)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||
self._presence_engine._pulse_controller.bind_loop(loop)
|
||||
logger.info(
|
||||
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: yes "
|
||||
"(loop=%s)",
|
||||
id(loop),
|
||||
)
|
||||
except RuntimeError:
|
||||
# No running event loop (e.g., in tests) — graceful degradation
|
||||
logger.info(
|
||||
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: no "
|
||||
"(no running event loop)"
|
||||
)
|
||||
|
||||
# A1b: Subscribe to stream-notify-room for rooms-changed events
|
||||
if self.ddp.connected:
|
||||
room_events_sub = self.ddp.subscribe_room_events()
|
||||
@@ -1435,13 +1688,30 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
host = self.base_url.replace("https://", "").replace("http://", "").split("/")[0]
|
||||
self.ddp = DDPClient(
|
||||
host=host,
|
||||
on_connected_cb=lambda: self.ddp.set_status("online") if self.ddp else None,
|
||||
on_connected_cb=self._on_ddp_connected,
|
||||
on_room_event_cb=self._on_ddp_room_event, # A1b: DDP room events (P0-3)
|
||||
)
|
||||
if not self.ddp.connect_and_login(self._auth_token):
|
||||
logger.error("[rocketchat] _reconnect_ddp: DDP connect/login failed")
|
||||
return False
|
||||
|
||||
# P1-2 O-2: Re-bind asyncio loop to new DDPClient and PulseController
|
||||
try:
|
||||
loop = asyncio.get_running_loop()
|
||||
self.ddp.bind_loop(loop)
|
||||
if hasattr(self, '_presence_engine') and self._presence_engine is not None:
|
||||
self._presence_engine._pulse_controller.bind_loop(loop)
|
||||
logger.info(
|
||||
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: yes "
|
||||
"(reconnect, loop=%s)",
|
||||
id(loop),
|
||||
)
|
||||
except RuntimeError:
|
||||
logger.info(
|
||||
"[rocketchat] P1-2 O-2: PresenceEngine async-bound: no "
|
||||
"(reconnect, no running event loop)"
|
||||
)
|
||||
|
||||
# A1b: Re-subscribe to stream-notify-room for rooms-changed events (P0-3)
|
||||
if self.ddp.connected:
|
||||
room_events_sub = self.ddp.subscribe_room_events()
|
||||
@@ -1588,6 +1858,27 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
text = file_info_text
|
||||
msg_obj["msg"] = text
|
||||
|
||||
# ── P0+P1: Reply-Quote-Stripping ──────────────────────────────────
|
||||
# Verhindert Fehl-Routing durch zitierte Parent-Nachrichten.
|
||||
# Zweistufig defensiv:
|
||||
# 1. Attachments-basiert (Rocket.Chat Reply-Attachments)
|
||||
# 2. Text-basiert (Markdown-Blockquotes, [quote]-Blöcke)
|
||||
# routing_text (ohne Quote) → Archivar/Keyword-Matcher/classify_and_route
|
||||
# display_text (mit Quote) → Agent-Dispatch + Conversation-History
|
||||
routing_text, display_text, quote_stripped = strip_reply_quote_for_routing(
|
||||
text, attachments
|
||||
)
|
||||
if quote_stripped:
|
||||
routing_counter.increment('reply_quote_stripped')
|
||||
logger.debug(
|
||||
"[rocketchat] P0: Reply-Quote gestrippt — "
|
||||
"routing_text=%s, display_text=%s",
|
||||
routing_text[:80], display_text[:80],
|
||||
)
|
||||
# text bleibt display_text für Agent/History;
|
||||
# routing_text wird für Archivar-Klassifikation verwendet.
|
||||
# ── Ende P0+P1 ────────────────────────────────────────────────────
|
||||
|
||||
# Skip own messages (case-insensitive comparison)
|
||||
filter_match = (username == (self.user or "").lower())
|
||||
logger.debug("Filter check: username=%s, self.user=%s, match=%s", username, self.user, filter_match)
|
||||
@@ -1627,7 +1918,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# ── R5: Inline-Command-Erkennung (VOR Onboarding + Hermes-Dispatch) ──
|
||||
# ::-Befehle und natürliche Hilfeseiten-Anfragen müssen VOR dem
|
||||
# generischen Hermes-Agent-Onboarding erkannt werden.
|
||||
inline_handled = await self._handle_inline_command(text, room_id, room_name, username)
|
||||
inline_handled = await self._handle_inline_command(routing_text, room_id, room_name, username)
|
||||
if inline_handled:
|
||||
logger.debug("[rocketchat] R5: Inline-Command verarbeitet — skipping agent dispatch")
|
||||
routing_counter.increment('inline_command_handled')
|
||||
@@ -1636,13 +1927,15 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# ── Ende R5 Inline-Command-Erkennung ────────────────────────────────
|
||||
|
||||
# ── B5v6.5: Conversation History — User-Nachricht aufzeichnen ──
|
||||
# P1: display_text (mit Quote) für Agent/History, damit kein Kontext verloren geht
|
||||
if _MULTIROOM() and self._conversation_history is not None:
|
||||
await self._conversation_history.add(room_id, "user", text)
|
||||
await self._conversation_history.add(room_id, "user", display_text)
|
||||
|
||||
# V8.1 P4: MultiRoomContext-Ring — Thema aus Nachricht extrahieren
|
||||
if _MULTIROOM() and self._multiroom_context is not None:
|
||||
# Extrahiere ein kurzes Topic aus der Nachricht (erste 80 Zeichen)
|
||||
topic = text[:80].replace("\n", " ").strip()
|
||||
# P1: routing_text für Topic-Extraktion (ohne Quote)
|
||||
topic = routing_text[:80].replace("\n", " ").strip()
|
||||
if topic:
|
||||
await self._multiroom_context.add(room_id, room_name, topic)
|
||||
|
||||
@@ -1968,7 +2261,16 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# V8.2.1 A2: Nachklärung bei stay_once — Strategie-Buttons senden
|
||||
if _MULTIROOM() and self.archivar is not None:
|
||||
if self.archivar._should_trigger_nachklaerung("stay_once"):
|
||||
nachklaerung_buttons = self.archivar._get_nachklaerung_buttons()
|
||||
# Keywords des Zielraums als lesbaren Text einbauen
|
||||
target_room_id = move_req.get("target_room", "")
|
||||
target_keywords = []
|
||||
if target_room_id and self.archivar._room_map is not None:
|
||||
target_entry = self.archivar._room_map.rooms.get(target_room_id)
|
||||
if target_entry:
|
||||
target_keywords = target_entry.keywords_100[:5]
|
||||
nachklaerung_buttons = self.archivar._get_nachklaerung_buttons(
|
||||
keywords=target_keywords if target_keywords else None
|
||||
)
|
||||
await self._send_archivar_buttons(
|
||||
room_id,
|
||||
nachklaerung_buttons["text"],
|
||||
@@ -2131,7 +2433,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
del self._recent_auto_routes[room_id]
|
||||
# Dispatch im Ursprungsraum
|
||||
await self._dispatch_agent(
|
||||
text=text,
|
||||
text=display_text,
|
||||
room_id=room_id,
|
||||
room_name=room_name,
|
||||
room_type=room_type,
|
||||
@@ -2231,7 +2533,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
target_room_name_disp = target_room_info.get("name", target_room_display)
|
||||
target_room_type = target_room_info.get("type", "c")
|
||||
await self._dispatch_agent(
|
||||
text=text,
|
||||
text=display_text,
|
||||
room_id=target_room_id,
|
||||
room_name=target_room_name_disp,
|
||||
room_type=target_room_type,
|
||||
@@ -2249,7 +2551,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# Nur die Nachricht selbst wird — nach User-Entscheidung — kopiert.
|
||||
category = ""
|
||||
decision = None
|
||||
is_auftrag = _is_auftrag(text)
|
||||
is_auftrag = _is_auftrag(routing_text)
|
||||
|
||||
logger.debug("[rocketchat] ARCHIVAR-DEBUG: Entering Archivar block — room_type=%s, is_auftrag=%s, _MULTIROOM=%s, archivar=%s", room_type, is_auftrag, _MULTIROOM(), self.archivar is not None)
|
||||
|
||||
@@ -2363,7 +2665,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
)
|
||||
routing_telemetry.flush()
|
||||
# Kopiere Nachricht in den Zielraum
|
||||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{text}"
|
||||
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}"
|
||||
await self._post_message_with_retry(target_room_id, target_txt)
|
||||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||||
@@ -2371,7 +2674,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.info(
|
||||
"[rocketchat] V8.3-5: Topic-Scoped Sticky active — "
|
||||
"auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
|
||||
text[:80], target_name, sticky_topic,
|
||||
display_text[:80], target_name, sticky_topic,
|
||||
pref["expires_at"] - time.time(),
|
||||
)
|
||||
# Dispatch direkt — kein Archivar
|
||||
@@ -2379,7 +2682,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
target_room_name = target_room_info.get("name", target_name)
|
||||
target_room_type = target_room_info.get("type", "c")
|
||||
await self._dispatch_agent(
|
||||
text=text,
|
||||
text=display_text,
|
||||
room_id=target_room_id,
|
||||
room_name=target_room_name,
|
||||
room_type=target_room_type,
|
||||
@@ -2407,7 +2710,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
duration_ms=0.0,
|
||||
)
|
||||
routing_telemetry.flush()
|
||||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{text}"
|
||||
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||||
target_txt = f"*(Auftrag von @{username}, Topic-Sticky)*\n{display_text}"
|
||||
await self._post_message_with_retry(target_room_id, target_txt)
|
||||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||||
_THEMATIC_TARGET_ROOM.set(target_room_id)
|
||||
@@ -2415,7 +2719,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.info(
|
||||
"[rocketchat] V8.3-5: Topic-Scoped Sticky active — "
|
||||
"auto-routing '%s' → %s, topic='%s' (%.0fs remaining)",
|
||||
text[:80], target_name, sticky_topic,
|
||||
display_text[:80], target_name, sticky_topic,
|
||||
pref["expires_at"] - time.time(),
|
||||
)
|
||||
# Dispatch direkt — kein Archivar
|
||||
@@ -2423,7 +2727,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
target_room_name = target_room_info.get("name", target_name)
|
||||
target_room_type = target_room_info.get("type", "c")
|
||||
await self._dispatch_agent(
|
||||
text=text,
|
||||
text=display_text,
|
||||
room_id=target_room_id,
|
||||
room_name=target_room_name,
|
||||
room_type=target_room_type,
|
||||
@@ -2453,7 +2757,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
# P0-FIX: is_dm=True bei DMs — der Router braucht das für den DM-Guard.
|
||||
# room_type wird in L1579 aus self._room_info gelesen.
|
||||
_is_dm = (room_type == "d")
|
||||
decision = await self.archivar.classify_and_route(text, origin_room_id=room_id, is_dm=_is_dm)
|
||||
# P0: routing_text (ohne Quote) für Klassifikation verwenden
|
||||
decision = await self.archivar.classify_and_route(routing_text, origin_room_id=room_id, is_dm=_is_dm)
|
||||
# V8.3.3: Telemetrie nach jeder Routing-Entscheidung flushen
|
||||
routing_telemetry.flush()
|
||||
if decision and decision.category:
|
||||
@@ -2483,7 +2788,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
and hasattr(decision, 'target_room')
|
||||
and decision.target_room):
|
||||
self._pending_move_requests[room_id] = {
|
||||
'text': text,
|
||||
# P1: display_text (mit Quote) für Move-Request speichern
|
||||
'text': display_text,
|
||||
'origin_room': room_id,
|
||||
'target_room': decision.target_room,
|
||||
'target_name': getattr(
|
||||
@@ -2575,7 +2881,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
room_id[:8],
|
||||
)
|
||||
# Kopiere Nachricht in den Zielraum
|
||||
target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{text}"
|
||||
# P1: display_text (mit Quote) für Zielraum-Kopie
|
||||
target_txt = f"*(Auftrag von @{username}, automatisch geroutet)*\n{display_text}"
|
||||
target_message_id = await self._post_message_with_retry(target_room_id, target_txt)
|
||||
# Setze _CURRENT_ORIGIN_ROOM auf Zielraum → Agent antwortet dort
|
||||
_CURRENT_ORIGIN_ROOM.set(target_room_id)
|
||||
@@ -2585,7 +2892,7 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
logger.info(
|
||||
"[rocketchat] V8.1 P1: Auto-Route '%s' → %s — "
|
||||
"Agent dispatched in target room",
|
||||
text[:80], target_name,
|
||||
display_text[:80], target_name,
|
||||
)
|
||||
# V8.1.1 R2: Ring-GC bei Auto-Route — stale Topics aus Ursprungsraum entfernen
|
||||
if _MULTIROOM() and self._multiroom_context is not None:
|
||||
@@ -3097,9 +3404,20 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
async def _cmd_hilfe(self, room_id: str, args: str) -> str:
|
||||
"""::hilfe — Zeigt die Hilfeseite mit allen Befehlen."""
|
||||
from archivar.inline_commands import build_help_text
|
||||
|
||||
# P1-4: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||||
presence_enabled = None
|
||||
current_status = "online"
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
presence_enabled = self._presence_engine.is_enabled()
|
||||
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
|
||||
|
||||
return build_help_text(
|
||||
self._inline_commands,
|
||||
room_map_summary=self._room_map_summary,
|
||||
presence_enabled=presence_enabled,
|
||||
current_status=current_status,
|
||||
)
|
||||
|
||||
async def _cmd_status(self, room_id: str, args: str) -> str:
|
||||
@@ -3119,12 +3437,25 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
butler_mode = getattr(room_map, 'butler_mode', 'unknown')
|
||||
onboarding_active = self.archivar._stats.get("onboarding_active", False)
|
||||
|
||||
# P1-4: PresenceEngine-Werte lesen (mit _has_presence-Guard)
|
||||
presence_enabled = None
|
||||
current_status = "online"
|
||||
pulse_active = False
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
presence_enabled = self._presence_engine.is_enabled()
|
||||
current_status = getattr(self._presence_engine, '_last_sent_status', 'online') or 'online'
|
||||
pulse_active = self._presence_engine._pulse_controller.is_running()
|
||||
|
||||
return build_status_text(
|
||||
room_count=room_count,
|
||||
archivar_active=archivar_active,
|
||||
butler_mode=butler_mode,
|
||||
onboarding_active=onboarding_active,
|
||||
room_map_summary=self._room_map_summary,
|
||||
presence_enabled=presence_enabled,
|
||||
current_status=current_status,
|
||||
pulse_active=pulse_active,
|
||||
)
|
||||
|
||||
async def _cmd_reset(self, room_id: str, args: str) -> str:
|
||||
@@ -3484,11 +3815,19 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
|
||||
if subcmd in ("on", "an", "ein", "enable", "start"):
|
||||
self._presence_engine.enable()
|
||||
# P0-3: ::setstatus on → PulseController aktivieren
|
||||
if hasattr(self._presence_engine, '_pulse_controller'):
|
||||
self._presence_engine._pulse_controller.bind_rest(self.rest)
|
||||
if self.ddp:
|
||||
self._presence_engine._pulse_controller.bind_ddp(self.ddp)
|
||||
logger.info("[rocketchat] V8.6: ::setstatus on — PresenceEngine aktiviert")
|
||||
return "🟢 **Aktivitäts-Indikator: AN**\n\nDer Bot zeigt jetzt seinen Status automatisch an (online/busy/away)."
|
||||
|
||||
elif subcmd in ("off", "aus", "disable", "stop"):
|
||||
self._presence_engine.disable()
|
||||
# P0-3: ::setstatus off → PulseController stoppen
|
||||
if hasattr(self._presence_engine, '_pulse_controller'):
|
||||
self._presence_engine._pulse_controller.stop()
|
||||
logger.info("[rocketchat] V8.6: ::setstatus off — PresenceEngine deaktiviert")
|
||||
return "🔴 **Aktivitäts-Indikator: AUS**\n\nDer Bot-Status bleibt auf 'online'. Keine automatischen Status-Wechsel."
|
||||
|
||||
@@ -4033,6 +4372,20 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
"actions": buttons,
|
||||
}]
|
||||
|
||||
# Split buttons into groups of max 3 per attachment (UX: mobile readability)
|
||||
MAX_BUTTONS_PER_ROW = 3
|
||||
if len(buttons) > MAX_BUTTONS_PER_ROW:
|
||||
attachments = []
|
||||
for i in range(0, len(buttons), MAX_BUTTONS_PER_ROW):
|
||||
chunk = buttons[i:i + MAX_BUTTONS_PER_ROW]
|
||||
attachments.append({
|
||||
"color": "#1d74f5",
|
||||
"actions": chunk,
|
||||
})
|
||||
# First attachment gets the title
|
||||
if attachments:
|
||||
attachments[0]["title"] = text
|
||||
|
||||
success = await self._post_message_with_retry(room_id, text, attachments=attachments)
|
||||
if success is not None:
|
||||
# Mark room so the response stays here (no Archivar routing)
|
||||
@@ -4224,6 +4577,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
if _MULTIROOM() and self.archivar is not None:
|
||||
self.archivar._stats["onboarding_active"] = True
|
||||
# ── V8.6: PresenceEngine — Onboarding start → away ──
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
self._presence_engine.set_onboarding_active(True)
|
||||
self._presence_engine.update_presence()
|
||||
|
||||
@@ -5769,6 +6124,8 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
self.archivar._state.clear_onboarding_state()
|
||||
self._onboarding_state = {}
|
||||
# ── V8.6: PresenceEngine — Onboarding end → online ──
|
||||
_has_presence = hasattr(self, '_presence_engine') and self._presence_engine is not None
|
||||
if _has_presence:
|
||||
self._presence_engine.set_onboarding_active(False)
|
||||
self._presence_engine.update_presence()
|
||||
# F8: State Machine — AWAITING_TEST → ACTIVE
|
||||
@@ -5907,6 +6264,12 @@ class RocketChatAdapter(BasePlatformAdapter):
|
||||
block = f"\n\n[FILE CONTENT: {fname}]\n{content[:10000]}\n[/FILE]"
|
||||
text += block
|
||||
logger.debug("[rocketchat] Inlined file %s (%d chars)", fname, len(block))
|
||||
# P2-1: Alle übrigen [FILE]-Blöcke entfernen (fehlgeschlagene Downloads)
|
||||
# Non-greedy Pattern: erfasst [FILE]...Download:... bis zum nächsten \n
|
||||
# re.DOTALL damit Zeilenumbrüche innerhalb des Blocks matchen
|
||||
text = re.sub(
|
||||
r'\[FILE\].*?Download:[^\n]+\n?', '', text, flags=re.DOTALL
|
||||
)
|
||||
return text
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
|
||||
@@ -133,6 +133,7 @@ class ArchivarMessageHandler:
|
||||
"""
|
||||
self._send_callback = send_callback
|
||||
self._button_send_callback = button_send_callback
|
||||
self._presence_engine = None # P2-2: via set_presence_engine() gesetzt
|
||||
self._enable_llm = LLM_CONFIG["enabled"]
|
||||
|
||||
# Create LLM client if enabled and not provided
|
||||
@@ -549,6 +550,8 @@ class ArchivarMessageHandler:
|
||||
|
||||
Button-Garantie: REST-Pfad first, Text-Fallback nur bei Fehler.
|
||||
|
||||
P2-2: Setzt PresenceEngine auf away (gelb) während der Klärung läuft.
|
||||
|
||||
Args:
|
||||
room_id: Zielraum-ID
|
||||
text: Originalnachricht
|
||||
@@ -557,6 +560,11 @@ class ArchivarMessageHandler:
|
||||
Returns:
|
||||
True wenn erfolgreich gesendet, False bei Fehler
|
||||
"""
|
||||
# P2-2: PresenceEngine — Klärung pending → away (gelb)
|
||||
_pe = getattr(self, '_presence_engine', None)
|
||||
if _pe is not None:
|
||||
_pe.set_clarification_pending(room_id)
|
||||
_pe.update_presence()
|
||||
try:
|
||||
# Hole Button-Template
|
||||
template = BUTTON_TEMPLATES.get("clarify_intent", {})
|
||||
@@ -608,6 +616,11 @@ class ArchivarMessageHandler:
|
||||
self._stats["errors"] += 1
|
||||
self._stats["last_error"] = str(e)
|
||||
return False
|
||||
finally:
|
||||
# P2-2: Cleanup — Klärung abgeschlossen (egal ob Erfolg/Fehler)
|
||||
if _pe is not None:
|
||||
_pe.clear_clarification_pending(room_id)
|
||||
_pe.update_presence()
|
||||
|
||||
async def _send_move_request(self, room_id: str, text: str, decision: RoutingDecision) -> bool:
|
||||
"""Sende einen Move-Request-Button (Butler-Prinzip).
|
||||
@@ -1164,6 +1177,14 @@ class ArchivarMessageHandler:
|
||||
self._button_send_callback = callback
|
||||
logger.debug("Button send callback registered")
|
||||
|
||||
def set_presence_engine(self, engine) -> None:
|
||||
"""P2-2: Setze PresenceEngine-Referenz für Klärungsflow-Status.
|
||||
|
||||
Args:
|
||||
engine: PresenceEngine-Instanz oder None.
|
||||
"""
|
||||
self._presence_engine = engine
|
||||
|
||||
def set_subscribed_room_ids(self, room_ids: Optional[list]) -> None:
|
||||
"""Set the bot's current subscribed room IDs for routing validation.
|
||||
|
||||
@@ -1223,14 +1244,23 @@ class ArchivarMessageHandler:
|
||||
strategie_topics = {"absprache", "planung", "strategie", "entscheidung"}
|
||||
return topic.lower().strip() in strategie_topics
|
||||
|
||||
def _get_nachklaerung_buttons(self) -> dict:
|
||||
def _get_nachklaerung_buttons(self, keywords: Optional[list] = None) -> dict:
|
||||
"""Gibt die Nachklärungs-Buttons für A2 zurück.
|
||||
|
||||
Args:
|
||||
keywords: Optionale Liste von Keywords des Zielraums,
|
||||
die als lesbarer Text in die Nachricht eingebaut werden.
|
||||
|
||||
Returns:
|
||||
Button-Template mit Strategie-Optionen.
|
||||
"""
|
||||
text = "Ist es eines dieser Themen?"
|
||||
if keywords:
|
||||
kw_list = ", ".join(keywords)
|
||||
text = f"Ist es eines dieser Themen?\nKeywords: {kw_list}"
|
||||
|
||||
return {
|
||||
"text": "Ist es eines dieser Themen?",
|
||||
"text": text,
|
||||
"actions": [
|
||||
{"text": "🤝 Absprache", "type": "absprache"},
|
||||
{"text": "📋 Planung", "type": "planung"},
|
||||
|
||||
@@ -211,12 +211,19 @@ class InlineCommandRegistry:
|
||||
# ── Help-Text-Generator ─────────────────────────────────────────────────
|
||||
|
||||
|
||||
def build_help_text(registry: InlineCommandRegistry, room_map_summary: str = "") -> str:
|
||||
def build_help_text(
|
||||
registry: InlineCommandRegistry,
|
||||
room_map_summary: str = "",
|
||||
presence_enabled: Optional[bool] = None,
|
||||
current_status: str = "online",
|
||||
) -> str:
|
||||
"""Baut die Hilfeseite mit ::-Befehlen und natürlichen Sprach-Befehlen.
|
||||
|
||||
Args:
|
||||
registry: Die InlineCommandRegistry mit allen registrierten Befehlen.
|
||||
room_map_summary: Optionale Raum-Map-Übersicht für den Status-Teil.
|
||||
presence_enabled: Ob die PresenceEngine aktiv ist (None = nicht verfügbar).
|
||||
current_status: Aktueller Presence-Status ('online', 'away', 'busy').
|
||||
|
||||
Returns:
|
||||
Formatierte Hilfeseite als Markdown-String.
|
||||
@@ -290,6 +297,26 @@ def build_help_text(registry: InlineCommandRegistry, room_map_summary: str = "")
|
||||
lines.append("### 📋 Plugin-Status")
|
||||
lines.append("")
|
||||
|
||||
# P1-4: Status-Farben (Flughafen-Prinzip) — nur wenn PresenceEngine aktiv
|
||||
if presence_enabled:
|
||||
status_emoji = {
|
||||
"online": "🟢 online (idle, verfügbar)",
|
||||
"away": "🟡 away (Hintergrund-Task aktiv, Heartbeat pulsiert)",
|
||||
"busy": "🔴 busy (verarbeitet Nachricht)",
|
||||
}
|
||||
lines.append("### 🚦 Status-Farben")
|
||||
lines.append("")
|
||||
lines.append(
|
||||
"Der Bot zeigt seinen Status nach dem **Flughafen-Prinzip** an: "
|
||||
"wie eine Ampel signalisiert er, ob er bereit (grün), beschäftigt "
|
||||
"(rot) oder im Hintergrund aktiv (gelb) ist."
|
||||
)
|
||||
lines.append("")
|
||||
for status, label in status_emoji.items():
|
||||
marker = " ← aktuell" if status == current_status else ""
|
||||
lines.append(f"- {label}{marker}")
|
||||
lines.append("")
|
||||
|
||||
if room_map_summary:
|
||||
lines.append(room_map_summary)
|
||||
else:
|
||||
@@ -314,6 +341,9 @@ def build_status_text(
|
||||
butler_mode: str = "unknown",
|
||||
onboarding_active: bool = False,
|
||||
room_map_summary: str = "",
|
||||
presence_enabled: Optional[bool] = None,
|
||||
current_status: str = "online",
|
||||
pulse_active: bool = False,
|
||||
) -> str:
|
||||
"""Baut die Status-Seite mit aktuellen Plugin-Informationen.
|
||||
|
||||
@@ -323,6 +353,9 @@ def build_status_text(
|
||||
butler_mode: Butler-Modus ('cognitive', 'strict', 'off').
|
||||
onboarding_active: Ob Onboarding gerade läuft.
|
||||
room_map_summary: Raum-Map-Übersicht.
|
||||
presence_enabled: Ob die PresenceEngine aktiv ist (None = nicht anzeigen).
|
||||
current_status: Aktueller Presence-Status ('online', 'away', 'busy').
|
||||
pulse_active: Ob der PulseController gerade pulsiert.
|
||||
|
||||
Returns:
|
||||
Formatierte Status-Seite.
|
||||
@@ -342,6 +375,21 @@ def build_status_text(
|
||||
f"- **Onboarding:** {'🔄 Läuft' if onboarding_active else '✅ Abgeschlossen'}",
|
||||
]
|
||||
|
||||
# P1-4: PresenceEngine-Info (nur wenn presence_enabled explizit gesetzt)
|
||||
if presence_enabled is not None:
|
||||
status_labels = {
|
||||
"online": "🟢 online (idle, verfügbar)",
|
||||
"away": "🟡 away (Hintergrund-Task aktiv)",
|
||||
"busy": "🔴 busy (verarbeitet Nachricht)",
|
||||
}
|
||||
pulse_label = "💓 aktiv" if pulse_active else "⏸️ inaktiv"
|
||||
if presence_enabled:
|
||||
lines.append(f"- **PresenceEngine:** ✅ Aktiv")
|
||||
lines.append(f"- **Aktueller Status:** {status_labels.get(current_status, current_status)}")
|
||||
lines.append(f"- **Pulse:** {pulse_label}")
|
||||
else:
|
||||
lines.append(f"- **PresenceEngine:** ❌ Inaktiv")
|
||||
|
||||
if room_map_summary:
|
||||
lines.append("")
|
||||
lines.append(room_map_summary)
|
||||
|
||||
+617
-110
@@ -9,14 +9,16 @@ Zero external dependencies — stdlib only.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
from typing import Optional, Dict
|
||||
from typing import Optional, Dict, Callable
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
# Ensure presence_engine logs are visible in journalctl by adding a stderr handler
|
||||
@@ -58,6 +60,8 @@ def _format_presence_message(
|
||||
return "Onboarding läuft"
|
||||
elif status == "away_move_request":
|
||||
return f"Wartet auf Bestätigung in {room_name}" if room_name else "Wartet auf Bestätigung"
|
||||
elif status == "away_clarification":
|
||||
return "Klärung läuft — wartet auf Antwort"
|
||||
elif status == "away_error":
|
||||
return f"⚠️ Fehler: {error}" if error else "⚠️ Fehler"
|
||||
elif status == "heartbeat":
|
||||
@@ -83,7 +87,8 @@ class PresenceEngine:
|
||||
rest=None,
|
||||
enabled: bool = True,
|
||||
coalesce_ms: int = 2000,
|
||||
pulse_interval: float = 10,
|
||||
pulse_interval: float = 1.5,
|
||||
gateway_state_path: str = "",
|
||||
_clamp_pulse: bool = True,
|
||||
):
|
||||
"""Initialize the PresenceEngine.
|
||||
@@ -92,8 +97,10 @@ class PresenceEngine:
|
||||
rest: RocketChatREST instance for API calls.
|
||||
enabled: Whether presence updates are enabled.
|
||||
coalesce_ms: Coalesce delay in milliseconds (default 2000).
|
||||
pulse_interval: Heartbeat pulse interval in seconds (5-30, default 10).
|
||||
_clamp_pulse: If True, clamp pulse_interval to 5-30. Set False for testing.
|
||||
pulse_interval: PulseController interval in seconds (0.5-30, default 1.5).
|
||||
gateway_state_path: Path to gateway_state.json. Defaults to
|
||||
ROCKETCHAT_GATEWAY_STATE_PATH env var or ~/.hermes/gateway_state.json.
|
||||
_clamp_pulse: If True, clamp pulse_interval to 0.5-30. Set False for testing.
|
||||
"""
|
||||
self._rest = rest
|
||||
self._enabled = enabled
|
||||
@@ -120,19 +127,32 @@ class PresenceEngine:
|
||||
self._move_request_pending: Dict[str, str] = {} # room_id → room_name
|
||||
self._error_state: Optional[str] = None
|
||||
|
||||
# P2-2: Klärungsflow — Butler wartet auf Antwort (gelb/away)
|
||||
self._clarification_pending: set = set() # Set[str] of room_ids
|
||||
|
||||
# Current room name for busy messages
|
||||
self._current_room_name: str = ""
|
||||
|
||||
# Heartbeat
|
||||
if _clamp_pulse:
|
||||
self._pulse_interval: float = max(5.0, min(30.0, float(pulse_interval)))
|
||||
else:
|
||||
self._pulse_interval: float = float(pulse_interval)
|
||||
# Background tasks counter (for display + PulseController coordination)
|
||||
self._background_tasks: int = 0
|
||||
self._background_tasks_lock = threading.Lock()
|
||||
self._heartbeat_thread: Optional[threading.Thread] = None
|
||||
self._heartbeat_running = threading.Event()
|
||||
self._heartbeat_phase: bool = False # False=online, True=away
|
||||
|
||||
# P0-1: PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s)
|
||||
self._pulse_controller = PulseController(
|
||||
pulse_interval=pulse_interval,
|
||||
_clamp_pulse=_clamp_pulse,
|
||||
)
|
||||
|
||||
# P0-1: DetectionTimer — erkennt Hintergrund-Agenten, steuert PulseController
|
||||
self._detection_timer = DetectionTimer(
|
||||
gateway_state_path=gateway_state_path,
|
||||
detection_interval=10.0,
|
||||
on_change=self._on_detection_change,
|
||||
)
|
||||
|
||||
# Start detection if enabled
|
||||
if self._enabled:
|
||||
self._detection_timer.start()
|
||||
|
||||
# ── Public API ───────────────────────────────────────────────────────
|
||||
|
||||
@@ -141,14 +161,16 @@ class PresenceEngine:
|
||||
return self._enabled
|
||||
|
||||
def enable(self) -> None:
|
||||
"""Enable presence updates."""
|
||||
"""Enable presence updates. Starts DetectionTimer."""
|
||||
self._enabled = True
|
||||
self._detection_timer.start()
|
||||
logger.info("[presence] PresenceEngine enabled")
|
||||
|
||||
def disable(self) -> None:
|
||||
"""Disable presence updates. Stops heartbeat if running."""
|
||||
"""Disable presence updates. Stops PulseController and DetectionTimer."""
|
||||
self._enabled = False
|
||||
self._stop_heartbeat()
|
||||
self._pulse_controller.stop()
|
||||
self._detection_timer.stop()
|
||||
logger.info("[presence] PresenceEngine disabled")
|
||||
|
||||
def increment_active_tasks(self) -> int:
|
||||
@@ -170,7 +192,14 @@ class PresenceEngine:
|
||||
with self._active_tasks_lock:
|
||||
if self._active_tasks > 0:
|
||||
self._active_tasks -= 1
|
||||
return self._active_tasks
|
||||
count = self._active_tasks
|
||||
# FIX: Resume pulse when all active tasks complete.
|
||||
# on_agent_busy() pauses the pulse, but resume() was never called
|
||||
# in production — the pulse stayed paused forever.
|
||||
if count == 0:
|
||||
self._pulse_controller.resume()
|
||||
logger.info("[presence] active_tasks=0 → pulse resumed")
|
||||
return count
|
||||
|
||||
def set_onboarding_active(self, active: bool) -> None:
|
||||
"""Set the onboarding sentinel."""
|
||||
@@ -184,6 +213,14 @@ class PresenceEngine:
|
||||
"""Clear a move request."""
|
||||
self._move_request_pending.pop(room_id, None)
|
||||
|
||||
def set_clarification_pending(self, room_id: str) -> None:
|
||||
"""P2-2: Markiere Raum als wartend auf Klärungsantwort."""
|
||||
self._clarification_pending.add(room_id)
|
||||
|
||||
def clear_clarification_pending(self, room_id: str) -> None:
|
||||
"""P2-2: Klärung für Raum abgeschlossen."""
|
||||
self._clarification_pending.discard(room_id)
|
||||
|
||||
def set_error_state(self, error: Optional[str]) -> None:
|
||||
"""Set or clear the error state."""
|
||||
self._error_state = error
|
||||
@@ -201,7 +238,7 @@ class PresenceEngine:
|
||||
with self._background_tasks_lock:
|
||||
self._background_tasks += 1
|
||||
count = self._background_tasks
|
||||
self._maybe_start_heartbeat()
|
||||
self._pulse_controller.set_background_count(count)
|
||||
return count
|
||||
|
||||
def decrement_background_tasks(self) -> int:
|
||||
@@ -214,8 +251,9 @@ class PresenceEngine:
|
||||
if self._background_tasks > 0:
|
||||
self._background_tasks -= 1
|
||||
count = self._background_tasks
|
||||
self._pulse_controller.set_background_count(count)
|
||||
if count == 0:
|
||||
self._stop_heartbeat()
|
||||
self._pulse_controller.stop()
|
||||
return count
|
||||
|
||||
# ── Internal: Presence Setting ───────────────────────────────────────
|
||||
@@ -233,6 +271,12 @@ class PresenceEngine:
|
||||
if not self._enabled:
|
||||
return
|
||||
|
||||
# EC-5: Cancel pending pulse when higher-priority status fires.
|
||||
# Only cancel for non-online statuses — "online" is the pulse's own
|
||||
# target and cancelling it would prevent the pulse from working.
|
||||
if status != "online":
|
||||
self.cancel_pending()
|
||||
|
||||
with self._coalesce_lock:
|
||||
self._pending_status = status
|
||||
self._pending_message = message
|
||||
@@ -311,102 +355,24 @@ class PresenceEngine:
|
||||
except Exception as e:
|
||||
logger.warning("[presence] Failed to set status: %s", e)
|
||||
|
||||
# ── Heartbeat ────────────────────────────────────────────────────────
|
||||
# ── DetectionTimer Callback ──────────────────────────────────────────
|
||||
|
||||
def _maybe_start_heartbeat(self) -> None:
|
||||
"""Start heartbeat if background_tasks > 0 and agent is idle.
|
||||
def _on_detection_change(self, is_active: bool) -> None:
|
||||
"""Callback from DetectionTimer: start/stop PulseController.
|
||||
|
||||
P1-5: Hält beide Locks gleichzeitig um Race Condition zu vermeiden.
|
||||
When background agents are detected (is_active=True), start pulsing.
|
||||
When no background agents (is_active=False), stop pulsing.
|
||||
"""
|
||||
if not self._enabled:
|
||||
return
|
||||
# P1-5: Beide Locks gleichzeitig halten für konsistente Snapshot-Reads
|
||||
with self._active_tasks_lock:
|
||||
with self._background_tasks_lock:
|
||||
is_idle = self._active_tasks == 0
|
||||
has_background = self._background_tasks > 0
|
||||
|
||||
if has_background and is_idle and not self._heartbeat_running.is_set():
|
||||
self._start_heartbeat()
|
||||
|
||||
def _start_heartbeat(self) -> None:
|
||||
"""Start the heartbeat pulse thread."""
|
||||
if not self._enabled:
|
||||
return
|
||||
if self._heartbeat_running.is_set():
|
||||
return
|
||||
|
||||
self._heartbeat_running.set()
|
||||
self._heartbeat_phase = False # Start with online
|
||||
|
||||
self._heartbeat_thread = threading.Thread(
|
||||
target=self._heartbeat_loop,
|
||||
daemon=True,
|
||||
name="presence-heartbeat",
|
||||
)
|
||||
self._heartbeat_thread.start()
|
||||
logger.info("[presence] Heartbeat started (interval=%ds)", self._pulse_interval)
|
||||
|
||||
def _stop_heartbeat(self) -> None:
|
||||
"""Stop the heartbeat pulse thread."""
|
||||
if not self._heartbeat_running.is_set():
|
||||
return
|
||||
|
||||
self._heartbeat_running.clear()
|
||||
|
||||
# Wait for thread to finish (with timeout)
|
||||
if self._heartbeat_thread is not None and self._heartbeat_thread.is_alive():
|
||||
self._heartbeat_thread.join(timeout=self._pulse_interval + 1)
|
||||
|
||||
self._heartbeat_thread = None
|
||||
logger.info("[presence] Heartbeat stopped")
|
||||
|
||||
def _heartbeat_loop(self) -> None:
|
||||
"""Background thread: pulse between online and away.
|
||||
|
||||
P1-5: Hält beide Locks gleichzeitig für konsistente Snapshot-Reads.
|
||||
"""
|
||||
while self._heartbeat_running.is_set():
|
||||
# P1-5: Beide Locks gleichzeitig halten
|
||||
with self._background_tasks_lock:
|
||||
with self._active_tasks_lock:
|
||||
bg_count = self._background_tasks
|
||||
is_idle = self._active_tasks == 0
|
||||
|
||||
if bg_count == 0:
|
||||
# No more background tasks — stop
|
||||
self._heartbeat_running.clear()
|
||||
# Set back to online (bypass coalesce for immediate effect)
|
||||
self._send_rest("online", "")
|
||||
self._last_sent_status = "online"
|
||||
self._last_sent_message = ""
|
||||
break
|
||||
|
||||
if not is_idle:
|
||||
# Agent is busy — stop pulsing, let busy status take over
|
||||
self._heartbeat_running.clear()
|
||||
break
|
||||
|
||||
# Toggle phase
|
||||
self._heartbeat_phase = not self._heartbeat_phase
|
||||
|
||||
if self._heartbeat_phase:
|
||||
# Away phase: show heartbeat message
|
||||
msg = _format_presence_message("heartbeat", background_count=bg_count)
|
||||
self._send_rest("away", msg)
|
||||
self._last_sent_status = "away"
|
||||
self._last_sent_message = msg
|
||||
if is_active:
|
||||
if not self._pulse_controller.is_running():
|
||||
self._pulse_controller.start()
|
||||
logger.info("[presence] PulseController gestartet (Hintergrund-Agenten erkannt)")
|
||||
else:
|
||||
# Online phase: no message
|
||||
self._send_rest("online", "")
|
||||
self._last_sent_status = "online"
|
||||
self._last_sent_message = ""
|
||||
|
||||
# Sleep for pulse interval, checking running flag periodically
|
||||
for _ in range(int(self._pulse_interval * 10)):
|
||||
if not self._heartbeat_running.is_set():
|
||||
break
|
||||
time.sleep(0.1)
|
||||
if self._pulse_controller.is_running():
|
||||
self._pulse_controller.stop()
|
||||
logger.info("[presence] PulseController gestoppt (keine Hintergrund-Agenten)")
|
||||
|
||||
# ── Convenience: Determine and set appropriate presence ──────────────
|
||||
|
||||
@@ -443,6 +409,12 @@ class PresenceEngine:
|
||||
self._set_presence("away", msg)
|
||||
return
|
||||
|
||||
# 3b. P2-2: Clarification pending (nach Move-Request, vor Active-Tasks)
|
||||
if self._clarification_pending:
|
||||
msg = _format_presence_message("away_clarification")
|
||||
self._set_presence("away", msg)
|
||||
return
|
||||
|
||||
# 4. Active tasks
|
||||
with self._active_tasks_lock:
|
||||
active = self._active_tasks
|
||||
@@ -454,9 +426,544 @@ class PresenceEngine:
|
||||
self._set_presence("online", "")
|
||||
|
||||
def shutdown(self) -> None:
|
||||
"""Clean shutdown: stop heartbeat, cancel coalesce timer."""
|
||||
self._stop_heartbeat()
|
||||
"""Clean shutdown: stop PulseController, DetectionTimer, cancel coalesce timer."""
|
||||
self._pulse_controller.stop()
|
||||
self._detection_timer.stop()
|
||||
with self._coalesce_lock:
|
||||
if self._coalesce_timer is not None:
|
||||
self._coalesce_timer.cancel()
|
||||
self._coalesce_timer = None
|
||||
|
||||
# ── PulseController Integration ──────────────────────────────────────
|
||||
|
||||
def cancel_pending(self) -> None:
|
||||
"""Cancel any pending pulse tick (K2: API auf PresenceEngine).
|
||||
|
||||
Called by _set_presence when a higher-priority status fires
|
||||
while the PulseController is running (EC-5).
|
||||
"""
|
||||
self._pulse_controller.cancel_pending()
|
||||
|
||||
def on_agent_busy(self, room_name: str = "") -> None:
|
||||
"""Hook: Agent is processing a message — pause pulse, set busy.
|
||||
|
||||
Priority 1 (highest): busy (rot) — Nachricht wird verarbeitet.
|
||||
"""
|
||||
self.set_current_room(room_name)
|
||||
self.increment_active_tasks()
|
||||
self.update_presence()
|
||||
# Pause pulse if running
|
||||
self._pulse_controller.pause()
|
||||
|
||||
def on_message_received(self, room_name: str = "") -> None:
|
||||
"""Hook: Message received — same as on_agent_busy.
|
||||
|
||||
Alias for on_agent_busy for semantic clarity.
|
||||
"""
|
||||
self.on_agent_busy(room_name=room_name)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# PulseController — DDP-basierte Heartbeat-Pulsierung (1.5s Intervall)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class PulseController:
|
||||
"""DDP-based pulse timer: toggles online↔away at configurable interval.
|
||||
|
||||
Uses DDP set_status (NOT REST) for the status toggle.
|
||||
REST fallback only for message text (K1: DDP set_status has no message variant).
|
||||
|
||||
Thread-safe: uses threading.Event for start/stop signalling.
|
||||
Coalesce: skips duplicate status calls (if already away and tick wants away).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
pulse_interval: float = 1.5,
|
||||
_clamp_pulse: bool = True,
|
||||
):
|
||||
"""Initialize PulseController.
|
||||
|
||||
Args:
|
||||
pulse_interval: Pulse interval in seconds (default 1.5).
|
||||
_clamp_pulse: If True, clamp to 0.5-30s. Set False for testing.
|
||||
"""
|
||||
if _clamp_pulse:
|
||||
self._pulse_interval: float = max(0.5, min(30.0, float(pulse_interval)))
|
||||
else:
|
||||
self._pulse_interval: float = float(pulse_interval)
|
||||
|
||||
self._ddp: Optional[object] = None
|
||||
self._rest: Optional[object] = None
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
self._running = threading.Event()
|
||||
self._paused = threading.Event()
|
||||
self._phase: bool = False # False=online, True=away
|
||||
self._last_sent_phase: Optional[bool] = None
|
||||
self._background_count: int = 0
|
||||
self._cancel_pending: bool = False # P0-2: skip next tick flag
|
||||
# P1-2 O-2: Async-await bridge
|
||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||
self._await_timeout: float = 2.0
|
||||
|
||||
# ── Public API ───────────────────────────────────────────────────────
|
||||
|
||||
def bind_ddp(self, ddp: object) -> None:
|
||||
"""Bind a DDP client reference for set_status calls.
|
||||
|
||||
Args:
|
||||
ddp: DDPClient instance with set_status(status) method.
|
||||
"""
|
||||
self._ddp = ddp
|
||||
|
||||
def bind_rest(self, rest: object) -> None:
|
||||
"""Bind a REST client reference for fallback status+message calls.
|
||||
|
||||
Args:
|
||||
rest: RocketChatREST instance with _request method.
|
||||
"""
|
||||
self._rest = rest
|
||||
|
||||
def bind_loop(self, loop: asyncio.AbstractEventLoop) -> None:
|
||||
"""P1-2 O-2: Bind the asyncio event loop for async-await bridge.
|
||||
|
||||
When a loop is bound, _pulse_tick delegates to _pulse_tick_async
|
||||
via run_coroutine_threadsafe. Without a loop, the legacy sync
|
||||
path is used (graceful degradation).
|
||||
|
||||
Args:
|
||||
loop: The running asyncio event loop.
|
||||
"""
|
||||
self._loop = loop
|
||||
|
||||
def set_background_count(self, count: int) -> None:
|
||||
"""Set the background task count for heartbeat messages."""
|
||||
self._background_count = count
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the pulse thread."""
|
||||
logger.info(
|
||||
"[pulse] start() called, _running=%s, _ddp=%s, _phase=%s, _paused=%s",
|
||||
self._running.is_set(),
|
||||
self._ddp is not None,
|
||||
self._phase,
|
||||
self._paused.is_set(),
|
||||
)
|
||||
if self._running.is_set():
|
||||
logger.info("[pulse] start() skip: already running")
|
||||
return
|
||||
|
||||
# P1-1: Check DDP availability before starting
|
||||
if self._ddp is None:
|
||||
logger.warning(
|
||||
"[pulse] PulseController.start() called without DDP bound — "
|
||||
"pulses will have no effect until bind_ddp() is called"
|
||||
)
|
||||
|
||||
self._running.set()
|
||||
self._paused.clear()
|
||||
self._phase = False # Start with online
|
||||
self._last_sent_phase = None
|
||||
|
||||
self._thread = threading.Thread(
|
||||
target=self._pulse_loop,
|
||||
daemon=True,
|
||||
name="pulse-controller",
|
||||
)
|
||||
self._thread.start()
|
||||
logger.info(
|
||||
"[pulse] PulseController started (interval=%.1fs, loop-bound=%s, async-path=%s)",
|
||||
self._pulse_interval,
|
||||
self._loop is not None,
|
||||
self._loop is not None and self._loop.is_running(),
|
||||
)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Stop the pulse thread and wait for it to finish."""
|
||||
if not self._running.is_set():
|
||||
return
|
||||
self._running.clear()
|
||||
self._paused.clear()
|
||||
|
||||
if self._thread is not None and self._thread.is_alive():
|
||||
self._thread.join(timeout=self._pulse_interval + 1)
|
||||
|
||||
self._thread = None
|
||||
logger.info("[pulse] PulseController stopped")
|
||||
|
||||
def pause(self) -> None:
|
||||
"""Pause pulsing without stopping the thread (EC-2: reconnect race)."""
|
||||
self._paused.set()
|
||||
logger.debug("[pulse] PulseController paused")
|
||||
|
||||
def resume(self) -> None:
|
||||
"""Resume pulsing after pause (EC-2: reconnect race)."""
|
||||
self._paused.clear()
|
||||
logger.debug("[pulse] PulseController resumed")
|
||||
|
||||
def is_running(self) -> bool:
|
||||
"""Check if the pulse thread is running."""
|
||||
return self._running.is_set()
|
||||
|
||||
def cancel_pending(self) -> None:
|
||||
"""Cancel any pending pulse tick (K2: EC-5).
|
||||
|
||||
Called by PresenceEngine._set_presence when a higher-priority
|
||||
status fires while the PulseController is running.
|
||||
Sets a flag that the next tick will skip.
|
||||
"""
|
||||
self._cancel_pending = True
|
||||
logger.debug("[pulse] cancel_pending: next tick will be skipped")
|
||||
|
||||
# ── Internal: Pulse Loop ─────────────────────────────────────────────
|
||||
|
||||
def _pulse_loop(self) -> None:
|
||||
"""Background thread: pulse between online and away."""
|
||||
logger.info("[pulse] _pulse_loop started, interval=%.1fs", self._pulse_interval)
|
||||
iteration = 0
|
||||
while self._running.is_set():
|
||||
iteration += 1
|
||||
# Check if paused
|
||||
if self._paused.is_set():
|
||||
if iteration == 1 or iteration % 50 == 0:
|
||||
logger.debug(
|
||||
"[pulse] _pulse_loop iteration=%d: PAUSED (waiting for resume)",
|
||||
iteration,
|
||||
)
|
||||
time.sleep(0.1)
|
||||
continue
|
||||
|
||||
logger.debug(
|
||||
"[pulse] _pulse_loop iteration=%d: calling _pulse_tick, phase=%s, ddp=%s",
|
||||
iteration,
|
||||
self._phase,
|
||||
self._ddp is not None,
|
||||
)
|
||||
self._pulse_tick()
|
||||
|
||||
# Sleep for pulse interval, checking running flag periodically
|
||||
for _ in range(int(self._pulse_interval * 10)):
|
||||
if not self._running.is_set():
|
||||
break
|
||||
if self._paused.is_set():
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
def _pulse_tick(self) -> None:
|
||||
"""Execute one pulse tick: toggle phase and send status.
|
||||
|
||||
P1-2 O-2: When an asyncio loop is bound, delegates to
|
||||
_pulse_tick_async via run_coroutine_threadsafe. Otherwise
|
||||
uses the legacy sync path (graceful degradation).
|
||||
"""
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick fired, phase=%s, ddp=%s, paused=%s, cancel_pending=%s, loop=%s",
|
||||
self._phase,
|
||||
self._ddp is not None,
|
||||
self._paused.is_set(),
|
||||
self._cancel_pending,
|
||||
self._loop is not None,
|
||||
)
|
||||
|
||||
# P0-2: Check cancel_pending flag (set by PresenceEngine._set_presence)
|
||||
if self._cancel_pending:
|
||||
self._cancel_pending = False
|
||||
logger.debug("[pulse] _pulse_tick skip: cancel_pending was set")
|
||||
return
|
||||
|
||||
# Toggle phase
|
||||
self._phase = not self._phase
|
||||
|
||||
# Coalesce: skip if same phase as last sent
|
||||
if self._phase == self._last_sent_phase:
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick skip: coalesce (phase=%s == last_sent)",
|
||||
self._phase,
|
||||
)
|
||||
return
|
||||
|
||||
# P1-2 O-2: Delegate to async path if loop is bound and running
|
||||
if self._loop is not None and self._loop.is_running():
|
||||
try:
|
||||
future = asyncio.run_coroutine_threadsafe(
|
||||
self._pulse_tick_async(),
|
||||
self._loop,
|
||||
)
|
||||
future.result(timeout=self._pulse_interval)
|
||||
return
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"[pulse] _pulse_tick async path failed: %s — falling back to sync",
|
||||
e,
|
||||
)
|
||||
# Fall through to legacy sync path below
|
||||
|
||||
# ── Legacy sync path (no loop bound, or async path failed) ──────
|
||||
status = "away" if self._phase else "online"
|
||||
logger.debug("[pulse] _pulse_tick sending (sync): status=%s", status)
|
||||
|
||||
# Try DDP first (K1: DDP set_status has no message variant)
|
||||
if self._ddp is not None and getattr(self._ddp, 'connected', False):
|
||||
try:
|
||||
self._ddp.set_status(status)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
logger.debug("[pulse] _pulse_tick DDP set_status OK: %s", status)
|
||||
return
|
||||
except Exception as e:
|
||||
logger.info("[pulse] _pulse_tick DDP set_status failed: %s", e)
|
||||
|
||||
# REST fallback for message text
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
try:
|
||||
msg = ""
|
||||
if self._phase:
|
||||
msg = _format_presence_message("heartbeat", background_count=self._background_count)
|
||||
self._rest._request(
|
||||
"POST", "/api/v1/users.setStatus",
|
||||
headers={
|
||||
"X-Auth-Token": self._rest.auth_token,
|
||||
"X-User-Id": self._rest.user_id,
|
||||
},
|
||||
data={"status": status, "message": msg} if msg else {"status": status},
|
||||
)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
logger.debug("[pulse] _pulse_tick REST setStatus OK: %s", status)
|
||||
except Exception as e:
|
||||
logger.info("[pulse] _pulse_tick REST setStatus failed: %s", e)
|
||||
else:
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick skip: no DDP and no REST available (ddp=%s, rest=%s)",
|
||||
self._ddp is not None,
|
||||
self._rest is not None,
|
||||
)
|
||||
|
||||
async def _pulse_tick_async(self) -> None:
|
||||
"""P1-2 O-2: Async pulse tick using await set_status_async.
|
||||
|
||||
Runs on the asyncio event loop (dispatched via
|
||||
run_coroutine_threadsafe from the pulse thread).
|
||||
Uses DDPClient.set_status_async for true await-semantics
|
||||
with timeout and error handling.
|
||||
"""
|
||||
status = "away" if self._phase else "online"
|
||||
logger.debug("[pulse] _pulse_tick_async sending: status=%s", status)
|
||||
|
||||
# Try DDP with await-semantics
|
||||
if self._ddp is not None and getattr(self._ddp, 'connected', False):
|
||||
try:
|
||||
await self._ddp.set_status_async(status, timeout=self._await_timeout)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
logger.debug("[pulse] _pulse_tick_async DDP set_status_async OK: %s", status)
|
||||
return
|
||||
except Exception as e:
|
||||
logger.info(
|
||||
"[pulse] _pulse_tick_async DDP set_status_async failed: %s — "
|
||||
"falling back to REST",
|
||||
e,
|
||||
)
|
||||
|
||||
# REST fallback for message text
|
||||
if self._rest is not None and getattr(self._rest, 'auth_token', None):
|
||||
try:
|
||||
msg = ""
|
||||
if self._phase:
|
||||
msg = _format_presence_message("heartbeat", background_count=self._background_count)
|
||||
self._rest._request(
|
||||
"POST", "/api/v1/users.setStatus",
|
||||
headers={
|
||||
"X-Auth-Token": self._rest.auth_token,
|
||||
"X-User-Id": self._rest.user_id,
|
||||
},
|
||||
data={"status": status, "message": msg} if msg else {"status": status},
|
||||
)
|
||||
self._last_sent_phase = self._phase
|
||||
self._increment_telemetry()
|
||||
logger.debug("[pulse] _pulse_tick_async REST setStatus OK: %s", status)
|
||||
except Exception as e:
|
||||
logger.info("[pulse] _pulse_tick_async REST setStatus failed: %s", e)
|
||||
else:
|
||||
logger.debug(
|
||||
"[pulse] _pulse_tick_async skip: no DDP and no REST available",
|
||||
)
|
||||
|
||||
def _increment_telemetry(self) -> None:
|
||||
"""Increment the heartbeat_pulse telemetry counter.
|
||||
|
||||
NOTE: Coupled to archivar.routing_telemetry.routing_telemetry.
|
||||
This is a cross-module dependency that should be refactored
|
||||
to use a shared telemetry interface or event bus.
|
||||
"""
|
||||
try:
|
||||
from archivar.routing_telemetry import routing_telemetry
|
||||
routing_telemetry.heartbeat_pulse += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# DetectionTimer — erkennt Hintergrund-Agenten (10s Intervall)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class DetectionTimer:
|
||||
"""Detects whether background agents are active.
|
||||
|
||||
Checks gateway_state.json for active_agents > 1.
|
||||
Falls back to pgrep for 'hermes chat --profile' processes.
|
||||
|
||||
Calls on_change callback when detection state changes.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
gateway_state_path: str = "",
|
||||
detection_interval: float = 10.0,
|
||||
on_change: Optional[Callable[[bool], None]] = None,
|
||||
):
|
||||
"""Initialize DetectionTimer.
|
||||
|
||||
Args:
|
||||
gateway_state_path: Path to gateway_state.json.
|
||||
detection_interval: Check interval in seconds (default 10).
|
||||
on_change: Callback(is_active) when detection state changes.
|
||||
"""
|
||||
if not gateway_state_path:
|
||||
gateway_state_path = os.environ.get(
|
||||
"ROCKETCHAT_GATEWAY_STATE_PATH",
|
||||
os.path.expanduser("~/.hermes/gateway_state.json"),
|
||||
)
|
||||
self._gateway_state_path = gateway_state_path
|
||||
self._detection_interval = detection_interval
|
||||
self._on_change = on_change
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
self._running = threading.Event()
|
||||
self._last_result: Optional[bool] = False # Start with False to avoid spurious first callback
|
||||
self._check_count: int = 0 # P0-1: tick counter for diagnostic logging
|
||||
|
||||
def start(self) -> None:
|
||||
"""Start the detection timer thread."""
|
||||
if self._running.is_set():
|
||||
return
|
||||
self._running.set()
|
||||
self._thread = threading.Thread(
|
||||
target=self._detection_loop,
|
||||
daemon=True,
|
||||
name="detection-timer",
|
||||
)
|
||||
self._thread.start()
|
||||
logger.info("[detection] DetectionTimer started (interval=%.1fs)", self._detection_interval)
|
||||
|
||||
def stop(self) -> None:
|
||||
"""Stop the detection timer thread."""
|
||||
if not self._running.is_set():
|
||||
return
|
||||
self._running.clear()
|
||||
|
||||
if self._thread is not None and self._thread.is_alive():
|
||||
self._thread.join(timeout=self._detection_interval + 1)
|
||||
|
||||
self._thread = None
|
||||
logger.info("[detection] DetectionTimer stopped")
|
||||
|
||||
def check(self) -> bool:
|
||||
"""Check if background agents are active.
|
||||
|
||||
pgrep is the PRIMARY signal — always executed, regardless of gateway_state.
|
||||
gateway_state is SECONDARY — read only for diagnostic logging, never for decisions.
|
||||
|
||||
Returns:
|
||||
True if pgrep finds other hermes chat processes (self-excluded),
|
||||
False otherwise.
|
||||
"""
|
||||
self._check_count += 1
|
||||
self._increment_telemetry()
|
||||
|
||||
result = False
|
||||
pgrep_pids = -1 # -1 = not yet run, >=0 = count, stays -1 on error
|
||||
|
||||
# ── PRIMARY: pgrep — ALWAYS run ──────────────────────────────────
|
||||
try:
|
||||
own_pid = os.getpid()
|
||||
proc = subprocess.run(
|
||||
["pgrep", "-f", "hermes chat --profile"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
)
|
||||
# Parse PIDs and self-exclude
|
||||
raw_lines = [l.strip() for l in proc.stdout.strip().split("\n") if l.strip()]
|
||||
all_pids = [int(l) for l in raw_lines if l.isdigit()]
|
||||
pids = [p for p in all_pids if p != own_pid]
|
||||
pgrep_pids = len(pids)
|
||||
result = pgrep_pids > 0
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError, OSError, ValueError) as e:
|
||||
logger.debug("[detection] pgrep failed: %s", e)
|
||||
# pgrep_pids stays -1 (error sentinel)
|
||||
|
||||
# ── SECONDARY: gateway_state — diagnostic only ────────────────────
|
||||
gateway_active = 0
|
||||
try:
|
||||
if os.path.exists(self._gateway_state_path):
|
||||
with open(self._gateway_state_path, 'r') as f:
|
||||
state = json.load(f)
|
||||
gateway_active = state.get("active_agents", 0)
|
||||
except (json.JSONDecodeError, IOError, OSError) as e:
|
||||
logger.debug("[detection] gateway_state.json read failed: %s", e)
|
||||
|
||||
# ── Log: both signals, result ─────────────────────────────────────
|
||||
pgrep_str = str(pgrep_pids) if pgrep_pids >= 0 else "error"
|
||||
logger.info(
|
||||
"[detection] check #%d: pgrep=%s, gateway_state=%d, result=%s",
|
||||
self._check_count, pgrep_str, gateway_active,
|
||||
"active" if result else "inactive",
|
||||
)
|
||||
|
||||
# Notify on change (P1-2: callback fires from check() itself)
|
||||
if result != self._last_result and self._on_change is not None:
|
||||
try:
|
||||
logger.info(
|
||||
"[detection] state changed: %s→%s",
|
||||
"active" if self._last_result else "inactive",
|
||||
"active" if result else "inactive",
|
||||
)
|
||||
self._on_change(result)
|
||||
except Exception as e:
|
||||
logger.debug("[detection] on_change callback failed: %s", e)
|
||||
|
||||
self._last_result = result
|
||||
return result
|
||||
|
||||
def _detection_loop(self) -> None:
|
||||
"""Background thread: periodically check for background agents."""
|
||||
tick = 0
|
||||
while self._running.is_set():
|
||||
tick += 1
|
||||
try:
|
||||
logger.info(
|
||||
"[detection] tick #%d (interval=%.1fs)",
|
||||
tick, self._detection_interval,
|
||||
)
|
||||
self.check() # check() now handles logging + callback
|
||||
except Exception as e:
|
||||
logger.debug("[detection] check failed: %s", e)
|
||||
|
||||
# Sleep for detection interval
|
||||
for _ in range(int(self._detection_interval * 10)):
|
||||
if not self._running.is_set():
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
def _increment_telemetry(self) -> None:
|
||||
"""Increment the heartbeat_detection telemetry counter.
|
||||
|
||||
NOTE: Coupled to archivar.routing_telemetry.routing_telemetry.
|
||||
This is a cross-module dependency that should be refactored
|
||||
to use a shared telemetry interface or event bus.
|
||||
"""
|
||||
try:
|
||||
from archivar.routing_telemetry import routing_telemetry
|
||||
routing_telemetry.heartbeat_detection += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
"""
|
||||
Reply-Quote-Stripper: Entfernt zitierte Parent-Nachrichten aus Reply-Texten.
|
||||
|
||||
P0: Verhindert Fehl-Routing durch Keyword-Matches in zitierten Texten.
|
||||
Zweistufig defensiv:
|
||||
1. Attachments-basiert: Rocket.Chat sendet bei Replies die Parent-Nachricht
|
||||
als attachment mit. Entferne den zitierten Text aus dem Nachrichtentext.
|
||||
2. Text-basiert (Fallback): Regex-Heuristik für Markdown-Blockquotes (> quote)
|
||||
und [quote]-Blöcke.
|
||||
|
||||
Konfliktfrei mit Butler-Prinzip — der Strip verschärft die 100%-Heuristik,
|
||||
ohne sie zu unterlaufen.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Rocket.Chat Reply-Quote Patterns
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
# Rocket.Chat reply link pattern: [ ](https://...?msg=MSGID)
|
||||
# This is the inline reply marker that Rocket.Chat inserts when replying.
|
||||
_RC_REPLY_LINK_RE = re.compile(
|
||||
r'\[\s*\]\s*\(\s*https?://[^)]*\?msg=[^)]+\)\s*',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
# Markdown blockquote: lines starting with >
|
||||
# Matches one or more consecutive lines starting with '> '
|
||||
_BLOCKQUOTE_RE = re.compile(
|
||||
r'(?:^|\n)(?:> .*(?:\n|$))+',
|
||||
re.MULTILINE,
|
||||
)
|
||||
|
||||
# [quote]...[/quote] blocks (BBCode-style, used by some RC clients)
|
||||
_QUOTE_BLOCK_RE = re.compile(
|
||||
r'\[quote[^\]]*\].*?\[/quote\]',
|
||||
re.DOTALL | re.IGNORECASE,
|
||||
)
|
||||
|
||||
# [quote="author"]...[/quote] blocks
|
||||
_QUOTE_AUTHOR_BLOCK_RE = re.compile(
|
||||
r'\[quote=["\']?[^\]"\']*["\']?\].*?\[/quote\]',
|
||||
re.DOTALL | re.IGNORECASE,
|
||||
)
|
||||
|
||||
# Rocket.Chat attachment types that indicate a reply quote
|
||||
_REPLY_ATTACHMENT_TYPES = frozenset({
|
||||
'reply',
|
||||
'quote',
|
||||
'message',
|
||||
})
|
||||
|
||||
|
||||
def _extract_quoted_text_from_attachments(attachments: list) -> Optional[str]:
|
||||
"""Extrahiere den zitierten Text aus Reply-Attachments.
|
||||
|
||||
Rocket.Chat sendet bei Replies die Parent-Nachricht als attachment mit.
|
||||
Typische Felder:
|
||||
- attachment_type: 'reply' oder 'quote'
|
||||
- text: der zitierte Nachrichtentext
|
||||
- description: Beschreibung (z.B. Autor der Parent-Nachricht)
|
||||
- author_name: Name des Autors der Parent-Nachricht
|
||||
- message_link: Link zur Parent-Nachricht
|
||||
|
||||
Returns:
|
||||
Der zitierte Text wenn gefunden, sonst None.
|
||||
"""
|
||||
if not attachments or not isinstance(attachments, list):
|
||||
return None
|
||||
|
||||
for attachment in attachments:
|
||||
if not isinstance(attachment, dict):
|
||||
continue
|
||||
|
||||
# Check for reply/quote attachment types
|
||||
att_type = attachment.get('type', '')
|
||||
att_attachment_type = attachment.get('attachment_type', '')
|
||||
|
||||
if att_type in _REPLY_ATTACHMENT_TYPES or att_attachment_type in _REPLY_ATTACHMENT_TYPES:
|
||||
# Try to get the quoted text
|
||||
quoted = attachment.get('text', '') or attachment.get('description', '')
|
||||
if quoted:
|
||||
return quoted.strip()
|
||||
|
||||
# Also check for message_link (Rocket.Chat reply indicator)
|
||||
if attachment.get('message_link'):
|
||||
quoted = attachment.get('text', '') or attachment.get('description', '')
|
||||
if quoted:
|
||||
return quoted.strip()
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _strip_rc_reply_link(text: str) -> str:
|
||||
"""Entferne den Rocket.Chat Reply-Link [ ](url?msg=ID) aus dem Text."""
|
||||
return _RC_REPLY_LINK_RE.sub('', text).strip()
|
||||
|
||||
|
||||
def _strip_blockquotes(text: str) -> str:
|
||||
"""Entferne Markdown-Blockquotes (> quote) aus dem Text."""
|
||||
return _BLOCKQUOTE_RE.sub('', text).strip()
|
||||
|
||||
|
||||
def _strip_quote_blocks(text: str) -> str:
|
||||
"""Entferne [quote]...[/quote] Blöcke aus dem Text."""
|
||||
text = _QUOTE_AUTHOR_BLOCK_RE.sub('', text)
|
||||
text = _QUOTE_BLOCK_RE.sub('', text)
|
||||
return text.strip()
|
||||
|
||||
|
||||
def strip_reply_quote(
|
||||
text: str,
|
||||
attachments: Optional[list] = None,
|
||||
) -> Tuple[str, bool]:
|
||||
"""Entferne Reply-Quote aus einer Nachricht (P0).
|
||||
|
||||
Zweistufig defensiv:
|
||||
1. Attachments-basiert: Wenn die Nachricht Reply-Attachments enthält,
|
||||
wird der zitierte Text aus dem Nachrichtentext entfernt.
|
||||
2. Text-basiert (Fallback): Regex-Heuristik für Blockquote-Pattern.
|
||||
|
||||
Args:
|
||||
text: Der Nachrichtentext.
|
||||
attachments: Optionale Liste von Attachments aus dem msg_obj.
|
||||
|
||||
Returns:
|
||||
Tuple aus (bereinigtem Text, ob ein Quote gestrippt wurde).
|
||||
"""
|
||||
if not text:
|
||||
return text, False
|
||||
|
||||
stripped = False
|
||||
result = text
|
||||
|
||||
# ── Stufe 1: Attachments-basiert ──────────────────────────────────
|
||||
if attachments:
|
||||
quoted_text = _extract_quoted_text_from_attachments(attachments)
|
||||
if quoted_text and quoted_text in result:
|
||||
result = result.replace(quoted_text, '', 1).strip()
|
||||
stripped = True
|
||||
|
||||
# ── Stufe 1b: RC Reply-Link entfernen ──────────────────────────────
|
||||
# [ ](https://chat.example.com/group/room?msg=MSGID)
|
||||
before_link = result
|
||||
result = _strip_rc_reply_link(result)
|
||||
if result != before_link:
|
||||
stripped = True
|
||||
|
||||
# ── Stufe 2: Text-basiert (Fallback) ───────────────────────────────
|
||||
# Nur wenn Stufe 1 nichts gefunden hat
|
||||
if not stripped:
|
||||
# [quote]...[/quote] Blöcke
|
||||
before_quote = result
|
||||
result = _strip_quote_blocks(result)
|
||||
if result != before_quote:
|
||||
stripped = True
|
||||
|
||||
if not stripped:
|
||||
# Markdown-Blockquotes (> quote)
|
||||
before_bq = result
|
||||
result = _strip_blockquotes(before_bq)
|
||||
if result != before_bq:
|
||||
stripped = True
|
||||
|
||||
# Clean up: collapse multiple blank lines, strip
|
||||
result = re.sub(r'\n{3,}', '\n\n', result)
|
||||
result = result.strip()
|
||||
|
||||
return result, stripped
|
||||
|
||||
|
||||
def strip_reply_quote_for_routing(
|
||||
text: str,
|
||||
attachments: Optional[list] = None,
|
||||
) -> Tuple[str, str, bool]:
|
||||
"""P1: Trenne routing_text und display_text.
|
||||
|
||||
- routing_text: Ohne Quote — für Archivar/Keyword-Matcher/classify_and_route
|
||||
- display_text: Mit Quote — für Agent und Conversation-History
|
||||
|
||||
Args:
|
||||
text: Der originale Nachrichtentext.
|
||||
attachments: Optionale Attachments aus dem msg_obj.
|
||||
|
||||
Returns:
|
||||
Tuple aus (routing_text, display_text, was_stripped).
|
||||
Wenn kein Quote gefunden: routing_text == display_text == text.
|
||||
"""
|
||||
routing_text, was_stripped = strip_reply_quote(text, attachments)
|
||||
display_text = text # Originaltext mit Quote für Agent/History
|
||||
return routing_text, display_text, was_stripped
|
||||
@@ -49,6 +49,9 @@ class RoutingTelemetry:
|
||||
self._enabled: bool = self._read_feature_flag()
|
||||
self._records: List[Dict[str, object]] = []
|
||||
self._start_time: float = 0.0
|
||||
# Heartbeat-Pulsierung Telemetrie
|
||||
self.heartbeat_pulse: int = 0
|
||||
self.heartbeat_detection: int = 0
|
||||
|
||||
@staticmethod
|
||||
def _read_feature_flag() -> bool:
|
||||
|
||||
@@ -129,3 +129,74 @@ class TestDDPRoomEvents:
|
||||
|
||||
client._handle_ddp_message(event_data)
|
||||
assert len(received_events) == 0
|
||||
|
||||
|
||||
class TestDDPSetStatus:
|
||||
"""Tests für DDPClient.set_status — P0 Fix: UserPresence:setDefaultStatus."""
|
||||
|
||||
def test_set_status_online_sends_correct_json(self):
|
||||
"""set_status('online') sendet UserPresence:setDefaultStatus mit params=['online']."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = True
|
||||
client.sock = MagicMock()
|
||||
|
||||
with patch.object(client, "_send_json") as mock_send:
|
||||
result = client.set_status("online")
|
||||
|
||||
assert result is True
|
||||
mock_send.assert_called_once()
|
||||
call_args = mock_send.call_args[0][0]
|
||||
assert call_args["msg"] == "method"
|
||||
assert call_args["method"] == "UserPresence:setDefaultStatus"
|
||||
assert call_args["params"] == ["online"]
|
||||
assert call_args["id"].startswith("st")
|
||||
|
||||
def test_set_status_away_sends_correct_json(self):
|
||||
"""set_status('away') sendet UserPresence:setDefaultStatus mit params=['away']."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = True
|
||||
client.sock = MagicMock()
|
||||
|
||||
with patch.object(client, "_send_json") as mock_send:
|
||||
result = client.set_status("away")
|
||||
|
||||
assert result is True
|
||||
mock_send.assert_called_once()
|
||||
call_args = mock_send.call_args[0][0]
|
||||
assert call_args["msg"] == "method"
|
||||
assert call_args["method"] == "UserPresence:setDefaultStatus"
|
||||
assert call_args["params"] == ["away"]
|
||||
assert call_args["id"].startswith("st")
|
||||
|
||||
def test_set_status_busy_sends_correct_json(self):
|
||||
"""set_status('busy') sendet UserPresence:setDefaultStatus mit params=['busy']."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = True
|
||||
client.sock = MagicMock()
|
||||
|
||||
with patch.object(client, "_send_json") as mock_send:
|
||||
result = client.set_status("busy")
|
||||
|
||||
assert result is True
|
||||
mock_send.assert_called_once()
|
||||
call_args = mock_send.call_args[0][0]
|
||||
assert call_args["msg"] == "method"
|
||||
assert call_args["method"] == "UserPresence:setDefaultStatus"
|
||||
assert call_args["params"] == ["busy"]
|
||||
assert call_args["id"].startswith("st")
|
||||
|
||||
def test_set_status_disconnected_returns_false(self):
|
||||
"""set_status gibt False zurück wenn nicht connected."""
|
||||
from adapter import DDPClient
|
||||
|
||||
client = DDPClient("test.example.com")
|
||||
client.connected = False
|
||||
|
||||
result = client.set_status("online")
|
||||
assert result is False
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1092,3 +1092,142 @@ class TestCommandHandlersMocked:
|
||||
assert handler is not None
|
||||
result = await handler("room1", "")
|
||||
assert "hermes update" in result
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1-4: Status-Farben in ::hilfe und ::status
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestHelpTextPresenceColors:
|
||||
"""P1-4: build_help_text zeigt Status-Farben-Sektion wenn presence_enabled."""
|
||||
|
||||
def test_help_text_includes_status_colors_when_presence_enabled(self):
|
||||
"""presence_enabled=True → 'Status-Farben' Sektion erscheint."""
|
||||
from archivar.inline_commands import InlineCommandRegistry, build_help_text
|
||||
|
||||
registry = InlineCommandRegistry()
|
||||
text = build_help_text(registry, presence_enabled=True, current_status="online")
|
||||
|
||||
assert "Status-Farben" in text, (
|
||||
f"Status-Farben Sektion fehlt:\n{text}"
|
||||
)
|
||||
assert "online" in text
|
||||
assert "away" in text
|
||||
assert "busy" in text
|
||||
# Flughafen-Prinzip erklärt
|
||||
assert "flughafen" in text.lower() or "ampel" in text.lower(), (
|
||||
f"Flughafen-Prinzip nicht erklärt:\n{text}"
|
||||
)
|
||||
|
||||
def test_help_text_no_status_colors_when_presence_disabled(self):
|
||||
"""presence_enabled=False → keine Status-Farben Sektion."""
|
||||
from archivar.inline_commands import InlineCommandRegistry, build_help_text
|
||||
|
||||
registry = InlineCommandRegistry()
|
||||
text = build_help_text(registry, presence_enabled=False)
|
||||
|
||||
assert "Status-Farben" not in text, (
|
||||
f"Status-Farben Sektion sollte nicht erscheinen:\n{text}"
|
||||
)
|
||||
|
||||
def test_help_text_no_status_colors_when_presence_none(self):
|
||||
"""presence_enabled=None (default) → keine Status-Farben Sektion."""
|
||||
from archivar.inline_commands import InlineCommandRegistry, build_help_text
|
||||
|
||||
registry = InlineCommandRegistry()
|
||||
text = build_help_text(registry)
|
||||
|
||||
assert "Status-Farben" not in text
|
||||
|
||||
|
||||
class TestStatusTextPresenceInfo:
|
||||
"""P1-4: build_status_text zeigt PresenceEngine-Info wenn presence_enabled."""
|
||||
|
||||
def test_status_text_includes_presence_info_when_enabled(self):
|
||||
"""presence_enabled=True → PresenceEngine + Status + Pulse Zeilen."""
|
||||
from archivar.inline_commands import build_status_text
|
||||
|
||||
text = build_status_text(
|
||||
room_count=3,
|
||||
archivar_active=True,
|
||||
butler_mode="cognitive",
|
||||
presence_enabled=True,
|
||||
current_status="online",
|
||||
pulse_active=True,
|
||||
)
|
||||
|
||||
assert "PresenceEngine" in text, (
|
||||
f"PresenceEngine-Zeile fehlt:\n{text}"
|
||||
)
|
||||
assert "Aktiv" in text # ✅ Aktiv
|
||||
assert "online" in text, (
|
||||
f"Aktueller Status fehlt:\n{text}"
|
||||
)
|
||||
assert "aktiv" in text.lower(), (
|
||||
f"Pulse-Info fehlt:\n{text}"
|
||||
)
|
||||
|
||||
def test_status_text_includes_presence_info_when_disabled(self):
|
||||
"""presence_enabled=False → PresenceEngine ❌ Inaktiv."""
|
||||
from archivar.inline_commands import build_status_text
|
||||
|
||||
text = build_status_text(
|
||||
room_count=0,
|
||||
archivar_active=False,
|
||||
butler_mode="off",
|
||||
presence_enabled=False,
|
||||
current_status="online",
|
||||
pulse_active=False,
|
||||
)
|
||||
|
||||
assert "PresenceEngine" in text
|
||||
assert "Inaktiv" in text
|
||||
|
||||
def test_status_text_no_presence_info_when_default(self):
|
||||
"""presence_enabled=False (default) → keine PresenceEngine-Zeile."""
|
||||
from archivar.inline_commands import build_status_text
|
||||
|
||||
text = build_status_text(
|
||||
room_count=1,
|
||||
archivar_active=True,
|
||||
butler_mode="strict",
|
||||
)
|
||||
|
||||
assert "PresenceEngine" not in text, (
|
||||
f"PresenceEngine sollte nicht erscheinen (default):\n{text}"
|
||||
)
|
||||
|
||||
def test_status_text_shows_away_status(self):
|
||||
"""current_status='away' → 🟡 away im Status-Text."""
|
||||
from archivar.inline_commands import build_status_text
|
||||
|
||||
text = build_status_text(
|
||||
room_count=2,
|
||||
archivar_active=True,
|
||||
butler_mode="cognitive",
|
||||
presence_enabled=True,
|
||||
current_status="away",
|
||||
pulse_active=True,
|
||||
)
|
||||
|
||||
assert "away" in text, (
|
||||
f"away-Status fehlt:\n{text}"
|
||||
)
|
||||
|
||||
def test_status_text_shows_busy_status(self):
|
||||
"""current_status='busy' → 🔴 busy im Status-Text."""
|
||||
from archivar.inline_commands import build_status_text
|
||||
|
||||
text = build_status_text(
|
||||
room_count=2,
|
||||
archivar_active=True,
|
||||
butler_mode="cognitive",
|
||||
presence_enabled=True,
|
||||
current_status="busy",
|
||||
pulse_active=False,
|
||||
)
|
||||
|
||||
assert "busy" in text, (
|
||||
f"busy-Status fehlt:\n{text}"
|
||||
)
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
"""
|
||||
Tests für Reply-Quote-Stripping (P0 + P1).
|
||||
|
||||
Testet:
|
||||
- Attachments-basiertes Stripping (Stufe 1)
|
||||
- Text-basiertes Stripping (Stufe 2): [quote]-Blöcke, Markdown-Blockquotes
|
||||
- RC Reply-Link-Entfernung
|
||||
- Edge Cases: Nachrichten ohne Quote, verschachtelte Quotes, Edits
|
||||
- P1: routing_text vs display_text Trennung
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
from plugin.archivar.reply_quote_stripper import (
|
||||
strip_reply_quote,
|
||||
strip_reply_quote_for_routing,
|
||||
_extract_quoted_text_from_attachments,
|
||||
_strip_rc_reply_link,
|
||||
_strip_blockquotes,
|
||||
_strip_quote_blocks,
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Stufe 1: Attachments-basiertes Stripping
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestAttachmentBasedStripping:
|
||||
"""Tests für attachments-basiertes Quote-Stripping (Stufe 1)."""
|
||||
|
||||
def test_reply_attachment_type_reply(self):
|
||||
"""Attachment mit type='reply' wird erkannt und gestrippt."""
|
||||
text = "Meine Antwort auf deine Frage\n\nDas ist der zitierte Text von der Parent-Nachricht"
|
||||
attachments = [
|
||||
{
|
||||
"type": "reply",
|
||||
"text": "Das ist der zitierte Text von der Parent-Nachricht",
|
||||
"author_name": "bernd",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
assert "zitierte Text" not in result
|
||||
assert "Meine Antwort" in result
|
||||
|
||||
def test_reply_attachment_type_quote(self):
|
||||
"""Attachment mit type='quote' wird erkannt."""
|
||||
text = "Ja, genau!\n\nUrsprüngliche Frage: Wie funktioniert der Archivar?"
|
||||
attachments = [
|
||||
{
|
||||
"type": "quote",
|
||||
"text": "Ursprüngliche Frage: Wie funktioniert der Archivar?",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
assert "Ursprüngliche Frage" not in result
|
||||
assert "Ja, genau!" in result
|
||||
|
||||
def test_reply_attachment_with_attachment_type_field(self):
|
||||
"""Attachment mit attachment_type='reply' wird erkannt."""
|
||||
text = "Gute Idee!\n\nWir sollten den Archivar erweitern um Multi-Room-Support"
|
||||
attachments = [
|
||||
{
|
||||
"attachment_type": "reply",
|
||||
"description": "Wir sollten den Archivar erweitern um Multi-Room-Support",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
assert "Multi-Room-Support" not in result
|
||||
assert "Gute Idee!" in result
|
||||
|
||||
def test_reply_attachment_with_message_link(self):
|
||||
"""Attachment mit message_link wird als Reply-Indikator erkannt."""
|
||||
text = "Antwort\n\nOriginal: Bitte dokumentiere das neue Feature"
|
||||
attachments = [
|
||||
{
|
||||
"message_link": "https://chat.example.com/group/room?msg=abc123",
|
||||
"text": "Original: Bitte dokumentiere das neue Feature",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
assert "dokumentiere" not in result
|
||||
assert "Antwort" in result
|
||||
|
||||
def test_no_reply_attachment_no_strip(self):
|
||||
"""Normales File-Attachment löst KEIN Stripping aus."""
|
||||
text = "Schau dir mal diese Datei an"
|
||||
attachments = [
|
||||
{
|
||||
"type": "file",
|
||||
"title": "dokumentation.pdf",
|
||||
"title_link": "/file-upload/abc123/dokumentation.pdf",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is False
|
||||
assert result == text
|
||||
|
||||
def test_empty_attachments_no_strip(self):
|
||||
"""Leere Attachment-Liste → kein Strip."""
|
||||
text = "Normaler Text ohne Quote"
|
||||
result, stripped = strip_reply_quote(text, [])
|
||||
assert stripped is False
|
||||
assert result == text
|
||||
|
||||
def test_none_attachments_no_strip(self):
|
||||
"""None attachments → kein Strip."""
|
||||
text = "Normaler Text ohne Quote"
|
||||
result, stripped = strip_reply_quote(text, None)
|
||||
assert stripped is False
|
||||
assert result == text
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Stufe 1b: RC Reply-Link-Entfernung
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestRCReplyLinkStripping:
|
||||
"""Tests für Rocket.Chat Reply-Link-Entfernung."""
|
||||
|
||||
def test_strip_rc_reply_link(self):
|
||||
"""[ ](url?msg=ID) wird entfernt."""
|
||||
text = "[ ](https://chat.example.com/group/room?msg=abc123) Meine Antwort"
|
||||
result = _strip_rc_reply_link(text)
|
||||
assert "[ ](https://chat.example.com" not in result
|
||||
assert "Meine Antwort" in result
|
||||
|
||||
def test_strip_rc_reply_link_with_text_after(self):
|
||||
"""Reply-Link am Anfang, Text danach."""
|
||||
text = "[ ](https://chat.example.com/group/room?msg=abc123) Was meinst du zum Archivar?"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "Archivar" in result
|
||||
assert "msg=abc123" not in result
|
||||
|
||||
def test_no_reply_link_no_strip(self):
|
||||
"""Text ohne Reply-Link bleibt unverändert."""
|
||||
text = "Was meinst du zum Archivar?"
|
||||
result = _strip_rc_reply_link(text)
|
||||
assert result == text
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Stufe 2: Text-basiertes Stripping
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestTextBasedStripping:
|
||||
"""Tests für text-basiertes Quote-Stripping (Stufe 2)."""
|
||||
|
||||
def test_strip_quote_block(self):
|
||||
"""[quote]...[/quote] Block wird entfernt."""
|
||||
text = "Meine Antwort\n\n[quote]Das ist ein zitierter Text[/quote]"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "[quote]" not in result
|
||||
assert "zitierter Text" not in result
|
||||
assert "Meine Antwort" in result
|
||||
|
||||
def test_strip_quote_author_block(self):
|
||||
"""[quote="author"]...[/quote] Block wird entfernt."""
|
||||
text = 'Antwort\n\n[quote="bernd"]Original: Bitte dokumentiere das[/quote]'
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "dokumentiere" not in result
|
||||
assert "Antwort" in result
|
||||
|
||||
def test_strip_markdown_blockquote(self):
|
||||
"""> Markdown-Blockquote wird entfernt."""
|
||||
text = "Meine Antwort\n\n> Das ist ein zitierter Text\n> mit mehreren Zeilen"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "zitierter Text" not in result
|
||||
assert "Meine Antwort" in result
|
||||
|
||||
def test_strip_multiline_blockquote(self):
|
||||
"""Mehrzeilige > Blockquote wird komplett entfernt."""
|
||||
text = "Antwort:\n\n> Zeile 1 des Zitats\n> Zeile 2 des Zitats\n> Zeile 3 des Zitats\n\nEigener Text"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "Zeile 1" not in result
|
||||
assert "Zeile 2" not in result
|
||||
assert "Zeile 3" not in result
|
||||
assert "Antwort:" in result
|
||||
assert "Eigener Text" in result
|
||||
|
||||
def test_quote_block_with_keyword_inside(self):
|
||||
"""Quote-Block mit Keyword 'archivar' wird entfernt — verhindert Fehl-Routing."""
|
||||
text = "Frage zum Plugin\n\n[quote]Der Archivar routet Nachrichten automatisch[/quote]"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "Archivar" not in result
|
||||
assert "Frage zum Plugin" in result
|
||||
|
||||
def test_blockquote_with_keyword_inside(self):
|
||||
"""Markdown-Blockquote mit Keyword wird entfernt."""
|
||||
text = "Neue Frage\n\n> Bitte dokumentiere das Multi-Room-Feature im Archivar"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "dokumentiere" not in result
|
||||
assert "Multi-Room" not in result
|
||||
assert "Neue Frage" in result
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Edge Cases
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestEdgeCases:
|
||||
"""Edge-Case-Tests für Reply-Quote-Stripping."""
|
||||
|
||||
def test_no_quote_no_change(self):
|
||||
"""Nachricht ohne Quote bleibt unverändert."""
|
||||
text = "Kannst du mir den Archivar erklären?"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is False
|
||||
assert result == text
|
||||
|
||||
def test_empty_text(self):
|
||||
"""Leerer Text bleibt leer."""
|
||||
result, stripped = strip_reply_quote("")
|
||||
assert stripped is False
|
||||
assert result == ""
|
||||
|
||||
def test_text_with_gt_symbol_not_blockquote(self):
|
||||
"""> mitten im Text (kein Zeilenanfang) ist kein Blockquote."""
|
||||
text = "Die Bedingung ist x > 5 und y < 10"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is False
|
||||
assert "x > 5" in result
|
||||
|
||||
def test_nested_quotes_outermost_only(self):
|
||||
"""Verschachtelte Quotes: nur die äußerste wird entfernt (defensiv)."""
|
||||
text = "Antwort\n\n> Äußeres Zitat\n> > Inneres Zitat\n> Noch äußeres"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
# Der gesamte > Block wird entfernt
|
||||
assert "Äußeres Zitat" not in result
|
||||
assert "Inneres Zitat" not in result
|
||||
assert "Antwort" in result
|
||||
|
||||
def test_edit_message_no_quote(self):
|
||||
"""Edit-Nachrichten ohne Quote werden nicht verändert."""
|
||||
text = "EDIT: Korrigierte Version des Archivar-Dokuments"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is False
|
||||
assert "Archivar" in result # Keyword bleibt erhalten
|
||||
|
||||
def test_quote_block_with_attachment_priority(self):
|
||||
"""Attachments-basiertes Stripping hat Priorität vor Text-basiertem."""
|
||||
text = "Antwort\n\n> Das ist ein Blockquote\n\nZitierter Attachment-Text"
|
||||
attachments = [
|
||||
{
|
||||
"type": "reply",
|
||||
"text": "Zitierter Attachment-Text",
|
||||
}
|
||||
]
|
||||
result, stripped = strip_reply_quote(text, attachments)
|
||||
assert stripped is True
|
||||
# Attachment-Text wurde entfernt
|
||||
assert "Zitierter Attachment-Text" not in result
|
||||
# Blockquote wurde NICHT entfernt (weil Stufe 1 schon gestrippt hat)
|
||||
# Das ist okay — wir strippen nur einmal
|
||||
|
||||
def test_whitespace_only_after_strip(self):
|
||||
"""Nach Strip nur noch Whitespace → leerer String."""
|
||||
text = "[ ](https://chat.example.com/group/room?msg=abc123)"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert result == ""
|
||||
|
||||
def test_multiple_blank_lines_collapsed(self):
|
||||
"""Mehrfache Leerzeilen nach Strip werden kollabiert."""
|
||||
text = "Antwort\n\n\n\n> Zitat\n\n\n\nEigener Text"
|
||||
result, stripped = strip_reply_quote(text)
|
||||
assert stripped is True
|
||||
assert "\n\n\n\n" not in result
|
||||
assert "Antwort" in result
|
||||
assert "Eigener Text" in result
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# P1: routing_text vs display_text
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestRoutingVsDisplayText:
|
||||
"""Tests für P1: Trennung von routing_text und display_text."""
|
||||
|
||||
def test_routing_text_stripped_display_text_preserved(self):
|
||||
"""routing_text ohne Quote, display_text mit Quote."""
|
||||
text = "Meine Frage\n\n[quote]Der Archivar ist ein Routing-System[/quote]"
|
||||
routing_text, display_text, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is True
|
||||
assert "Archivar" not in routing_text # Quote gestrippt
|
||||
assert "Meine Frage" in routing_text
|
||||
assert display_text == text # Original erhalten
|
||||
assert "Archivar" in display_text # Quote im display_text
|
||||
|
||||
def test_no_quote_both_same(self):
|
||||
"""Ohne Quote sind routing_text und display_text identisch."""
|
||||
text = "Kannst du den Archivar erklären?"
|
||||
routing_text, display_text, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is False
|
||||
assert routing_text == text
|
||||
assert display_text == text
|
||||
|
||||
def test_attachment_quote_routing_stripped(self):
|
||||
"""Attachment-Quote: routing_text gestrippt, display_text erhalten."""
|
||||
text = "Ja, gute Frage!\n\nBitte dokumentiere das Multi-Room-Feature"
|
||||
attachments = [
|
||||
{
|
||||
"type": "reply",
|
||||
"text": "Bitte dokumentiere das Multi-Room-Feature",
|
||||
}
|
||||
]
|
||||
routing_text, display_text, was_stripped = strip_reply_quote_for_routing(
|
||||
text, attachments
|
||||
)
|
||||
|
||||
assert was_stripped is True
|
||||
assert "dokumentiere" not in routing_text
|
||||
assert "Ja, gute Frage!" in routing_text
|
||||
assert display_text == text
|
||||
assert "dokumentiere" in display_text
|
||||
|
||||
def test_rc_reply_link_routing_stripped(self):
|
||||
"""RC Reply-Link: routing_text ohne Link, display_text mit Link."""
|
||||
text = "[ ](https://chat.example.com/group/room?msg=abc123) Frage zum Archivar"
|
||||
routing_text, display_text, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is True
|
||||
assert "msg=abc123" not in routing_text
|
||||
assert "Frage zum Archivar" in routing_text
|
||||
assert display_text == text
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Integration: Keyword-Matcher mit gestripptem Text
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestKeywordMatcherIntegration:
|
||||
"""Integrationstest: Keyword-Matcher sieht gestrippten Text nicht."""
|
||||
|
||||
def test_keyword_in_quote_not_matched(self):
|
||||
"""Keyword NUR im Quote → kein Match nach Strip."""
|
||||
from plugin.archivar.keyword_matcher import match_keyword
|
||||
|
||||
text = "Frage zum Plugin\n\n[quote]Bitte dokumentiere das Archivar-Feature[/quote]"
|
||||
routing_text, _, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is True
|
||||
# 'dokumentiere' war nur im Quote → nach Strip kein Match
|
||||
assert not match_keyword("dokumentiere", routing_text)
|
||||
# 'archivar' war nur im Quote → nach Strip kein Match
|
||||
assert not match_keyword("archivar", routing_text)
|
||||
|
||||
def test_keyword_in_body_still_matched(self):
|
||||
"""Keyword im Body (nicht im Quote) → Match nach Strip."""
|
||||
from plugin.archivar.keyword_matcher import match_keyword
|
||||
|
||||
text = "Bitte dokumentiere das Plugin\n\n[quote]Alte Frage zum Archivar[/quote]"
|
||||
routing_text, _, was_stripped = strip_reply_quote_for_routing(text)
|
||||
|
||||
assert was_stripped is True
|
||||
# 'dokumentiere' ist im Body → Match
|
||||
assert match_keyword("dokumentiere", routing_text)
|
||||
# 'archivar' war im Quote → kein Match
|
||||
assert not match_keyword("archivar", routing_text)
|
||||
@@ -179,3 +179,274 @@ def test_room_map_summary_multiroom_disabled(mock_multiroom):
|
||||
assert summary == "", (
|
||||
f"Deaktiviertes Multiroom sollte leeren String zurückgeben, nicht:\n{summary}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# V8.6: PresenceEngine-Init-Logging (R-3 + R-4)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestPresenceEngineInitLogging:
|
||||
"""R-3: INFO-Log bei erfolgreicher PresenceEngine-Initialisierung."""
|
||||
|
||||
def test_presence_engine_init_logs_info(self):
|
||||
"""Bei erfolgreicher Init wird ein INFO-Log mit enabled/coalesce_ms geschrieben."""
|
||||
import logging
|
||||
from io import StringIO
|
||||
|
||||
log_stream = StringIO()
|
||||
handler = logging.StreamHandler(log_stream)
|
||||
handler.setLevel(logging.INFO)
|
||||
|
||||
logger = logging.getLogger("plugin.adapter")
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
try:
|
||||
# Simuliere die PresenceEngine-Init wie in adapter.py Z.805-815
|
||||
from plugin.archivar.presence_engine import PresenceEngine
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
|
||||
_presence_enabled = True
|
||||
_coalesce_ms = 2000
|
||||
|
||||
engine = PresenceEngine(
|
||||
rest=mock_rest,
|
||||
enabled=_presence_enabled,
|
||||
coalesce_ms=_coalesce_ms,
|
||||
pulse_interval=10,
|
||||
)
|
||||
|
||||
# R-3: Log-Ausgabe
|
||||
logger.info(
|
||||
"[rocketchat] V8.6: PresenceEngine initialisiert (enabled=%s, coalesce_ms=%s)",
|
||||
_presence_enabled,
|
||||
_coalesce_ms,
|
||||
)
|
||||
|
||||
log_output = log_stream.getvalue()
|
||||
assert "V8.6: PresenceEngine initialisiert" in log_output, (
|
||||
f"INFO-Log fehlt:\n{log_output}"
|
||||
)
|
||||
assert "enabled=True" in log_output, (
|
||||
f"enabled-Parameter fehlt im Log:\n{log_output}"
|
||||
)
|
||||
assert "coalesce_ms=2000" in log_output, (
|
||||
f"coalesce_ms-Parameter fehlt im Log:\n{log_output}"
|
||||
)
|
||||
finally:
|
||||
logger.removeHandler(handler)
|
||||
|
||||
|
||||
class TestPresenceEngineInitErrorHandling:
|
||||
"""R-4: try/except um die Initialisierung — graceful degradation."""
|
||||
|
||||
def test_presence_engine_init_error_logs_and_graceful_degrade(self):
|
||||
"""Bei Fehler: ERROR-Log + self._presence_engine = None."""
|
||||
import logging
|
||||
from io import StringIO
|
||||
|
||||
log_stream = StringIO()
|
||||
handler = logging.StreamHandler(log_stream)
|
||||
handler.setLevel(logging.ERROR)
|
||||
|
||||
logger = logging.getLogger("plugin.adapter")
|
||||
logger.addHandler(handler)
|
||||
logger.setLevel(logging.ERROR)
|
||||
|
||||
try:
|
||||
# Simuliere einen Fehler bei der PresenceEngine-Init
|
||||
_presence_engine = None
|
||||
try:
|
||||
raise RuntimeError("PresenceEngine-Modul nicht gefunden")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
"[rocketchat] V8.6: PresenceEngine-Initialisierung FEHLGESCHLAGEN: %s",
|
||||
e,
|
||||
)
|
||||
_presence_engine = None # Graceful degradation
|
||||
|
||||
log_output = log_stream.getvalue()
|
||||
assert "V8.6: PresenceEngine-Initialisierung FEHLGESCHLAGEN" in log_output, (
|
||||
f"ERROR-Log fehlt:\n{log_output}"
|
||||
)
|
||||
assert "PresenceEngine-Modul nicht gefunden" in log_output, (
|
||||
f"Fehlermeldung fehlt im Log:\n{log_output}"
|
||||
)
|
||||
assert _presence_engine is None, (
|
||||
"Graceful degradation: _presence_engine muss None sein"
|
||||
)
|
||||
finally:
|
||||
logger.removeHandler(handler)
|
||||
|
||||
|
||||
class TestPresenceEngineNoneGuard:
|
||||
"""P1-3: _send_onboarding_message und _complete_onboarding müssen
|
||||
ohne _presence_engine (None) keinen AttributeError werfen."""
|
||||
|
||||
def test_send_onboarding_message_without_presence_engine(self):
|
||||
"""_send_onboarding_message: ohne _presence_engine → kein Crash."""
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
# _presence_engine NICHT setzen — simuliert graceful degradation
|
||||
adapter.archivar = MagicMock()
|
||||
adapter.archivar._state = MagicMock()
|
||||
adapter.archivar._stats = {}
|
||||
adapter._room_info = {}
|
||||
adapter._onboarding_state = None
|
||||
adapter._get_build_custom_buttons = MagicMock(return_value=MagicMock())
|
||||
adapter._post_message_with_retry = AsyncMock()
|
||||
|
||||
missing_rooms = [{"room_id": "room1", "name": "#test"}]
|
||||
|
||||
with patch("plugin.adapter._MULTIROOM", return_value=True):
|
||||
try:
|
||||
asyncio.run(adapter._send_onboarding_message("op_room", missing_rooms))
|
||||
except AttributeError as e:
|
||||
pytest.fail(
|
||||
f"_send_onboarding_message crashed ohne _presence_engine: {e}"
|
||||
)
|
||||
|
||||
def test_complete_onboarding_without_presence_engine(self):
|
||||
"""_complete_onboarding: ohne _presence_engine → kein Crash."""
|
||||
import asyncio
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
# _presence_engine NICHT setzen
|
||||
adapter.archivar = MagicMock()
|
||||
adapter.archivar._stats = {}
|
||||
adapter.archivar._state = MagicMock()
|
||||
adapter._onboarding_state = {"missing_rooms": []}
|
||||
adapter._room_map_summary = ""
|
||||
|
||||
with patch("archivar.onboarding.release_onboarding_lock"):
|
||||
try:
|
||||
asyncio.run(adapter._complete_onboarding("op_room"))
|
||||
except AttributeError as e:
|
||||
pytest.fail(
|
||||
f"_complete_onboarding crashed ohne _presence_engine: {e}"
|
||||
)
|
||||
|
||||
|
||||
class TestFileBlockStripping:
|
||||
"""P2-1: _download_and_inline_files muss [FILE]-Blöcke nach
|
||||
fehlgeschlagenen Downloads aus dem Text entfernen."""
|
||||
|
||||
def test_file_blocks_stripped_after_failed_download(self):
|
||||
"""Fehlgeschlagener Download → [FILE]-Blöcke werden entfernt."""
|
||||
import asyncio
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.download_file = MagicMock(return_value=None) # Download fails
|
||||
adapter.rest = mock_rest
|
||||
|
||||
text = (
|
||||
"Hier ist eine Datei:\n"
|
||||
"[FILE] report.pdf (application/pdf)\n"
|
||||
"Download: https://chat.example.com/file-upload/abc123/report.pdf\n"
|
||||
"\n"
|
||||
"Und noch eine:\n"
|
||||
"[FILE] image.png (image/png)\n"
|
||||
"Download: https://chat.example.com/file-upload/def456/image.png\n"
|
||||
"\n"
|
||||
"Ende der Nachricht."
|
||||
)
|
||||
|
||||
result = asyncio.run(adapter._download_and_inline_files(text))
|
||||
|
||||
# [FILE]-Blöcke müssen entfernt sein
|
||||
assert "[FILE]" not in result, (
|
||||
f"[FILE]-Marker nicht entfernt:\n{result}"
|
||||
)
|
||||
assert "Download:" not in result, (
|
||||
f"Download-URL nicht entfernt:\n{result}"
|
||||
)
|
||||
# Restlicher Text muss erhalten bleiben
|
||||
assert "Hier ist eine Datei:" in result
|
||||
assert "Ende der Nachricht." in result
|
||||
|
||||
def test_file_blocks_stripped_mixed_success_failure(self):
|
||||
"""Ein erfolgreicher Download + ein Fehlschlag → nur Fail-Marker entfernt."""
|
||||
import asyncio
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
mock_rest = MagicMock()
|
||||
|
||||
# Erster Download erfolgreich, zweiter fehlgeschlagen
|
||||
call_count = [0]
|
||||
|
||||
def download_file(fid, fname):
|
||||
call_count[0] += 1
|
||||
if call_count[0] == 1:
|
||||
return "Inhalt der PDF-Datei"
|
||||
return None
|
||||
|
||||
mock_rest.download_file = download_file
|
||||
adapter.rest = mock_rest
|
||||
|
||||
text = (
|
||||
"[FILE] report.pdf (application/pdf)\n"
|
||||
"Download: https://chat.example.com/file-upload/abc123/report.pdf\n"
|
||||
"\n"
|
||||
"[FILE] missing.doc (application/msword)\n"
|
||||
"Download: https://chat.example.com/file-upload/xyz789/missing.doc\n"
|
||||
)
|
||||
|
||||
result = asyncio.run(adapter._download_and_inline_files(text))
|
||||
|
||||
# Erfolgreicher Download: Content muss da sein
|
||||
assert "[FILE CONTENT: report.pdf]" in result
|
||||
assert "Inhalt der PDF-Datei" in result
|
||||
# Fehlgeschlagener Download: [FILE]-Block muss weg sein
|
||||
assert "missing.doc" not in result, (
|
||||
f"Fehlgeschlagener [FILE]-Block nicht entfernt:\n{result}"
|
||||
)
|
||||
assert "xyz789" not in result
|
||||
|
||||
def test_file_blocks_stripped_unicode_filename(self):
|
||||
"""Unicode-Dateinamen in [FILE]-Blöcken werden korrekt gestrippt."""
|
||||
import asyncio
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.download_file = MagicMock(return_value=None)
|
||||
adapter.rest = mock_rest
|
||||
|
||||
text = (
|
||||
"Schau dir das an:\n"
|
||||
"[FILE] Überblick_2024.pdf (application/pdf)\n"
|
||||
"Download: https://chat.example.com/file-upload/abc123/Überblick_2024.pdf\n"
|
||||
"\n"
|
||||
"Und:\n"
|
||||
"[FILE] 報告書.docx (application/vnd.openxmlformats-officedocument.wordprocessingml.document)\n"
|
||||
"Download: https://chat.example.com/file-upload/def456/報告書.docx\n"
|
||||
)
|
||||
|
||||
result = asyncio.run(adapter._download_and_inline_files(text))
|
||||
|
||||
assert "[FILE]" not in result, (
|
||||
f"Unicode [FILE]-Marker nicht entfernt:\n{result}"
|
||||
)
|
||||
assert "Download:" not in result
|
||||
assert "Schau dir das an:" in result
|
||||
|
||||
@@ -0,0 +1,483 @@
|
||||
"""
|
||||
P1-2 O-2: Tests für echte await-Semantik bei DDP setDefaultStatus.
|
||||
|
||||
10 Tests:
|
||||
1-5: DDPClient.set_status_async (Future-Store, Timeout, Error, NotConnected, Leak)
|
||||
6-8: PulseController async-bridge (loop-bound, fallback, pause)
|
||||
9-10: Legacy-Pfade unverändert (on_connected, idle timer)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import concurrent.futures
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch, PropertyMock
|
||||
|
||||
import pytest
|
||||
|
||||
# Ensure the plugin package is importable
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from plugin.adapter import (
|
||||
DDPClient,
|
||||
DDPTimeout,
|
||||
DDPServerError,
|
||||
DDPNotConnected,
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Hilfsfunktionen
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
def _make_ddp_client(connected: bool = True) -> DDPClient:
|
||||
"""Erzeugt einen DDPClient mit Mock-Socket für Tests."""
|
||||
client = DDPClient.__new__(DDPClient)
|
||||
client.host = "test.example.com"
|
||||
client._on_message = None
|
||||
client._on_connected = None
|
||||
client._on_room_event = None
|
||||
client.sock = None
|
||||
client.connected = connected
|
||||
client._running = False
|
||||
client._reader_thread = None
|
||||
client._write_lock = threading.Lock()
|
||||
client._msg_queue = MagicMock()
|
||||
client._next_sub_id = 1
|
||||
client._sub_rooms = {}
|
||||
client._session = None
|
||||
client._reconnect_attempt = 0
|
||||
client._last_rx_time = 0.0
|
||||
# P1-2 O-2 fields
|
||||
client._pending_results = {}
|
||||
client._loop = None
|
||||
client._result_lock = threading.Lock()
|
||||
client._msg_seq = 0
|
||||
return client
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 1: set_status_async resolves on result message
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestSetStatusAsyncResolvesOnResult:
|
||||
"""Test 1: Reader schickt result → Future wird True."""
|
||||
|
||||
def test_set_status_async_resolves_on_result_message(self):
|
||||
"""Simuliere: set_status_async sendet, Reader löst Future auf."""
|
||||
client = _make_ddp_client(connected=True)
|
||||
client._send_json = MagicMock() # Mock send
|
||||
|
||||
# Starte einen asyncio-Loop im Hintergrund
|
||||
async def _run():
|
||||
# Rufe set_status_async auf
|
||||
task = asyncio.create_task(client.set_status_async("online", timeout=5.0))
|
||||
|
||||
# Warte kurz, dass die msg_id registriert wird
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
# Simuliere: Reader-Thread empfängt result
|
||||
msg_id = None
|
||||
with client._result_lock:
|
||||
for mid in list(client._pending_results.keys()):
|
||||
msg_id = mid
|
||||
break
|
||||
|
||||
assert msg_id is not None, "msg_id sollte in _pending_results registriert sein"
|
||||
|
||||
# Reader löst Future auf (simuliert _handle_result_message)
|
||||
client._handle_result_message({
|
||||
"msg": "result",
|
||||
"id": msg_id,
|
||||
"result": True,
|
||||
})
|
||||
|
||||
# Warte auf Task
|
||||
result = await asyncio.wait_for(task, timeout=2.0)
|
||||
assert result is True
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
def test_set_status_async_sends_correct_frame(self):
|
||||
"""set_status_async sendet korrektes DDP-Frame."""
|
||||
client = _make_ddp_client(connected=True)
|
||||
sent_frames = []
|
||||
client._send_json = lambda obj: sent_frames.append(obj)
|
||||
|
||||
async def _run():
|
||||
# Starte set_status_async
|
||||
task = asyncio.create_task(client.set_status_async("away", timeout=5.0))
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
# Finde die msg_id aus dem gesendeten Frame
|
||||
assert len(sent_frames) == 1
|
||||
frame = sent_frames[0]
|
||||
assert frame["msg"] == "method"
|
||||
assert frame["method"] == "UserPresence:setDefaultStatus"
|
||||
assert frame["params"] == ["away"]
|
||||
assert frame["id"].startswith("st")
|
||||
msg_id = frame["id"]
|
||||
|
||||
# Simuliere result vom Server
|
||||
client._handle_result_message({
|
||||
"msg": "result",
|
||||
"id": msg_id,
|
||||
"result": True,
|
||||
})
|
||||
|
||||
result = await asyncio.wait_for(task, timeout=2.0)
|
||||
assert result is True
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 2: set_status_async times out without result
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestSetStatusAsyncTimeout:
|
||||
"""Test 2: kein result → DDPTimeout nach timeout."""
|
||||
|
||||
def test_set_status_async_times_out_without_result(self):
|
||||
"""Wenn kein result kommt, wird DDPTimeout geworfen."""
|
||||
client = _make_ddp_client(connected=True)
|
||||
client._send_json = MagicMock()
|
||||
|
||||
async def _run():
|
||||
with pytest.raises(DDPTimeout) as exc_info:
|
||||
await client.set_status_async("online", timeout=0.1)
|
||||
assert "timed out" in str(exc_info.value).lower()
|
||||
|
||||
# Future sollte aus _pending_results entfernt sein
|
||||
with client._result_lock:
|
||||
assert len(client._pending_results) == 0
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 3: set_status_async raises on server error
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestSetStatusAsyncServerError:
|
||||
"""Test 3: error-Feld → DDPServerError."""
|
||||
|
||||
def test_set_status_async_raises_on_server_error(self):
|
||||
"""Server schickt error → DDPServerError wird geworfen."""
|
||||
client = _make_ddp_client(connected=True)
|
||||
client._send_json = MagicMock()
|
||||
|
||||
async def _run():
|
||||
task = asyncio.create_task(client.set_status_async("busy", timeout=5.0))
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
# Finde msg_id
|
||||
msg_id = None
|
||||
with client._result_lock:
|
||||
for mid in list(client._pending_results.keys()):
|
||||
msg_id = mid
|
||||
break
|
||||
|
||||
assert msg_id is not None
|
||||
|
||||
# Simuliere Server-Error
|
||||
client._handle_result_message({
|
||||
"msg": "result",
|
||||
"id": msg_id,
|
||||
"error": {"error": "status not allowed"},
|
||||
})
|
||||
|
||||
with pytest.raises(DDPServerError) as exc_info:
|
||||
await asyncio.wait_for(task, timeout=2.0)
|
||||
assert "status not allowed" in str(exc_info.value)
|
||||
|
||||
# Future sollte aus Store entfernt sein
|
||||
with client._result_lock:
|
||||
assert msg_id not in client._pending_results
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 4: set_status_async not connected raises
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestSetStatusAsyncNotConnected:
|
||||
"""Test 4: DDPNotConnected wenn nicht connected."""
|
||||
|
||||
def test_set_status_async_not_connected_raises(self):
|
||||
"""Nicht connected → DDPNotConnected."""
|
||||
client = _make_ddp_client(connected=False)
|
||||
|
||||
async def _run():
|
||||
with pytest.raises(DDPNotConnected):
|
||||
await client.set_status_async("online")
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 5: _pending_results store does not leak
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestPendingResultsNoLeak:
|
||||
"""Test 5: 100 parallel, 50 ohne result → Sweep räumt auf."""
|
||||
|
||||
def test_pending_results_store_does_not_leak(self):
|
||||
"""Sweep entfernt stale Futures (>2s alt)."""
|
||||
client = _make_ddp_client(connected=True)
|
||||
client._send_json = MagicMock()
|
||||
|
||||
# Registriere 50 "alte" Futures (Timestamp vor 3s)
|
||||
old_ts = int((time.time() - 3.0) * 1000)
|
||||
for i in range(50):
|
||||
msg_id = f"st{old_ts}_{i}"
|
||||
future = concurrent.futures.Future()
|
||||
with client._result_lock:
|
||||
client._pending_results[msg_id] = future
|
||||
|
||||
# Registriere 50 "frische" Futures (Timestamp jetzt)
|
||||
fresh_ts = int(time.time() * 1000)
|
||||
for i in range(50, 100):
|
||||
msg_id = f"st{fresh_ts}_{i}"
|
||||
future = concurrent.futures.Future()
|
||||
with client._result_lock:
|
||||
client._pending_results[msg_id] = future
|
||||
|
||||
assert len(client._pending_results) == 100
|
||||
|
||||
# Sweep ausführen
|
||||
client._sweep_pending_results()
|
||||
|
||||
# Nur die 50 frischen sollten übrig sein
|
||||
remaining = len(client._pending_results)
|
||||
assert remaining == 50, (
|
||||
f"Erwartet 50 verbleibende Futures, bekam {remaining}"
|
||||
)
|
||||
|
||||
# Alle verbleibenden sollten frische msg_ids haben
|
||||
for msg_id in client._pending_results:
|
||||
ts_part = msg_id[2:].split("_")[0]
|
||||
ts_ms = int(ts_part)
|
||||
assert ts_ms >= fresh_ts, (
|
||||
f"Alte msg_id {msg_id} wurde nicht gesweept"
|
||||
)
|
||||
|
||||
def test_sweep_handles_malformed_msg_ids(self):
|
||||
"""Sweep entfernt auch Futures mit kaputten msg_ids."""
|
||||
client = _make_ddp_client(connected=True)
|
||||
|
||||
# Registriere Future mit kaputter msg_id
|
||||
future = concurrent.futures.Future()
|
||||
with client._result_lock:
|
||||
client._pending_results["kaputt"] = future
|
||||
|
||||
client._sweep_pending_results()
|
||||
|
||||
assert len(client._pending_results) == 0
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 6: PulseController uses async when loop bound
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestPulseControllerAsyncWhenLoopBound:
|
||||
"""Test 6: set_status_async aufgerufen, set_status 0x wenn Loop gebunden."""
|
||||
|
||||
def test_pulse_controller_uses_async_when_loop_bound(self):
|
||||
"""Mit gebundenem Loop → _pulse_tick_async wird aufgerufen."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock()
|
||||
# set_status_async muss eine echte Coroutine sein
|
||||
async def _mock_set_status_async(status, timeout=2.0):
|
||||
return True
|
||||
mock_ddp.set_status_async = _mock_set_status_async
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
async def _run():
|
||||
loop = asyncio.get_running_loop()
|
||||
pc.bind_loop(loop)
|
||||
await pc._pulse_tick_async()
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
# set_status (sync) sollte NICHT aufgerufen worden sein
|
||||
mock_ddp.set_status.assert_not_called()
|
||||
|
||||
def test_pulse_controller_async_falls_back_to_rest(self):
|
||||
"""Wenn set_status_async fehlschlägt → REST-Fallback."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
async def _mock_set_status_async_raises(status, timeout=2.0):
|
||||
raise DDPTimeout("timeout")
|
||||
mock_ddp.set_status_async = _mock_set_status_async_raises
|
||||
mock_rest = MagicMock()
|
||||
mock_rest.auth_token = "token"
|
||||
mock_rest.user_id = "user123"
|
||||
mock_rest._request = MagicMock(return_value={"success": True})
|
||||
pc.bind_ddp(mock_ddp)
|
||||
pc.bind_rest(mock_rest)
|
||||
|
||||
async def _run():
|
||||
loop = asyncio.get_running_loop()
|
||||
pc.bind_loop(loop)
|
||||
await pc._pulse_tick_async()
|
||||
|
||||
asyncio.run(_run())
|
||||
|
||||
# REST sollte als Fallback aufgerufen worden sein
|
||||
mock_rest._request.assert_called_once()
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 7: PulseController fallback to sync when no loop
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestPulseControllerFallbackToSync:
|
||||
"""Test 7: set_status (sync) aufgerufen wenn kein Loop gebunden."""
|
||||
|
||||
def test_pulse_controller_fallback_to_sync_when_no_loop(self):
|
||||
"""Ohne Loop → legacy sync-Pfad mit set_status."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(return_value=True)
|
||||
mock_ddp.set_status_async = MagicMock()
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# KEIN Loop gebunden → _pulse_tick nutzt sync-Pfad
|
||||
pc._pulse_tick()
|
||||
|
||||
# set_status (sync) sollte aufgerufen worden sein
|
||||
mock_ddp.set_status.assert_called_once()
|
||||
# set_status_async sollte NICHT aufgerufen worden sein
|
||||
mock_ddp.set_status_async.assert_not_called()
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 8: PulseController pause still works in async mode
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestPulseControllerPauseInAsyncMode:
|
||||
"""Test 8: pause stoppt async-Pfad."""
|
||||
|
||||
def test_pulse_controller_pause_still_works_in_async_mode(self):
|
||||
"""Pausierter PulseController führt keinen Tick aus."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(return_value=True)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# Pausieren
|
||||
pc.pause()
|
||||
assert pc._paused.is_set()
|
||||
|
||||
# _pulse_tick sollte wegen Pause nichts tun
|
||||
# (die Pause-Prüfung ist in _pulse_loop, nicht in _pulse_tick)
|
||||
# _pulse_tick selbst prüft nur cancel_pending
|
||||
# Also: _pulse_tick wird trotz Pause ausgeführt, wenn direkt aufgerufen
|
||||
# Das ist korrekt — die Pause greift in _pulse_loop
|
||||
pc._pulse_tick()
|
||||
# set_status wird aufgerufen (weil _pulse_tick Pause nicht prüft)
|
||||
# Das ist das erwartete Verhalten: _pulse_loop ist für Pause zuständig
|
||||
|
||||
# Resume
|
||||
pc.resume()
|
||||
assert not pc._paused.is_set()
|
||||
|
||||
def test_pulse_controller_cancel_pending_skips_tick(self):
|
||||
"""cancel_pending Flag überspringt nächsten Tick."""
|
||||
from plugin.archivar.presence_engine import PulseController
|
||||
|
||||
pc = PulseController(pulse_interval=0.05, _clamp_pulse=False)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.connected = True
|
||||
mock_ddp.set_status = MagicMock(return_value=True)
|
||||
pc.bind_ddp(mock_ddp)
|
||||
|
||||
# Setze cancel_pending
|
||||
pc.cancel_pending()
|
||||
assert pc._cancel_pending is True
|
||||
|
||||
# _pulse_tick sollte übersprungen werden
|
||||
pc._pulse_tick()
|
||||
|
||||
# set_status sollte NICHT aufgerufen worden sein
|
||||
mock_ddp.set_status.assert_not_called()
|
||||
# cancel_pending sollte zurückgesetzt sein
|
||||
assert pc._cancel_pending is False
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 9: on_connected set_status remains sync
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestOnConnectedSetStatusRemainsSync:
|
||||
"""Test 9: Legacy-Pfad _on_ddp_connected nutzt set_status (sync)."""
|
||||
|
||||
def test_on_connected_set_status_remains_sync(self):
|
||||
"""_on_ddp_connected ruft ddp.set_status('online') auf (sync)."""
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.set_status = MagicMock(return_value=True)
|
||||
adapter.ddp = mock_ddp
|
||||
adapter._presence_engine = None # Kein PresenceEngine
|
||||
|
||||
# Rufe _on_ddp_connected auf
|
||||
adapter._on_ddp_connected()
|
||||
|
||||
# set_status (sync) sollte aufgerufen worden sein
|
||||
mock_ddp.set_status.assert_called_once_with("online")
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 10: Legacy timer set_status remains sync
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class TestLegacyTimerSetStatusRemainsSync:
|
||||
"""Test 10: _schedule_idle_timer nutzt set_status (sync)."""
|
||||
|
||||
def test_legacy_timer_set_status_remains_sync(self):
|
||||
"""Idle-Timer ruft ddp.set_status('away') auf (sync)."""
|
||||
from plugin.adapter import RocketChatAdapter
|
||||
|
||||
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
|
||||
mock_ddp = MagicMock()
|
||||
mock_ddp.set_status = MagicMock(return_value=True)
|
||||
adapter.ddp = mock_ddp
|
||||
# Kein _presence_engine → idle timer wird aktiv
|
||||
adapter._presence_engine = None
|
||||
adapter._status_timer = None
|
||||
|
||||
# Rufe _schedule_idle_timer auf
|
||||
adapter._schedule_idle_timer()
|
||||
|
||||
# Timer sollte gestartet sein
|
||||
assert adapter._status_timer is not None
|
||||
|
||||
# Führe die Timer-Callback manuell aus
|
||||
# (die innere _set_away-Funktion)
|
||||
adapter._status_timer.cancel()
|
||||
# Simuliere: Timer feuert
|
||||
if adapter.ddp:
|
||||
adapter.ddp.set_status("away")
|
||||
|
||||
mock_ddp.set_status.assert_called_with("away")
|
||||
@@ -0,0 +1,363 @@
|
||||
"""
|
||||
V8.6: install.sh --update-only Tests (TDD: RED first).
|
||||
|
||||
Testet die neuen --update-only Features:
|
||||
1. __pycache__-Löschung VOR dem Kopieren
|
||||
2. __pycache__-Löschung NACH dem Kopieren
|
||||
3. systemctl --user restart hermes-gateway
|
||||
4. Post-Deployment-Verifikation (journalctl)
|
||||
5. Idempotenz
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Hilfsfunktionen
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
INSTALL_SH = Path(__file__).resolve().parents[1] / "install.sh"
|
||||
|
||||
|
||||
def _read_install_sh() -> str:
|
||||
"""Liest install.sh komplett ein."""
|
||||
return INSTALL_SH.read_text()
|
||||
|
||||
|
||||
def _extract_update_only_section(content: str) -> str:
|
||||
"""Extrahiert den --update-only Block aus install.sh."""
|
||||
# Der Block beginnt bei 'if $UPDATE_ONLY; then' und endet bei 'fi' vor dem Hauptfluss
|
||||
match = re.search(
|
||||
r'if \$UPDATE_ONLY; then.*?(?=\nfi\n\n# 1\. System-Dependencies|\nfi\n\nexit 0)',
|
||||
content,
|
||||
re.DOTALL,
|
||||
)
|
||||
if match:
|
||||
return match.group(0)
|
||||
return ""
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 1: Syntax-Check
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestInstallShSyntax:
|
||||
"""install.sh muss bash -n bestehen."""
|
||||
|
||||
def test_bash_syntax_ok(self):
|
||||
"""bash -n findet keine Syntax-Fehler."""
|
||||
if not INSTALL_SH.exists():
|
||||
pytest.skip("install.sh nicht gefunden")
|
||||
result = subprocess.run(
|
||||
["bash", "-n", str(INSTALL_SH)],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
assert result.returncode == 0, (
|
||||
f"bash -n failed:\n{result.stderr}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 2: __pycache__-Löschung VOR dem Kopieren
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestUpdateOnlyCacheCleanupBefore:
|
||||
"""__pycache__ muss VOR dem Kopieren gelöscht werden."""
|
||||
|
||||
def test_find_pycache_delete_before_copy(self):
|
||||
"""Der find-Befehl für __pycache__ erscheint VOR dem Kopier-Befehl."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# Suche nach __pycache__-Löschung
|
||||
assert "find" in update_section, (
|
||||
f"Kein find-Befehl im --update-only Block:\n{update_section}"
|
||||
)
|
||||
assert "__pycache__" in update_section, (
|
||||
f"Kein __pycache__-Bezug im --update-only Block:\n{update_section}"
|
||||
)
|
||||
|
||||
# Die erste __pycache__-Löschung muss VOR deploy_plugin kommen
|
||||
first_pycache_pos = update_section.find("__pycache__")
|
||||
deploy_pos = update_section.find("deploy_plugin")
|
||||
assert first_pycache_pos < deploy_pos, (
|
||||
f"__pycache__-Löschung ({first_pycache_pos}) muss VOR deploy_plugin ({deploy_pos}) kommen"
|
||||
)
|
||||
|
||||
def test_pycache_delete_uses_rm_rf(self):
|
||||
"""__pycache__-Löschung nutzt rm -rf."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# Mindestens ein find ... -exec rm -rf ... für __pycache__
|
||||
assert re.search(
|
||||
r"find.*__pycache__.*rm\s+-rf",
|
||||
update_section,
|
||||
), (
|
||||
f"Kein 'find ... __pycache__ ... rm -rf' gefunden:\n{update_section}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 3: __pycache__-Löschung NACH dem Kopieren
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestUpdateOnlyCacheCleanupAfter:
|
||||
"""__pycache__ muss NACH dem Kopieren NOCHMAL gelöscht werden."""
|
||||
|
||||
def test_second_pycache_delete_after_copy(self):
|
||||
"""Zweite __pycache__-Löschung erscheint NACH deploy_plugin."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# deploy_plugin-Position
|
||||
deploy_pos = update_section.find("deploy_plugin")
|
||||
|
||||
# Zweites __pycache__-Vorkommen NACH deploy_plugin
|
||||
after_deploy = update_section[deploy_pos:]
|
||||
assert "__pycache__" in after_deploy, (
|
||||
f"Keine __pycache__-Löschung NACH deploy_plugin:\n{after_deploy}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 4: systemctl --user restart hermes-gateway
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestUpdateOnlyServiceRestart:
|
||||
"""Gateway-Dienst muss nach dem Update neu gestartet werden."""
|
||||
|
||||
def test_systemctl_restart_present(self):
|
||||
"""systemctl --user restart hermes-gateway ist im --update-only Block."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "systemctl --user restart hermes-gateway" in update_section, (
|
||||
f"systemctl restart fehlt im --update-only Block:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_no_restart_flag_respected(self):
|
||||
"""--no-restart Flag überspringt den Neustart."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# --no-restart muss im Block behandelt werden
|
||||
assert "NO_RESTART" in update_section, (
|
||||
f"NO_RESTART-Flag wird nicht im --update-only Block behandelt:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_restart_after_deploy(self):
|
||||
"""systemctl restart kommt NACH deploy_plugin."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
deploy_pos = update_section.find("deploy_plugin")
|
||||
restart_pos = update_section.find("systemctl --user restart hermes-gateway")
|
||||
|
||||
assert restart_pos > deploy_pos, (
|
||||
f"restart ({restart_pos}) muss NACH deploy_plugin ({deploy_pos}) kommen"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 5: Post-Deployment-Verifikation
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestUpdateOnlyPostDeployVerification:
|
||||
"""Nach dem Deployment muss das Log verifiziert werden."""
|
||||
|
||||
def test_journalctl_presence_check(self):
|
||||
"""journalctl prüft auf 'PresenceEngine' oder 'presence'."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# Muss journalctl mit PresenceEngine/presence-Suche enthalten
|
||||
assert "journalctl" in update_section, (
|
||||
f"journalctl fehlt im --update-only Block:\n{update_section}"
|
||||
)
|
||||
assert re.search(
|
||||
r"[Pp]resence(?:Engine)?",
|
||||
update_section,
|
||||
), (
|
||||
f"Keine PresenceEngine/presence-Prüfung im --update-only Block:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_journalctl_archivar_check(self):
|
||||
"""journalctl prüft auf 'Archivar initialisiert'."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "Archivar initialisiert" in update_section, (
|
||||
f"'Archivar initialisiert'-Check fehlt im --update-only Block:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_journalctl_connected_check(self):
|
||||
"""journalctl prüft auf 'Connected to'."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "Connected to" in update_section, (
|
||||
f"'Connected to'-Check fehlt im --update-only Block:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_verification_errors_are_fatal(self):
|
||||
"""Fehlende Log-Einträge führen zu ERROR (nicht stillschweigend)."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# Muss err() oder die() oder exit 1 bei Fehlern enthalten
|
||||
assert re.search(
|
||||
r'(err|die|exit\s+1)',
|
||||
update_section,
|
||||
), (
|
||||
f"Keine Fehlerbehandlung (err/die/exit 1) bei Verifikation:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_retry_loop_present(self):
|
||||
"""Verifikation nutzt Retry-Schleife mit bis zu 3 Versuchen."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "_check_attempt" in update_section, (
|
||||
f"Keine _check_attempt Variable (Retry-Schleife) im --update-only Block:\n{update_section}"
|
||||
)
|
||||
assert "for _check_attempt in 1 2 3" in update_section, (
|
||||
f"Keine 'for _check_attempt in 1 2 3' Schleife:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_precise_timestamp(self):
|
||||
"""journalctl nutzt präzisen Zeitstempel statt '2 minutes ago'."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "_verify_since" in update_section, (
|
||||
f"Keine _verify_since Variable (präziser Zeitstempel):\n{update_section}"
|
||||
)
|
||||
assert "date '+%Y-%m-%d %H:%M:%S'" in update_section, (
|
||||
f"Kein date-Aufruf für präzisen Zeitstempel:\n{update_section}"
|
||||
)
|
||||
# Darf KEIN '2 minutes ago' mehr enthalten
|
||||
assert "2 minutes ago" not in update_section, (
|
||||
f"'2 minutes ago' noch im --update-only Block (sollte durch _verify_since ersetzt sein):\n{update_section}"
|
||||
)
|
||||
|
||||
def test_no_pager_flag(self):
|
||||
"""journalctl nutzt --no-pager für zuverlässige Ausgabe."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "--no-pager" in update_section, (
|
||||
f"Kein --no-pager Flag bei journalctl:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_sleep_12_seconds(self):
|
||||
"""Initialer Sleep ist 12s (nicht 8s)."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "sleep 12" in update_section, (
|
||||
f"Kein 'sleep 12' im --update-only Block:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_hit_count_output(self):
|
||||
"""Jede Prüfung gibt Treffer-Anzahl aus (nicht nur 'NICHT gefunden')."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# Mindestens 3 Treffer-Ausgaben (eine pro Check)
|
||||
assert update_section.count("Treffer") >= 3, (
|
||||
f"Weniger als 3 'Treffer'-Ausgaben (sollte pro Check eine sein):\n{update_section}"
|
||||
)
|
||||
|
||||
def test_retry_wait_message(self):
|
||||
"""Zwischen Retry-Versuchen wird 'Warte 5s' ausgegeben."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
assert "Warte 5s" in update_section, (
|
||||
f"Keine 'Warte 5s'-Meldung zwischen Retry-Versuchen:\n{update_section}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 6: Idempotenz
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestUpdateOnlyIdempotency:
|
||||
"""--update-only muss mehrfach ohne Side-Effects ausführbar sein."""
|
||||
|
||||
def test_no_state_mutation_outside_plugin_dir(self):
|
||||
"""--update-only ändert NUR das Plugin-Verzeichnis + Gateway-Status."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# Darf KEINE config.yaml, .env, room-map.json, SOUL.md schreiben
|
||||
forbidden = ["config.yaml", ".env", "room-map.json", "SOUL.md"]
|
||||
for pattern in forbidden:
|
||||
assert pattern not in update_section, (
|
||||
f"--update-only darf '{pattern}' nicht anfassen:\n{update_section}"
|
||||
)
|
||||
|
||||
def test_git_pull_before_deploy(self):
|
||||
"""git pull kommt VOR deploy_plugin."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
git_pull_pos = update_section.find("git pull")
|
||||
deploy_pos = update_section.find("deploy_plugin")
|
||||
|
||||
assert git_pull_pos < deploy_pos, (
|
||||
f"git pull ({git_pull_pos}) muss VOR deploy_plugin ({deploy_pos}) kommen"
|
||||
)
|
||||
|
||||
def test_dry_run_supported(self):
|
||||
"""--update-only respektiert --dry-run."""
|
||||
content = _read_install_sh()
|
||||
update_section = _extract_update_only_section(content)
|
||||
|
||||
# DRY_RUN muss im Block referenziert werden
|
||||
assert "DRY_RUN" in update_section or "$DRY_RUN" in update_section, (
|
||||
f"DRY_RUN wird nicht im --update-only Block behandelt:\n{update_section}"
|
||||
)
|
||||
|
||||
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
# Test 7: deploy_plugin hat bereits __pycache__-Cleanup (bestehend)
|
||||
# ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
class TestDeployPluginCacheCleanup:
|
||||
"""deploy_plugin() muss ebenfalls __pycache__ bereinigen."""
|
||||
|
||||
def test_deploy_plugin_has_pycache_cleanup(self):
|
||||
"""deploy_plugin() enthält __pycache__-Löschung."""
|
||||
content = _read_install_sh()
|
||||
|
||||
# Extrahiere deploy_plugin()-Funktion
|
||||
match = re.search(
|
||||
r'deploy_plugin\(\)\s*\{.*?(?=\n\}\n\n#)',
|
||||
content,
|
||||
re.DOTALL,
|
||||
)
|
||||
assert match, "deploy_plugin()-Funktion nicht gefunden"
|
||||
|
||||
func_body = match.group(0)
|
||||
assert "__pycache__" in func_body, (
|
||||
f"deploy_plugin() enthält keine __pycache__-Bereinigung:\n{func_body[:500]}"
|
||||
)
|
||||
assert "rm -rf" in func_body, (
|
||||
f"deploy_plugin() nutzt kein rm -rf für __pycache__:\n{func_body[:500]}"
|
||||
)
|
||||
Reference in New Issue
Block a user