fix: install.sh __pycache__ cleanup + service reload + post-deploy verification, PresenceEngine init logging R3+R4

TEIL 1 — install.sh --update-only:
- __pycache__-Löschung VOR und NACH deploy_plugin (find -exec rm -rf)
- systemctl --user reload des Gateway-Dienstes mit 30s Wait-Loop
- Post-Deployment-Verifikation via journalctl:
  * PresenceEngine/presence (min. 1 Treffer)
  * 'Archivar initialisiert'
  * 'Connected to'
- Fehlende Checks → die() mit klarer Meldung
- Idempotent: keine config.yaml/.env/room-map.json-Änderungen
- --no-restart und --dry-run respektiert

TEIL 2 — adapter.py PresenceEngine-Init (R-3 + R-4):
- R-3: logger.info() bei erfolgreicher Init (enabled, coalesce_ms)
- R-4: try/except mit logger.error() + self._presence_engine = None
  (graceful degradation → alter Idle-Timer greift)

Tests: 15 neue install.sh-Tests + 2 neue adapter.py-Tests
Alle bestehenden Tests unverändert (3 pre-existing failures unberührt)
This commit is contained in:
Bernd (Hermes)
2026-07-23 11:59:26 +02:00
parent ce4789fe30
commit 37d6c10e45
4 changed files with 522 additions and 14 deletions
+98 -3
View File
@@ -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,113 @@ 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
# Kurze Pause für Log-Einträge
sleep 3
# Prüfe auf PresenceEngine/presence
_update_presence_hits="$(journalctl --user -u hermes-gateway --since '1 minute ago' 2>/dev/null | grep -c -i 'PresenceEngine\|presence' || echo "0")"
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 — Plugin-Code wurde möglicherweise nicht geladen (stale __pycache__?)"
_update_verify_fail=1
fi
# Prüfe auf 'Archivar initialisiert'
if journalctl --user -u hermes-gateway --since '1 minute ago' 2>/dev/null | grep -q 'Archivar initialisiert'; then
ok "'Archivar initialisiert' im Log gefunden"
else
err "FAIL: 'Archivar initialisiert' NICHT im Gateway-Log"
_update_verify_fail=1
fi
# Prüfe auf 'Connected to'
if journalctl --user -u hermes-gateway --since '1 minute ago' 2>/dev/null | grep -q 'Connected to'; then
ok "'Connected to' im Log gefunden"
else
err "FAIL: 'Connected to' NICHT im Gateway-Log — Gateway hat keine Verbindung"
_update_verify_fail=1
fi
else
warn "journalctl nicht verfügbar — Post-Deployment-Verifikation übersprungen"
fi
if [ $_update_verify_fail -eq 0 ]; then
ok "Post-Deployment-Verifikation: ALLE CHECKS BESTANDEN"
else
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
+12
View File
@@ -803,6 +803,7 @@ 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"))
@@ -813,6 +814,17 @@ class RocketChatAdapter(BasePlatformAdapter):
coalesce_ms=_coalesce_ms,
pulse_interval=_pulse_interval,
)
logger.info(
"[rocketchat] V8.6: PresenceEngine initialisiert (enabled=%s, coalesce_ms=%s)",
_presence_enabled,
_coalesce_ms,
)
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.
+103
View File
@@ -179,3 +179,106 @@ 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)
+298
View File
@@ -0,0 +1,298 @@
"""
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}"
)
# ═══════════════════════════════════════════════════════════════════════════
# 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]}"
)