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:
@@ -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())
|
||||
Executable
+58
@@ -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)."
|
||||
Reference in New Issue
Block a user