feat(F071,F068,F070): Welle 2 — Refactor-Audit, Stabilitaets-Monitor, Contract-Test-Framework @implements: [F-071] [F-068] [F-070]

This commit is contained in:
Bernd (Hermes)
2026-09-17 17:40:10 +02:00
parent df8be1c0d7
commit 31ca0f2533
13 changed files with 1527 additions and 0 deletions
+313
View File
@@ -0,0 +1,313 @@
"""F070 — Vertrags-Test-Framework Plugin ↔ Hermes-Core.
Stellt sicher, dass das Rocket.Chat-Plugin die Core-API korrekt nutzt.
Testet den VERTRAG zwischen Plugin und Hermes-Core:
1. Plugin lädt korrekt (importierbar, register(ctx) vorhanden)
2. Plugin registriert die Plattform via ctx.register_platform
3. Alle vom Plugin beanspruchten Hooks sind in Core-VALID_HOOKS registriert
(Kontrakt: kein toter Hook — P-032/P-064-Klasse)
4. Core-API-Aufrufe (send_message, get_room_info, register_command) sind
über die Adapter-/Core-Schnittstelle erreichbar
5. Commands sind per InlineCommandRegistry registriert
Zwei Einstiegspunkte:
- pytest: python3 -m pytest tests/contract/test_contract_framework.py
- Runner: python3 tests/contract/test_contract_framework.py (Standalone-CLI)
Der Kern ist run_contract_checks() → {"checked", "passed", "failed": [...]}.
Der CLI-Runner scripts/run_contract_tests.sh ruft pytest auf diesem Modul auf.
@implements: [F-070]
"""
from __future__ import annotations
import ast
import importlib
import inspect
import logging
import re
import sys
from pathlib import Path
from typing import Dict, List, Optional
import pytest
logger = logging.getLogger(__name__)
# ── Pfade ──────────────────────────────────────────────────────────────────
_REPO_ROOT = Path(__file__).resolve().parent.parent.parent # tests/contract/ -> Repo-Root
_PLUGIN_DIR = _REPO_ROOT / "plugin"
def _ensure_plugin_importable() -> None:
"""Plugin-Paket importierbar machen.
Das Plugin ist ein Python-Package unter <repo>/plugin. Um `import plugin`
zu ermöglichen, muss der PARENT (Repos-Root) auf sys.path, nicht der
Plugin-Ordner selbst (sonst sucht Python <repo>/plugin/plugin). Analog
zur conftest.py-Konvention.
"""
parent = _PLUGIN_DIR.parent
if _PLUGIN_DIR.is_dir() and str(parent) not in sys.path:
sys.path.insert(0, str(parent))
# Zusätzlich den Plugin-Ordner für Flat-Imports (P-022-Kompatibilität)
if _PLUGIN_DIR.is_dir() and str(_PLUGIN_DIR) not in sys.path:
sys.path.insert(0, str(_PLUGIN_DIR))
# ── Vertrags-Beschreibung ────────────────────────────────────────────────
# Kernel-Methoden/Attribute, die der RocketChatAdapter exponiert —
# Abkürzung des Core-API-Vertrags des Plugins:
# send_message → RocketChatREST.post_message (REST chat.postMessage)
# get_room_info → Adapter._room_info (Raum-Metadaten-Dict)
# register_command → Adapter._register_inline_commands (InlineCommandRegistry)
EXPECTED_ADAPTER_KERNEL_METHODS = {
"register_command": "_register_inline_commands",
"get_room_info": "_room_info",
"send_message": "post_message",
}
# Der Plugin-Entrypoint muss diese Top-Level-Funktionen exportieren
# (Hermes-Plugin-Basisvertrag).
EXPECTED_MODULE_FUNCTIONS = {
"register",
"check_requirements",
"validate_config",
"is_connected",
}
def _collect_plugin_hooks(plugin_mod) -> List[str]:
"""Extrahiert die vom Plugin beanspruchten Hook-Namen.
Scannt den Plugin-Quelltext auf `ctx.register_hook("...")`.
Liefert zusätzlich die bekannten Presence-Hooks (aus dem Quelltext).
"""
# Fallback-Menge (documented Presence-Hooks des Plugins)
known = {
"pre_gateway_dispatch", "post_llm_call", "subagent_start",
"subagent_stop", "on_session_start", "on_session_end",
"on_session_finalize", "on_session_reset",
"pre_tool_call", "post_tool_call",
"on_kanban_worker_spawned", "on_kanban_worker_exited",
"on_kanban_worker_stale_claim",
}
try:
src_path = Path(inspect.getfile(plugin_mod)).resolve()
src = src_path.read_text(encoding="utf-8")
found = set(re.findall(r'register_hook\(\s*["\']([a-z_]+)["\']', src))
return sorted(known | found)
except (OSError, TypeError):
return sorted(known)
def _get_valid_hooks_from_core() -> Optional[set]:
"""Liest Core-VALID_HOOKS. None wenn Core nicht importierbar."""
try:
import hermes_cli.plugins as core_plugins
hooks = getattr(core_plugins, "VALID_HOOKS", None)
return set(hooks) if hooks else None
except ImportError:
return None
def _collect_registered_commands() -> List[str]:
"""Sammelt die via InlineCommandRegistry registrierten ::-Befehle."""
try:
from plugin.adapter import RocketChatAdapter
from plugin.archivar.inline_commands import InlineCommandRegistry
# Adapter ohne vollständige Initialisierung: nur Registry + Register
adapter = RocketChatAdapter.__new__(RocketChatAdapter)
adapter._inline_commands = InlineCommandRegistry()
adapter._register_inline_commands()
return sorted(adapter._inline_commands.get_commands().keys())
except Exception as e: # noqa: BLE001 - defensiv, Vertrags-Test
logger.warning("[f070] Command-Sammlung fehlgeschlagen: %s", e)
return []
def _module_entrypoint_names(plugin_mod) -> set:
"""Namen der Top-Level-Funktionen im Plugin-__init__.py."""
try:
src = Path(inspect.getfile(plugin_mod)).resolve()
if src.name != "__init__.py":
src = src.parent / "__init__.py"
tree = ast.parse(src.read_text(encoding="utf-8")) if src.exists() else None
if tree:
return {n.name for n in ast.walk(tree)
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
except (OSError, SyntaxError):
pass
return {n for n in dir(plugin_mod) if callable(getattr(plugin_mod, n, None))}
def run_contract_checks(
valid_hooks: Optional[set] = None,
) -> Dict[str, object]:
"""Führt die Vertrags-Prüfungen aus und liefert eine Zusammenfassung.
Args:
valid_hooks: Optional ein set gültiger Hook-Namen (Default: aus
hermes_cli.plugins.VALID_HOOKS, falls Core importierbar).
Returns:
{"checked": int, "passed": int, "failed": [str,...]}
"""
checked = 0
passed = 0
failed: List[str] = []
def _ok() -> None:
nonlocal checked, passed
checked += 1
passed += 1
def _fail(desc: str) -> None:
nonlocal checked
checked += 1
failed.append(desc)
_ensure_plugin_importable()
try:
plugin_mod = importlib.import_module("plugin")
except ImportError as e:
_fail(f"Plugin-Modul 'plugin' NICHT importierbar: {e}")
return {"checked": checked, "passed": passed, "failed": failed}
# ── 1. Basisvertrag: Entrypoint-Funktionen ──────────────────────────
names = _module_entrypoint_names(plugin_mod)
for fn in EXPECTED_MODULE_FUNCTIONS:
has_fn = fn in names or (hasattr(plugin_mod, fn) and callable(getattr(plugin_mod, fn)))
_ok() if has_fn else _fail(f"Plugin fehlt Entrypoint-Funktion '{fn}()'")
# ── 2. Adapter-Kern-API (send_message, get_room_info, register_command) ──
try:
from plugin.adapter import RocketChatAdapter
src_path = Path(inspect.getfile(RocketChatAdapter)).resolve()
src = src_path.read_text(encoding="utf-8")
for logical, impl in EXPECTED_ADAPTER_KERNEL_METHODS.items():
if impl in src or impl in names:
_ok()
else:
_fail(f"Adapter-API '{logical}' nicht gefunden (erwartet '{impl}')")
except ImportError as e:
_fail(f"Adapter importierbar: {e}")
# ── 3. Hook-Kontrakt (kein toter Hook) ──────────────────────────────
hooks = _collect_plugin_hooks(plugin_mod)
core_hooks = valid_hooks if valid_hooks is not None else _get_valid_hooks_from_core()
if core_hooks is None:
for h in hooks:
_ok() # Hook bekannt (Quelltext), Core-Kontrast nicht prüfbar
logger.info("[f070] Core-VALID_HOOKS nicht lesbar — Hook-Kontrast übersprungen")
else:
for h in sorted(hooks):
if h in core_hooks:
_ok()
else:
_fail(f"Hook '{h}' NICHT in Core-VALID_HOOKS (toter Hook — P-032/P-064)")
# ── 4. Command-Registrierung ─────────────────────────────────────────
cmds = _collect_registered_commands()
_ok() if cmds else _fail("Keine ::-Befehle per InlineCommandRegistry registriert")
return {"checked": checked, "passed": passed, "failed": failed}
def build_report(result: Dict[str, object]) -> str:
"""Baut den Mensch-lesbaren Vertrags-Bericht."""
checked = result["checked"]
passed = result["passed"]
failed = result["failed"]
lines = [
"## 🤝 Contract-Test Plugin ↔ Core (F070)",
"",
f"**Geprüft:** {checked} | **Bestanden:** {passed} | "
f"**Fehlgeschlagen:** {len(failed)}",
"",
]
if failed:
lines.append("**Fehlgeschlagene Prüfungen:**")
for f in failed:
lines.append(f"- ⚠️ {f}")
lines.append("")
lines.append("**Ergebnis:** 🔴 NICHT kontrakt-konform")
else:
lines.append("**Ergebnis:** 🟢 Plugin ↔ Core-Vertrag erfüllt.")
return "\n".join(lines)
# ═══════════════════════════════════════════════════════════════════════════
# Pytest-Tests des Frameworks selbst
# ═══════════════════════════════════════════════════════════════════════════
def _has_real_plugin() -> bool:
return (_REPO_ROOT / "plugin").is_dir()
def test_framework_implements_marker():
content = Path(__file__).read_text(encoding="utf-8")
assert "@implements: [F-070]" in content, \
"test_contract_framework.py fehlt @implements: [F-070] (Bindestrich Pflicht)"
def test_contract_checks_return_shape():
res = run_contract_checks()
assert set(res) == {"checked", "passed", "failed"}
assert isinstance(res["checked"], int)
assert isinstance(res["passed"], int)
assert isinstance(res["failed"], list)
assert res["checked"] >= 4, "Mindestens Basisvertrag + Kern-API + Commands"
def test_collect_plugin_hooks_returns_list():
if _has_real_plugin():
import plugin # noqa: F401
hooks = _collect_plugin_hooks(importlib.import_module("plugin"))
assert isinstance(hooks, list)
assert len(hooks) > 0, "Plugin muss Presence-Hooks beanspruchen"
@pytest.mark.skipif(not _has_real_plugin(), reason="Echtes Plugin nicht im Repo-Kontext")
def test_real_plugin_contract_passes():
"""Gegen das echte Plugin im Repo: Vertrag muss (weitgehend) erfüllt sein."""
_ensure_plugin_importable()
import plugin # noqa: F401
res = run_contract_checks()
assert res["checked"] > 0, "Vertrags-Checks müssen laufen"
assert res["passed"] >= 4, \
f"Basisvertrag + Kern-API + Commands müssen bestehen: {res['failed']}"
# Kein Adapter-API-Fehler (send_message / get_room_info / register_command)
for f in res["failed"]:
assert "Adapter-API" not in f, f"Adapter-Kern-API muss vorhanden sein: {f}"
def test_build_report_formats():
ok = {"checked": 6, "passed": 6, "failed": []}
r = build_report(ok)
assert "Geprüft:" in r and "Bestanden:" in r
assert "🟢" in r
bad = {"checked": 6, "passed": 3, "failed": ["Hook 'ghost' fehlt"]}
r2 = build_report(bad)
assert "🔴" in r2
assert "ghost" in r2
def test_runner_standalone_executable():
src = Path(__file__).read_text(encoding="utf-8")
assert 'if __name__ == "__main__":' in src
assert "sys.exit(" in src
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
run_contract_checks()
res = run_contract_checks()
print(build_report(res))
sys.exit(1 if res["failed"] else 0)
+196
View File
@@ -0,0 +1,196 @@
"""F068 — 7-Tage-Stabilitätstest mit erweiterter Telemetrie: Tests.
Testet plugin/archivar/stability_monitor.py:
1. Module-Klassen & @implements-Marker
2. Test-Lifecycle: start / status / Fenster
3. Telemetrie-Sampling (message/error/restart) nur im laufenden Test
4. Persistenz (save/load über Instanzen hinweg)
5. Bericht-Generierung (automatisch nach Fenster + manuell)
6. is_completed / seconds_remaining Logik
7. Report-Bewertung (stabil / instabil)
@implements: [F-068]
"""
from __future__ import annotations
import json
import time
from pathlib import Path
import pytest
from plugin.archivar.stability_monitor import (
StabilityMonitor,
StabilityStatus,
STABILITY_WINDOW_S,
)
# ═══════════════════════════════════════════════════════════════════════════
# 1. Grundlegende Module-Struktur
# ═══════════════════════════════════════════════════════════════════════════
def test_module_implements_marker():
src = Path(__file__).resolve().parent.parent / "plugin" / "archivar" / "stability_monitor.py"
content = src.read_text()
assert "@implements: [F-068]" in content, \
"stability_monitor.py fehlt @implements: [F-068] (Bindestrich Pflicht)"
def test_classes_present():
from plugin.archivar.stability_monitor import StabilityMonitor as SM
assert SM is StabilityMonitor
assert StabilityStatus.RUNNING.value == "running"
@pytest.fixture
def monitor(tmp_path):
"""Isoliertes Monitor mit temp State-Pfad."""
m = StabilityMonitor(state_path=str(tmp_path / "stability-test.json"))
m.load()
return m
# ═══════════════════════════════════════════════════════════════════════════
# 2. Test-Lifecycle
# ═══════════════════════════════════════════════════════════════════════════
def test_initial_state(monitor):
assert monitor.status == StabilityStatus.INACTIVE
assert monitor.message_count == 0
assert monitor.error_count == 0
assert monitor.restart_count == 0
def test_start_transitions_to_running(monitor):
msg = monitor.start()
assert monitor.status == StabilityStatus.RUNNING
assert monitor._started_at is not None
assert "gestartet" in msg.lower() or "Stabilitätstest" in msg
def test_start_is_idempotent_while_running(monitor):
monitor.start()
first_start = monitor._started_at
msg = monitor.start()
assert monitor._started_at == first_start, "Wiederholter Start darf Fenster nicht neu setzen"
assert "läuft bereits" in msg
# ═══════════════════════════════════════════════════════════════════════════
# 3. Telemetrie-Sampling
# ═══════════════════════════════════════════════════════════════════════════
def test_sampling_only_while_running(monitor):
# INACTIVE → keine Zählung
monitor.record_message()
monitor.record_error()
monitor.record_restart()
assert monitor.message_count == 0
assert monitor.error_count == 0
assert monitor.restart_count == 0
# RUNNING → Zählung
monitor.start()
monitor.record_message()
monitor.record_message()
monitor.record_error()
monitor.record_restart()
assert monitor.message_count == 2
assert monitor.error_count == 1
assert monitor.restart_count == 1
def test_message_sets_last_timestamp(monitor):
monitor.start()
monitor.record_message()
assert monitor._last_message_ts is not None
# ═══════════════════════════════════════════════════════════════════════════
# 4. Persistenz
# ═══════════════════════════════════════════════════════════════════════════
def test_save_load_roundtrip(monitor, tmp_path):
monitor.start()
monitor.record_message()
monitor.record_message()
monitor.record_error()
monitor.save()
m2 = StabilityMonitor(state_path=str(tmp_path / "stability-test.json"))
assert m2.load() is True
assert m2.status == StabilityStatus.RUNNING
assert m2.message_count == 2
assert m2.error_count == 1
assert m2._started_at is not None
def test_load_missing_file_is_ok(monitor, tmp_path):
m2 = StabilityMonitor(state_path=str(tmp_path / "nicht-da.json"))
assert m2.load() is True
assert m2.status == StabilityStatus.INACTIVE
# ═══════════════════════════════════════════════════════════════════════════
# 5. Bericht-Generierung
# ═══════════════════════════════════════════════════════════════════════════
def test_manual_report_early_keeps_running(monitor):
monitor.start()
monitor.record_message()
report = monitor.generate_report_snapshot()
assert "Stabilitätsbericht" in report
# Fenster nicht abgelaufen → bleibt RUNNING
assert monitor.status == StabilityStatus.RUNNING
def test_auto_report_after_window(monitor):
monitor.start()
monitor.record_message()
monitor.record_message()
monitor.record_message() # 3 Nachrichten, 0 Fehler → stabil
# Fenster ablaufen lassen (Zeit manipulieren)
monitor._started_at = time.time() - STABILITY_WINDOW_S - 1
assert monitor.is_completed() is True
report = monitor.generate_report_snapshot()
assert "Stabilitätsbericht" in report
assert monitor.status == StabilityStatus.REPORTED
def test_report_stability_grading(monitor):
# instabil: viele Fehler — Fenster ablaufen lassen für End-Bewertung
monitor.start()
for _ in range(10):
monitor.record_error()
monitor._started_at = time.time() - STABILITY_WINDOW_S - 1
assert monitor.is_completed() is True
report = monitor.generate_report_snapshot()
assert "Instabil" in report or "🔴" in report
# ═══════════════════════════════════════════════════════════════════════════
# 6. Fenster-Logik
# ═══════════════════════════════════════════════════════════════════════════
def test_seconds_remaining_full_window(monitor):
monitor.start()
remaining = monitor.seconds_remaining()
assert 0 <= remaining <= STABILITY_WINDOW_S
def test_seconds_remaining_zero_when_expired(monitor):
monitor.start()
monitor._started_at = time.time() - STABILITY_WINDOW_S - 100
assert monitor.seconds_remaining() == 0.0
def test_reset(monitor):
monitor.start()
monitor.record_message()
monitor.record_error()
monitor.reset()
assert monitor.status == StabilityStatus.INACTIVE
assert monitor.message_count == 0
assert monitor.error_count == 0
+194
View File
@@ -0,0 +1,194 @@
"""F071 — Refactor-Disziplin: Audit-Script-Tests.
Testet scripts/audit_refactor.py:
1. Script existiert & ist ausführbar
2. @implements: [F-071] Marker gesetzt
3. Audit findet ein synthetisches Duplikat (2 gleiche Funktionen)
4. Audit findet wiederkehrende Naming-Verletzung
5. Audit findet unreferenzierte Funktion (toter Pfad)
6. Exit-Codes: 0 = sauber, 1 = Duplikat, 2 = Naming/Dead-Verdacht
7. --json Ausgabe liefert gültiges JSON
@implements: [F-071]
"""
from __future__ import annotations
import json
import subprocess
import sys
import tempfile
from pathlib import Path
import pytest
_REPO_ROOT = Path(__file__).resolve().parent.parent
SCRIPT = _REPO_ROOT / "scripts" / "audit_refactor.py"
def _run_script(args, cwd=_REPO_ROOT):
return subprocess.run(
[sys.executable, str(SCRIPT), *args],
capture_output=True, text=True, cwd=cwd,
)
# ═══════════════════════════════════════════════════════════════════════════
# 1. Script existiert & ausführbar
# ═══════════════════════════════════════════════════════════════════════════
def test_script_exists():
assert SCRIPT.exists(), "scripts/audit_refactor.py fehlt"
def test_script_runs_on_repo():
# Nur sinnvoll, wenn das echtes Repo (plugin/archivar) vorliegt.
if not (_REPO_ROOT / "plugin" / "archivar").is_dir():
pytest.skip("Repo-Verzeichnis plugin/archivar nicht vorhanden (Nicht-Repo-Kontext)")
r = _run_script(["--dir", "plugin/archivar"])
assert r.returncode in (0, 1, 2), \
f"Audit muss auf Repo laufen, rc={r.returncode}: {r.stderr}"
# ═══════════════════════════════════════════════════════════════════════════
# 2. @implements-Marker
# ═══════════════════════════════════════════════════════════════════════════
def test_implements_marker():
content = SCRIPT.read_text()
assert "@implements: [F-071]" in content, \
"audit_refactor.py fehlt @implements: [F-071] (Bindestrich Pflicht)"
# ═══════════════════════════════════════════════════════════════════════════
# 3. Duplikat-Erkennung
# ═══════════════════════════════════════════════════════════════════════════
DUPLICATE_FIXTURE = '''\
def compute_totals_a(items):
totals = []
running = 0
for it in items:
running = running + it
if running > 100:
totals.append(running)
else:
totals.append(0)
return totals
def compute_totals_b(values):
result = []
accum = 0
for v in values:
accum = accum + v
if accum > 100:
result.append(accum)
else:
result.append(0)
return result
'''
@pytest.fixture
def dup_dir():
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp) / "pkg"
base.mkdir()
(base / "dup.py").write_text(DUPLICATE_FIXTURE, encoding="utf-8")
yield str(base)
def test_detects_duplicate(dup_dir):
r = _run_script(["--dir", dup_dir, "--json"])
assert r.returncode == 0, f"JSON-Modus muss 0 liefern, stderr={r.stderr}"
data = json.loads(r.stdout)
assert len(data["duplicates"]) >= 1, \
f"Audit muss das Duplikat finden: {data['duplicates']}"
names = {o["name"] for d in data["duplicates"] for o in d["occurrences"]}
assert "compute_totals_a" in names and "compute_totals_b" in names
def test_duplicate_exit_code(dup_dir):
r = _run_script(["--dir", dup_dir]) # human-Modus
assert r.returncode == 1, "Duplikat muss Exit-Code 1 liefern"
# ═══════════════════════════════════════════════════════════════════════════
# 4. Naming-Verletzung (wiederkehrend)
# ═══════════════════════════════════════════════════════════════════════════
NAMING_FIXTURE = {
"a.py": (
"def BadNameOne(x):\n"
" return x + 1\n\n\n"
"def BadNameTwo(y):\n"
" return y * 2\n"
),
}
def test_detects_naming_violation():
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp) / "pkg"
base.mkdir()
for name, content in NAMING_FIXTURE.items():
(base / name).write_text(content, encoding="utf-8")
r = _run_script(["--dir", str(base), "--json"])
data = json.loads(r.stdout)
fn_rows = [(row[0], row[1]) for row in data["naming_findings"]]
assert any(n == "BadNameOne" and k == "Funktion" for n, k in fn_rows), \
f"naming_findings fehlt BadNameOne: {data['naming_findings']}"
assert any(n == "BadNameTwo" and k == "Funktion" for n, k in fn_rows)
# ═══════════════════════════════════════════════════════════════════════════
# 5. Toter Pfad (unreferenzierte Funktion)
# ═══════════════════════════════════════════════════════════════════════════
DEAD_FIXTURE = {
"a.py": (
"def used_function():\n"
" return 'x'\n\n\n"
"def dead_function():\n"
" return 'unused'\n\n\n"
"_caller = used_function()\n"
),
}
def test_detects_dead_code():
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp) / "pkg"
base.mkdir()
for name, content in DEAD_FIXTURE.items():
(base / name).write_text(content, encoding="utf-8")
r = _run_script(["--dir", str(base), "--json"])
data = json.loads(r.stdout)
dead_names = [n for n, _f in data["dead_code_suspects"]]
assert "dead_function" in dead_names
assert "used_function" not in dead_names
# ═══════════════════════════════════════════════════════════════════════════
# 6. Sauberes Paket → Exit 0
# ═══════════════════════════════════════════════════════════════════════════
CLEAN_FIXTURE = {
"x.py": (
"def used():\n"
" return 1\n\n\n"
"global_out = used()\n"
),
}
def test_clean_package_exit_zero():
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp) / "pkg"
base.mkdir()
for name, content in CLEAN_FIXTURE.items():
(base / name).write_text(content, encoding="utf-8")
r = _run_script(["--dir", str(base)])
assert r.returncode == 0, \
f"sauberes Paket soll 0 liefern: {r.stdout} {r.stderr}"