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
+62
View File
@@ -1550,6 +1550,18 @@ class RocketChatAdapter(BasePlatformAdapter):
from archivar.inline_commands import InlineCommandRegistry from archivar.inline_commands import InlineCommandRegistry
self._inline_commands = InlineCommandRegistry() self._inline_commands = InlineCommandRegistry()
self._register_inline_commands() self._register_inline_commands()
# F068: 7-Tage-Stabilitätstest — Monitor persistiert State und zählt
# Messages/Fehler/Neustarts während eines laufenden Testfensters.
try:
from archivar.stability_monitor import stability_monitor
self._stability_monitor = stability_monitor
self._stability_monitor.load()
self._stability_monitor.record_restart()
except Exception as e: # noqa: BLE001 - graceful degradation
self._stability_monitor = None
logger.warning("[f068] Stabilitäts-Monitor nicht initialisierbar: %s", e)
# R5: Username des letzten Inline-Command-Aufrufs (für ::reasoning # R5: Username des letzten Inline-Command-Aufrufs (für ::reasoning
# Session-Key-Ableitung). Wird in _handle_inline_command gesetzt. # Session-Key-Ableitung). Wird in _handle_inline_command gesetzt.
self._last_inline_username: str = "" self._last_inline_username: str = ""
@@ -3218,6 +3230,15 @@ class RocketChatAdapter(BasePlatformAdapter):
# Update activity # Update activity
self._last_activity = time.time() self._last_activity = time.time()
# F068: Stabilitätstelemetrie — eingehende verarbeitete Nachricht zählen
_st_mon = getattr(self, "_stability_monitor", None)
if _st_mon is not None:
try:
_st_mon.record_message()
except Exception: # noqa: BLE001 - Telemetrie nie crashen
pass
room_name = self._room_info.get(room_id, {}).get("name", room_id) room_name = self._room_info.get(room_id, {}).get("name", room_id)
room_type = self._room_info.get(room_id, {}).get("type", "unknown") room_type = self._room_info.get(room_id, {}).get("type", "unknown")
logger.info("[rocketchat] Message from %s in %s [%s]: %s", username, room_name, room_type, text[:80]) logger.info("[rocketchat] Message from %s in %s [%s]: %s", username, room_name, room_type, text[:80])
@@ -5321,6 +5342,40 @@ class RocketChatAdapter(BasePlatformAdapter):
category="Plugin", category="Plugin",
) )
# F068: 7-Tage-Stabilitätstest — Start/Bericht
self._inline_commands.register(
"stability-test", self._cmd_stability_test,
help_text="Startet den 7-Tage-Stabilitätstest (F068)",
description="Startet (oder setzt fort) den Stabilitätstest, der "
"7 Tage lang Telemetrie sammelt (Messages, Fehler, "
"Neustarts) und danach einen Bericht erstellt.",
category="Plugin",
)
self._inline_commands.register(
"stability-report", self._cmd_stability_report,
help_text="Erstellt den Stabilitätsbericht (F068)",
description="Erstellt jetzt den Stabilitätsbericht. Nach Ablauf "
"des 7-Tage-Fensters wird der Test als abgeschlossen "
"markiert.",
category="Plugin",
)
async def _cmd_stability_test(self, room_id: str, args: str) -> str:
"""::stability-test — Startet den 7-Tage-Stabilitätstest (F068)."""
monitor = getattr(self, "_stability_monitor", None)
if monitor is None:
return "⚠️ Stabilitäts-Monitor nicht verfügbar (Init-Fehler)."
return monitor.start()
async def _cmd_stability_report(self, room_id: str, args: str) -> str:
"""::stability-report — Erstellt den Stabilitätsbericht (F068)."""
monitor = getattr(self, "_stability_monitor", None)
if monitor is None:
return "⚠️ Stabilitäts-Monitor nicht verfügbar (Init-Fehler)."
if monitor.status.value == "inactive":
return "Kein Test aktiv. Start mit `::stability-test`."
return monitor.generate_report_snapshot()
async def _handle_inline_command( async def _handle_inline_command(
self, text: str, room_id: str, room_name: str, username: str self, text: str, room_id: str, room_name: str, username: str
) -> bool: ) -> bool:
@@ -10570,6 +10625,13 @@ class RocketChatAdapter(BasePlatformAdapter):
break break
except Exception as e: except Exception as e:
logger.error("[rocketchat] Listener error: %s", e) logger.error("[rocketchat] Listener error: %s", e)
# F068: Fehler-Telemetrie — Listener-Fehler zählen
_st_err = getattr(self, "_stability_monitor", None)
if _st_err is not None:
try:
_st_err.record_error()
except Exception: # noqa: BLE001 - Telemetrie nie crashen
pass
await asyncio.sleep(1) await asyncio.sleep(1)
def _ddp_queue_get(self, timeout: float): def _ddp_queue_get(self, timeout: float):
+1
View File
@@ -764,6 +764,7 @@ class ArchivarMessageHandler:
self._stats["last_error"] = str(e) self._stats["last_error"] = str(e)
return False return False
# TODO: DEAD CODE - F071
async def handle_move_request_response( async def handle_move_request_response(
self, self,
room_id: str, room_id: str,
+3
View File
@@ -365,6 +365,7 @@ class ArchivarState:
else: else:
return None # "ask" - Entscheidung pro Nachricht return None # "ask" - Entscheidung pro Nachricht
# TODO: DEAD CODE - F071
def remove_room_state(self, room_id: str) -> bool: def remove_room_state(self, room_id: str) -> bool:
"""Entferne den Zustand für einen Raum. """Entferne den Zustand für einen Raum.
@@ -475,12 +476,14 @@ class ArchivarState:
return self._rooms.copy() return self._rooms.copy()
@property @property
# TODO: DEAD CODE - F071
def is_loaded(self) -> bool: def is_loaded(self) -> bool:
"""True wenn der Zustand geladen wurde.""" """True wenn der Zustand geladen wurde."""
return self._loaded return self._loaded
# ── P1-3: stay_tracker Persistenz ────────────────────────────────── # ── P1-3: stay_tracker Persistenz ──────────────────────────────────
# TODO: DEAD CODE - F071
def get_stay_tracker(self) -> Dict[str, Dict[str, Union[int, float]]]: def get_stay_tracker(self) -> Dict[str, Dict[str, Union[int, float]]]:
"""Gibt den stay_tracker zurück (für Auto-Promotion nach 3x 'Hier bleiben').""" """Gibt den stay_tracker zurück (für Auto-Promotion nach 3x 'Hier bleiben')."""
if not self._loaded: if not self._loaded:
+3
View File
@@ -56,6 +56,7 @@ class ClassificationResult:
llm_verified: bool = False llm_verified: bool = False
"""True, wenn das Ergebnis durch LLM-Verifikation bestätigt wurde.""" """True, wenn das Ergebnis durch LLM-Verifikation bestätigt wurde."""
# TODO: DEAD CODE - F071
def is_confident(self, threshold: float = CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]) -> bool: def is_confident(self, threshold: float = CONFIDENCE_THRESHOLDS["AUTO_ROUTE"]) -> bool:
"""True wenn die Konfidenz über dem Schwellenwert für automatisches Routing liegt.""" """True wenn die Konfidenz über dem Schwellenwert für automatisches Routing liegt."""
return self.confidence >= threshold return self.confidence >= threshold
@@ -704,6 +705,7 @@ class IntentClassifier:
return self._initialized return self._initialized
@property @property
# TODO: DEAD CODE - F071
def init_error(self) -> Optional[str]: def init_error(self) -> Optional[str]:
"""Error message from initialization, or None.""" """Error message from initialization, or None."""
return self._init_error return self._init_error
@@ -714,6 +716,7 @@ class IntentClassifier:
return len(self._category_vectors) return len(self._category_vectors)
@property @property
# TODO: DEAD CODE - F071
def cache_size(self) -> int: def cache_size(self) -> int:
"""Number of cached message embeddings.""" """Number of cached message embeddings."""
return len(self._message_cache) return len(self._message_cache)
+1
View File
@@ -108,6 +108,7 @@ class DocumentationStore:
f"{text}\n" f"{text}\n"
) )
# TODO: DEAD CODE - F071
def list_stored(self, category: str = "") -> list[Path]: def list_stored(self, category: str = "") -> list[Path]:
"""List stored documents, optionally filtered by category. """List stored documents, optionally filtered by category.
+1
View File
@@ -3097,6 +3097,7 @@ class PresenceEngine:
# ── P-041a: Progress-Refresh ───────────────────────────────────────── # ── P-041a: Progress-Refresh ─────────────────────────────────────────
# TODO: DEAD CODE - F071
def refresh_chat_profile_timestamp(self) -> None: def refresh_chat_profile_timestamp(self) -> None:
"""P-041a: Setzt den chat_profile-Timestamp auf time.time(). """P-041a: Setzt den chat_profile-Timestamp auf time.time().
+1
View File
@@ -295,6 +295,7 @@ class RoomIndexManager:
# ── Incremental Updates ──────────────────────────────────────────── # ── Incremental Updates ────────────────────────────────────────────
# TODO: DEAD CODE - F071
def add_room(self, room_id: str, entry: RoomEntry) -> bool: def add_room(self, room_id: str, entry: RoomEntry) -> bool:
"""Fügt einen einzelnen Raum zum Index hinzu. """Fügt einen einzelnen Raum zum Index hinzu.
+314
View File
@@ -0,0 +1,314 @@
"""F068 — 7-Tage-Stabilitätstest mit erweiterter Telemetrie.
Sammelt über 7 Tage Telemetrie-Daten und erstellt danach (oder manuell)
einen Stabilitaets-Bericht.
Gesammelte Metriken:
- Uptime (Startzeitpunkt des Tests + Laufzeit in Sekunden/Tagen)
- Message-Count (Anzahl verarbeiteter eingehender Nachrichten)
- Error-Count (Anzahl aufgetretener Fehler/Exceptions im Plugin)
- Restart-Count (Anzahl Gateway-/Adapter-Neustarts während des Tests)
Start: inline Command `::stability-test`
Bericht: automatisch nach 7 Tagen ODER manuell via `::stability-report`
Persistenz: State wird in einer JSON-Datei gehalten (maschinen-spezifisch,
NICHT committen — siehe .gitignore / data-Pfad).
@implements: [F-068]
"""
from __future__ import annotations
import json
import logging
import os
import time
from datetime import datetime, timezone
from enum import Enum
from pathlib import Path
from typing import Dict, Optional
logger = logging.getLogger(__name__)
# ── Konfiguration ──────────────────────────────────────────────────────────
# Dauer des Testfensters (Default: 7 Tage). In Sekunden.
STABILITY_WINDOW_S: float = float(os.getenv("ARCHIVAR_STABILITY_WINDOW_S", str(7 * 24 * 3600)))
# Persistenz-Pfad (maschinen-spezifisch — analog archivar-state.json).
STABILITY_STATE_PATH: str = os.path.expanduser(
os.getenv("ARCHIVAR_STABILITY_STATE_PATH", "~/.hermes/hermes-agent/data/stability-monitor.json")
)
# Feature-Flag: Telemetrie-Sampling global ein/aus.
STABILITY_ENABLED: bool = os.getenv("ARCHIVAR_STABILITY_ENABLED", "true").strip().lower() not in ("false", "0", "no", "off")
class StabilityStatus(Enum):
"""Zustand des Stabilitätstests."""
INACTIVE = "inactive" # kein Test gestartet
RUNNING = "running" # Test läuft (innerhalb des Fensters)
COMPLETED = "completed" # Testfenster abgelaufen, Bericht fällig
REPORTED = "reported" # Bericht erstellt
class StabilityMonitor:
"""Überwacht die Plugin-Stabilität über 7 Tage (oder konfigurierbares Fenster).
Thread-sicher via GIL (single-writer Kontext — wie routing_counter).
Persistiert den State über Neustarts hinweg in einer JSON-Datei.
"""
def __init__(self, state_path: Optional[str] = None) -> None:
self._state_path = state_path or STABILITY_STATE_PATH
self._status: StabilityStatus = StabilityStatus.INACTIVE
self._started_at: Optional[float] = None
self._restarts_at_start: int = 0
# Zähler
self._message_count: int = 0
self._error_count: int = 0
self._restart_count: int = 0
# Zusätzliche Telemetrie (erweitert): letzte Activity-Timestamps
self._last_message_ts: Optional[float] = None
self._last_error_ts: Optional[float] = None
# Anzahl Fehler-Meldungen, die nach dem Bericht aufgetreten sind
self._errors_since_report: int = 0
self._loaded = False
# ── State-Persistenz ────────────────────────────────────────────────
def _to_dict(self) -> Dict[str, object]:
return {
"status": self._status.value,
"started_at": self._started_at,
"restarts_at_start": self._restarts_at_start,
"message_count": self._message_count,
"error_count": self._error_count,
"restart_count": self._restart_count,
"last_message_ts": self._last_message_ts,
"last_error_ts": self._last_error_ts,
"errors_since_report": self._errors_since_report,
}
def _from_dict(self, data: Dict[str, object]) -> None:
try:
self._status = StabilityStatus(data.get("status", "inactive"))
except ValueError:
self._status = StabilityStatus.INACTIVE
self._started_at = data.get("started_at")
self._restarts_at_start = int(data.get("restarts_at_start", 0))
self._message_count = int(data.get("message_count", 0))
self._error_count = int(data.get("error_count", 0))
self._restart_count = int(data.get("restart_count", 0))
self._last_message_ts = data.get("last_message_ts")
self._last_error_ts = data.get("last_error_ts")
self._errors_since_report = int(data.get("errors_since_report", 0))
def load(self) -> bool:
"""Lade den persistierten Test-State. True bei Erfolg (oder neu)."""
try:
path = Path(self._state_path)
if not path.exists():
self._loaded = True
return True
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
self._from_dict(data)
self._loaded = True
return True
except (json.JSONDecodeError, OSError, TypeError) as e:
logger.warning("[f068] Stabilitäts-State nicht ladbar (%s): %s", self._state_path, e)
self._loaded = False
return False
def save(self) -> bool:
"""Schreibe den State zurück in die JSON-Datei."""
try:
path = Path(self._state_path)
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_suffix(path.suffix + ".tmp")
with tmp.open("w", encoding="utf-8") as f:
json.dump(self._to_dict(), f, indent=2, ensure_ascii=False)
tmp.replace(path)
return True
except OSError as e:
logger.warning("[f068] Stabilitäts-State nicht schreibbar: %s", e)
return False
# ── Test-Lifecycle ──────────────────────────────────────────────────
def start(self, restart_count_hint: int = 0) -> str:
"""Startet (oder setzt fort) den Stabilitätstest.
Bei Erst-Start wird der Countdown auf STABILITY_WINDOW_S gesetzt.
Bei laufendem Test wird das Fenster NICHT neu gestartet (die bereits
gesammelten Daten bleiben relevant).
"""
if self._status == StabilityStatus.RUNNING and self._started_at is not None:
remaining = self.seconds_remaining()
return (
f"Stabilitätstest läuft bereits (noch {self._format_duration(remaining)}). "
f"Gesammelt: {self._message_count} Messages, "
f"{self._error_count} Fehler, {self._restart_count} Restarts."
)
self._status = StabilityStatus.RUNNING
self._started_at = time.time()
self._restarts_at_start = restart_count_hint
# Restart-Count relativ zum Teststart zurücksetzen
self._restart_count = 0
self._message_count = 0
self._error_count = 0
self._errors_since_report = 0
self.save()
return (
f"🟢 Stabilitätstest gestartet. Fenster: "
f"{self._format_duration(STABILITY_WINDOW_S)}. "
f"Bericht: automatisch nach Ablauf oder manuell via ::stability-report."
)
def seconds_remaining(self) -> float:
"""Verbleibende Sekunden bis zum Bericht (0 wenn abgelaufen)."""
if self._started_at is None:
return 0.0
elapsed = time.time() - self._started_at
remaining = STABILITY_WINDOW_S - elapsed
return max(remaining, 0.0)
def is_completed(self) -> bool:
"""True wenn der Test lief und das Fenster abgelaufen ist."""
return (
self._status == StabilityStatus.RUNNING
and self._started_at is not None
and time.time() - self._started_at >= STABILITY_WINDOW_S
)
# ── Telemetrie-Sampling ──────────────────────────────────────────────
def record_message(self) -> None:
"""Zählt eine verarbeitete eingehende Nachricht (während laufendem Test)."""
if not STABILITY_ENABLED or self._status != StabilityStatus.RUNNING:
return
self._message_count += 1
self._last_message_ts = time.time()
def record_error(self) -> None:
"""Zählt einen Plugin-Fehler (während laufendem Test)."""
if not STABILITY_ENABLED or self._status != StabilityStatus.RUNNING:
return
self._error_count += 1
self._last_error_ts = time.time()
def record_restart(self) -> None:
"""Zählt einen Neustart (während laufendem Test)."""
if not STABILITY_ENABLED or self._status != StabilityStatus.RUNNING:
return
self._restart_count += 1
self.save()
# ── Bericht ──────────────────────────────────────────────────────────
@staticmethod
def _format_duration(seconds: float) -> str:
seconds = max(0.0, float(seconds))
days = int(seconds // 86400)
hours = int((seconds % 86400) // 3600)
mins = int((seconds % 3600) // 60)
secs = int(seconds % 60)
return f"{days}d {hours:02d}h {mins:02d}m {secs:02d}s"
@staticmethod
def _format_uptime(started_at: float) -> str:
return StabilityMonitor._format_duration(time.time() - started_at)
def build_report(self) -> str:
"""Baut den Stabilitaets-Bericht als Mensch-lesbaren Markdown-String."""
uptime = self._format_uptime(self._started_at) if self._started_at else "—"
if self._started_at:
start_iso = datetime.fromtimestamp(self._started_at, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
else:
start_iso = "—"
ratio_success = 0.0
total = self._message_count + self._error_count
if total:
ratio_success = self._message_count / total
stability_pct = 100.0 * ratio_success
lines = [
"## 📈 Stabilitätsbericht (F068)",
"",
f"**Status:** {self._status.value}",
f"**Teststart:** {start_iso}",
f"**Uptime (im Testfenster):** {uptime}",
f"**Fenster:** {self._format_duration(STABILITY_WINDOW_S)}",
f"**Verbleibend:** {self._format_duration(self.seconds_remaining()) if self._status == StabilityStatus.RUNNING else '—'}",
"",
"**Telemetrie:**",
f"- Nachrichten verarbeitet: {self._message_count}",
f"- Fehler: {self._error_count}",
f"- Neustarts: {self._restart_count}",
f"- Stabilität: {stability_pct:.1f}%",
"",
"**Bewertung:**",
]
if self._status == StabilityStatus.INACTIVE:
lines.append("Kein Test aktiv. Start mit `::stability-test`.")
elif self._status in (StabilityStatus.COMPLETED, StabilityStatus.REPORTED) or self.is_completed():
# is_completed() = Fenster abgelaufen, auch wenn Status noch RUNNING
if self._error_count == 0 and self._restart_count == 0:
lines.append("🟢 Stabil über das gesamte Testfenster — keine Fehler, keine Neustarts.")
elif self._error_count <= 3 and self._restart_count == 0:
lines.append("🟡 Stabil mit wenigen Fehlern (keine Neustarts). Fehler-Pfade prüfen.")
else:
lines.append("🔴 Instabil — hohe Fehler- oder Neustart-Rate. Sofort analysieren (P-Klasse).")
else:
lines.append(f"Noch {self._format_duration(self.seconds_remaining())} bis zum Bericht.")
return "\n".join(lines)
def generate_report_snapshot(self) -> str:
"""Erzeugt den Bericht UND markiert den Test als REPORTED (endgültig).
Der Wechsel auf REPORTED erfolgt nur, wenn das Testfenster abgelaufen
ist — ein manueller Bericht während des Laufs bleibt RUNNING.
"""
report = self.build_report()
if self._status == StabilityStatus.RUNNING and self.is_completed():
self._status = StabilityStatus.REPORTED
self.save()
return report
def reset(self) -> None:
"""Setzt den Test vollständig zurück (für ::stability-test Neu-Start)."""
self._status = StabilityStatus.INACTIVE
self._started_at = None
self._restarts_at_start = 0
self._message_count = 0
self._error_count = 0
self._restart_count = 0
self._errors_since_report = 0
self._last_message_ts = None
self._last_error_ts = None
self.save()
# ── Abfragen für Status-Anzeige ─────────────────────────────────────
@property
def status(self) -> StabilityStatus:
return self._status
@property
def message_count(self) -> int:
return self._message_count
@property
def error_count(self) -> int:
return self._error_count
@property
def restart_count(self) -> int:
return self._restart_count
# Modul-Level-Singleton — analog routing_telemetry/routing_counter.
stability_monitor = StabilityMonitor()
+380
View File
@@ -0,0 +1,380 @@
"""F071 — Refactor-Disziplin-Audit für plugin/archivar/.
Findet Duplikate (via normalized-Fingerprints), prüft Naming-Konventionen
(PEP-08 + Projekt-Konvention: Funktionen/Methoden snake_case, Klassen
PascalCase, Konstanten UPPER_SNAKE), und listet tote/unreferenzierte
Code-Pfade auf (Funktionen ohne Aufrufer im Plugin-Paket).
Usage:
python3 scripts/audit_refactor.py [--dir plugin/archivar] [--json]
Exit-Codes: 0 = keine Befunde, 1 = Duplikate gefunden, 2 = nur
Naming-Abweichungen / DEAD-Code-Verdacht (kein Hard-Fail), 3 = Fehler.
Der Audit ist bewusst *informativ* (Refactor-Disziplin = verschärfen, nicht
automatisch umbauen): er meldet Befunde, damit ein Entwickler sie bewusst
entscheidet. Verifiziert tote Pfade im Code mit `# TODO: DEAD CODE - F071`
markieren (Audit-Disziplin), NICHT automatisch löschen.
@implements: [F-071]
"""
from __future__ import annotations
import argparse
import ast
import json
import re
import sys
from collections import defaultdict
from pathlib import Path
from typing import Dict, List, Tuple
# ── Konfiguration ──────────────────────────────────────────────────────────
DEFAULT_DIR = "plugin/archivar"
TARGET_EXT = ".py"
MIN_BODY_LINES = 4
PRIVATE_PREFIXES = ("_", "test_")
# Unterordner, die bei der Suche nach Duplikaten/Naming STANDARDMÄSSIG
# übersprungen werden (Tests haben eigene Duplikat-Toleranz, Fixtures sind
# bewusst ähnlich). Mit --include-tests einblendbar.
SKIP_TEST_SUBDIRS = True # Standard: tests/ überspringen
def _should_skip_dir(path: Path, include_tests: bool) -> bool:
"""Soll path (ein Verzeichnis-Pfad) übersprungen werden?"""
if "__pycache__" in path.parts:
return True
if not include_tests and "tests" in path.parts:
return True
return False
def _parse_file(path: Path) -> ast.Module:
with path.open("r", encoding="utf-8") as f:
return ast.parse(f.read(), filename=str(path))
def _anonymize_identifiers(node: ast.AST) -> ast.AST:
"""Ersetzt lokale Bezeichner (ast.Name.id, ast.arg.arg, ast.alias.asname)
durch Platzhalter, damit strukturelle Duplikate unabhängig von
Variablennamen erkannt werden. Methoden-/Attributnamen bleiben erhalten
(sie sind Teil der Struktur/der aufgerufenen API)."""
for child in ast.walk(node):
if isinstance(child, ast.Name):
child.id = "$ID$"
elif isinstance(child, ast.arg):
child.arg = "$ARG$"
elif isinstance(child, ast.alias):
child.asname = "$ASNAME$"
child.name = "$MODULE$"
elif isinstance(child, ast.keyword):
child.arg = None # keyword-Namen weg - strukturell nicht relevant
return node
def _normalized_body_from_ast(body_nodes: List[ast.stmt]) -> str:
"""Normalisiert eine AST-Node-Liste zu einem Fingerprint-String.
Anonymisiert lokale Bezeichner (Name.id, arg.arg), maskiert Literale,
und dump-t die Struktur (include_attributes=False). Erkennt strukturelle
Duplikate unabhängig von Variablennamen.
"""
parts = [_dump_anonymized(n) for n in body_nodes]
joined = "\n".join(parts)
joined = re.sub(r'("[^"]*")|(\'[^\']*\')', 'STR', joined)
joined = re.sub(r"\b\d+\.?\d*\b", "NUM", joined)
return joined
def _dump_anonymized(node: ast.AST) -> str:
import copy
node = _anonymize_identifiers(copy.deepcopy(node))
return ast.dump(node, annotate_fields=True, include_attributes=False)
def _iter_code_units(tree: ast.Module) -> List[Tuple[str, int, str]]:
"""Liefert (name, lineno, normalized_fingerprint) für Funktions- und
Methodendefinitionen mit Body-Umfang >= MIN_BODY_LINES."""
units: List[Tuple[str, int, str]] = []
for node in tree.body:
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
_collect_function(node, units)
elif isinstance(node, ast.ClassDef):
for sub in node.body:
if isinstance(sub, (ast.FunctionDef, ast.AsyncFunctionDef)):
_collect_function(sub, units)
return units
def _collect_function(node, units) -> None:
if len(node.body) >= MIN_BODY_LINES:
units.append((node.name, getattr(node, "lineno", 0),
_normalized_body_from_ast(node.body)))
# ── Naming-Audit ─────────────────────────────────────────────────────────
class NamingAudit:
"""Prüft Naming-Konventionen. Meldet wiederkehrende Verstöße (>=2)."""
NAME_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
SNAKE = re.compile(r"^_?[a-z][a-z0-9_]*$")
PASCAL = re.compile(r"^[A-Z][a-zA-Z0-9]*$")
def __init__(self) -> None:
self.findings: Dict[str, List[str]] = defaultdict(list)
def _violation(self, name: str, kind: str, where: str) -> None:
self.findings[(kind, name)].append(where)
def audit_module(self, path: Path, tree: ast.Module) -> None:
full = str(path)
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
name = node.name
if name.startswith(PRIVATE_PREFIXES):
continue
is_method = bool(node.args.args) and node.args.args[0].arg in ("self", "cls")
# Methoden innerhalb Klassen
if is_method:
if not self.NAME_RE.match(name) or not self.SNAKE.match(name):
self._violation(name, "Methode", f"{full}:{node.lineno}")
else:
if not self.NAME_RE.match(name) or not self.SNAKE.match(name):
self._violation(name, "Funktion", f"{full}:{node.lineno}")
elif isinstance(node, ast.ClassDef):
if node.name.startswith(PRIVATE_PREFIXES):
continue
if not self.PASCAL.match(node.name):
self._violation(node.name, "Klasse", f"{full}:{node.lineno}")
def consolidated(self) -> List[Tuple[str, str, int, str]]:
"""Jede echte Konventions-Verletzung melden (Name matcht das erwartete
Muster nicht). Kein >=2-Gate — jede Verletzung ist ein Fund und soll
von einem Entwickler entschieden werden."""
rows = []
for (kind, name) in sorted(self.findings):
where = self.findings[(kind, name)]
rows.append((name, kind, len(where), where[0]))
return rows
# ── Duplikat-Audit ────────────────────────────────────────────────────────
class DuplicateAudit:
def __init__(self) -> None:
self.fingerprints: Dict[str, List[Tuple[str, str, int]]] = defaultdict(list)
def add_units(self, path: Path, tree: ast.Module) -> None:
s = str(path)
for name, lineno, fp in _iter_code_units(tree):
self.fingerprints[fp].append((s, name, lineno))
def duplications(self) -> List[Dict[str, object]]:
results = []
for fp, items in self.fingerprints.items():
if len(items) < 2:
continue
files = {f for f, _n, _l in items}
names = {n for _f, n, _l in items}
# Doppel-Definition in derselben Zeile/Datei = Rebind, kein Dup
if len(files) == 1 and len(names) == 1:
continue
results.append({
"kind": "duplicate",
"occurrences": [
{"file": f, "name": n, "line": l} for f, n, l in items
],
})
return results
# ── Toter-Pfad-Audit ──────────────────────────────────────────────────────
class DeadCodeAudit:
def __init__(self, dir_path: Path) -> None:
self.dir_path = dir_path
self.defined: Dict[str, List[str]] = defaultdict(list)
self.called: set = set()
# Namen, die bereits mit `# TODO: DEAD CODE - F071` markiert sind =
# "dokumentiert tot" → werden NICHT als neue Befunde gemeldet.
self._documented_dead: set = set()
@staticmethod
def _is_marked_dead(src_lines: List[str], lineno: int) -> bool:
"""Ist die Funktions-Zeile (1-basiert) direkt mit dem F071-Marker
versehen? Die def-Zeile bei lineno → 0-basierter Index lineno-1;
der Marker liegt genau eine Zeile darüber."""
prev = lineno - 2
return prev >= 0 and "TODO: DEAD CODE - F071" in src_lines[prev]
def _collect_marked_names(self) -> None:
"""Sammle alle Funktions-Namen, die bereits den F071-Marker tragen."""
for path in self.dir_path.rglob("*" + TARGET_EXT):
if "tests" in path.parts or "__pycache__" in path.parts:
continue
try:
tree = _parse_file(path)
with path.open(encoding="utf-8") as f:
src_lines = f.readlines()
except (OSError, SyntaxError):
continue
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
if self._is_marked_dead(src_lines, node.lineno):
self._documented_dead.add(node.name)
def collect(self) -> None:
# Call-Graph über die GESAMTE plugin/-Baum (inkl. Tests + Attribute),
# damit Cross-File-Aufrufe aus adapter.py/rc_tools.py UND
# Property/dot-Access mitzählen. Ein Name gilt als "referenziert",
# wenn er IRGENDWO als Name-Load, Attribut-Load oder Import vorkommt.
scan_root = self.dir_path.parent if self.dir_path.name == "archivar" else self.dir_path
# Sammle bereits dokumentiert-tote Funktionen (F071-Marker) zuerst
self._collect_marked_names()
for path in scan_root.rglob("*" + TARGET_EXT):
if "__pycache__" in path.parts:
continue
try:
tree = _parse_file(path)
except (SyntaxError, OSError):
continue
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
# Property-Decorator-Funktionen sind Attribute, kein Code
self.defined[node.name].append(str(path))
# Referenz-Erfassung: überall wo der Name auftaucht
if isinstance(node, ast.Name):
self.called.add(node.id)
elif isinstance(node, ast.Attribute):
self.called.add(node.attr)
elif isinstance(node, ast.ImportFrom):
for a in node.names:
self.called.add(a.asname or a.name)
elif isinstance(node, ast.Import):
for a in node.names:
self.called.add(a.asname or a.name.split(".")[-1])
def dead_suspects(self) -> List[Tuple[str, List[str]]]:
suspects = []
for name, files in self.defined.items():
if name.startswith(PRIVATE_PREFIXES) or name in ("main",):
continue
# Bereits dokumentiert-tote Funktionen (F071-Marker) nicht erneut
# als neuen Befund melden.
if name in self._documented_dead:
continue
# Referenziert = taucht als Attribut/Name/Import im Call-Graph auf
# (auch `self.name` / `x.name` / `from m import name`).
if name in self.called:
continue
# Nur Befunde melden, deren Dateien unter dem Zielverzeichnis
# liegen UND nicht in tests/-Unterordnern (Test-Helper wie
# teardown_method sind kein toter Produktions-Code).
target = str(self.dir_path.resolve())
relevant = []
for f in files:
p = Path(f)
if "tests" in p.parts:
continue
if str(p.parent.resolve()).startswith(target):
relevant.append(f)
if not relevant:
continue
suspects.append((name, sorted(relevant)))
return suspects
# ── CLI / Report ─────────────────────────────────────────────────────
def _human_report(dir_, dups, naming_rows, dead) -> str:
lines = [f"# F071 Refactor-Audit: {dir_}"]
if not dups and not naming_rows and not dead:
lines.append("")
lines.append("Keine Befunde. Refactor-Disziplin OK.")
return "\n".join(lines)
if dups:
lines += ["", f"## Duplikate ({len(dups)})"]
for d in dups:
occ = "; ".join(
f"{o['name']}@{o['file']}:{o['line']}" for o in d["occurrences"]
)
lines.append(f"- {occ}")
if naming_rows:
lines += ["", "## Wiederkehrende Naming-Konventionen"]
for name, kind, cnt, where in naming_rows:
lines.append(f"- [{kind}] {name} ({cnt}x, z.B. {where})")
if dead:
lines += ["", "## Unreferenzierte Pfade (Verdacht)"]
for name, files in dead:
lines.append(
f"- {name} (definiert in {', '.join(files)})"
" -> markieren mit # TODO: DEAD CODE - F071"
)
lines.append("")
lines.append("Hinweis: DEAD-Code-Befunde sind Verdacht. Verifiziert tote "
"Pfade im Code mit `# TODO: DEAD CODE - F071` markieren, "
"NICHT automatisch löschen.")
return "\n".join(lines)
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dir", default=DEFAULT_DIR)
parser.add_argument("--include-tests", action="store_true",
help="tests/-Unterordner MIT einbeziehen")
parser.add_argument("--json", action="store_true")
args = parser.parse_args(argv)
dir_path = Path(args.dir)
if not dir_path.is_dir():
print(f"FEHLER: Verzeichnis existiert nicht: {dir_path}", file=sys.stderr)
return 3
dup_audit = DuplicateAudit()
naming = NamingAudit()
py_files = sorted(dir_path.rglob("*" + TARGET_EXT))
for path in py_files:
if _should_skip_dir(path.parent, args.include_tests):
continue
try:
tree = _parse_file(path)
except (SyntaxError, OSError) as e:
print(f"Übersprungen: {path} ({e})", file=sys.stderr)
continue
dup_audit.add_units(path, tree)
naming.audit_module(path, tree)
dups = dup_audit.duplications()
naming_rows = naming.consolidated()
dead_audit = DeadCodeAudit(dir_path)
dead_audit.collect()
dead = dead_audit.dead_suspects()
if args.json:
print(json.dumps({
"dir": str(dir_path),
"duplicates": dups,
"naming_findings": naming_rows,
"dead_code_suspects": dead,
}, ensure_ascii=False, indent=2))
return 0
print(_human_report(dir_path, dups, naming_rows, dead))
if dups:
return 1
if naming_rows or dead:
return 2
return 0
if __name__ == "__main__":
sys.exit(main())
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env bash
# F070 — Vertrags-Test-Runner Plugin ↔ Hermes-Core.
#
# Führt den Contract-Test (tests/contract/test_contract_framework.py) aus.
# Nutzt den Python-Interpreter des Hermes-Core-venv (P-029: .45-Plugin
# nur via venv-Python testen), mit Fallback auf system-python.
#
# @implements: [F-070]
set -uo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# venv-Python des Hermes-Core bevorzugen (P-029: snowballstemmer/faiss nur dort)
CANDIDATES=(
"$HOME/.hermes/hermes-agent/venv/bin/python"
"$HOME/.local/share/pipx/venvs/hermes-agent/bin/python"
"/usr/local/lib/hermes-agent/venv/bin/python"
)
PY=""
for cand in "${CANDIDATES[@]}"; do
if [ -x "$cand" ]; then PY="$cand"; break; fi
done
if [ -z "$PY" ]; then PY="$(command -v python3 || echo python3)"; fi
echo "[f070] Python: $PY"
echo "[f070] Repo: $REPO_ROOT"
cd "$REPO_ROOT"
PYTEST_RC=99
CLI_RC=99
# 1) pytest-basiert (Hauptpfad)
echo "[f070] == pytest: tests/contract/test_contract_framework.py =="
if "$PY" -m pytest tests/contract/test_contract_framework.py -q -p no:cacheprovider 2>&1; then
PYTEST_RC=0
else
PYTEST_RC=$?
fi
echo "[f070] pytest exit=$PYTEST_RC"
# 2) Standalone-CLI (Runner-Pfad) — erzeugt den Mensch-lesbaren Contract-Bericht
echo "[f070] == Standalone: python tests/contract/test_contract_framework.py =="
if "$PY" tests/contract/test_contract_framework.py 2>&1; then
CLI_RC=0
else
CLI_RC=$?
fi
echo "[f070] standalone exit=$CLI_RC"
# Exit: Fail, wenn einer der beiden Pfade fehlschlägt.
if [ "$PYTEST_RC" -ne 0 ] || [ "$CLI_RC" -ne 0 ]; then
echo "[f070] 🔴 Contract-Test FEHLGESCHLAGEN (pytest=$PYTEST_RC, cli=$CLI_RC)"
exit 1
fi
echo "[f070] 🟢 Contract-Test bestanden (pytest + Standalone)."
+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}"