#!/usr/bin/env python3 """Check maturity-engine against the NetKingdom security layer model (§5, §11). This is an Engine (PIP). The checkable claims: - INTENT.md frontmatter declares the layer and governs (GH-DEC-2026-017 §1) - layer.yaml is derived: marked `derived: true`, `derived_from: INTENT.md`, and declares layer=engine, role=pip - both layer values are in §3's closed four-token vocabulary and are compared after an ASCII case fold (A9); nothing is re-spelled. A disagreement that survives the fold is reported as a finding, not resolved by precedence (A11) - neither form carries a standard_version (A12) - no pep_stance path - no catalogued Tooling client (OpenBao, key-cape, cluster) - sqlite3 is this PIP's own store and is allowed Exit 0 clean, 1 undeclared Tooling contact, 2 declaration malformed. """ from __future__ import annotations import argparse import ast import re import sys from pathlib import Path import yaml # §3 as amended (A9): closed, four tokens, compared after an ASCII case fold. LAYER_VOCABULARY = {"taxonomy", "tooling", "engine", "staff"} def _fold(value: object) -> str: """ASCII case-fold: two spellings of a token are one token.""" return str(value).strip().encode("ascii", "ignore").decode().lower() ROOT = Path(__file__).resolve().parents[1] SRC = ROOT / "src" / "maturity_engine" DECL = ROOT / "layer.yaml" INTENT = ROOT / "INTENT.md" TOOLING_IMPORTS = { "hvac": "OpenBao / Vault client", "bao": "OpenBao client", "kubernetes": "cluster client", "kubernetes_asyncio": "cluster client", "ldap3": "direct LDAP client (key-cape tooling)", "python_ldap": "direct LDAP client (key-cape tooling)", } def load_declaration() -> dict: if not DECL.exists(): print(f"FAIL: no declaration at {DECL.relative_to(ROOT)} (§11)", file=sys.stderr) raise SystemExit(2) try: data = yaml.safe_load(DECL.read_text()) except yaml.YAMLError as exc: print(f"FAIL: {DECL.name} is not parseable: {exc}", file=sys.stderr) raise SystemExit(2) from exc for key in ("layer", "role", "repository", "tooling_contacts", "derived", "derived_from"): if key not in data: print(f"FAIL: {DECL.name} missing required key '{key}' (§11)", file=sys.stderr) raise SystemExit(2) if data["derived"] is not True: print( f"FAIL: {DECL.name} must be marked 'derived: true' (§11, GH-DEC-2026-017 §1)", file=sys.stderr, ) raise SystemExit(2) if data["derived_from"] != "INTENT.md": print( f"FAIL: {DECL.name} derives from {data['derived_from']!r}; §11 names INTENT.md", file=sys.stderr, ) raise SystemExit(2) if "standard_version" in data: print( f"FAIL: {DECL.name} carries 'standard_version' — a layer declaration MUST NOT " "carry a standard version (GH-DEC-2026-017 §5, A12)", file=sys.stderr, ) raise SystemExit(2) if _fold(data["layer"]) not in LAYER_VOCABULARY: print( f"FAIL: {DECL.name} layer {data['layer']!r} is outside §3's closed vocabulary " f"{sorted(LAYER_VOCABULARY)} (case-insensitive)", file=sys.stderr, ) raise SystemExit(2) if _fold(data["layer"]) != "engine": print(f"FAIL: declared layer is {data['layer']!r}, expected 'engine'", file=sys.stderr) raise SystemExit(2) if _fold(data["role"]) != "pip": print(f"FAIL: declared role is {data['role']!r}, expected 'pip'", file=sys.stderr) raise SystemExit(2) if data.get("pep_stance"): print("FAIL: pep_stance is set; this engine is not PEP-shaped", file=sys.stderr) raise SystemExit(2) return data def intent_frontmatter() -> dict: text = INTENT.read_text() match = re.match(r"^---\n(.*?)\n---\n", text, re.DOTALL) if not match: print("FAIL: INTENT.md has no YAML frontmatter (§11)", file=sys.stderr) raise SystemExit(2) meta = yaml.safe_load(match.group(1)) if not isinstance(meta, dict): print("FAIL: INTENT.md frontmatter is not a mapping", file=sys.stderr) raise SystemExit(2) if "layer" not in meta: print( "FAIL: INTENT.md frontmatter has no 'layer:' key — that is the declaration (§11)", file=sys.stderr, ) raise SystemExit(2) if "standard_version" in meta: print( "FAIL: INTENT.md frontmatter carries 'standard_version' — a layer declaration " "MUST NOT carry a standard version (GH-DEC-2026-017 §5, A12)", file=sys.stderr, ) raise SystemExit(2) if _fold(meta["layer"]) not in LAYER_VOCABULARY: print( f"FAIL: INTENT.md layer {meta['layer']!r} is outside §3's closed vocabulary " f"{sorted(LAYER_VOCABULARY)} (case-insensitive)", file=sys.stderr, ) raise SystemExit(2) return meta def imported_modules(path: Path) -> set[str]: try: tree = ast.parse(path.read_text()) except SyntaxError: return set() found: set[str] = set() for node in ast.walk(tree): if isinstance(node, ast.Import): found.update(alias.name.split(".")[0] for alias in node.names) elif isinstance(node, ast.ImportFrom): if node.level == 0 and node.module: found.add(node.module.split(".")[0]) return found def scan() -> list[tuple[Path, str, str]]: hits: list[tuple[Path, str, str]] = [] for path in sorted(SRC.rglob("*.py")): for module in sorted(imported_modules(path)): if module in TOOLING_IMPORTS: hits.append((path, module, TOOLING_IMPORTS[module])) return hits def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--report", action="store_true") args = parser.parse_args() decl = load_declaration() intent = intent_frontmatter() # A11: the derived form MUST agree with the governing one. Case is folded # first (A9), so a mismatch here is a real layer disagreement — a finding # in its own right, reported rather than resolved away by precedence. if _fold(intent["layer"]) != _fold(decl["layer"]): print( f"FAIL: layer disagreement after case fold — INTENT.md (governs) " f"{intent['layer']!r} vs layer.yaml (derived) {decl['layer']!r}", file=sys.stderr, ) return 2 if _fold(intent.get("role", "")) != _fold(decl["role"]): print( f"FAIL: INTENT.md role {intent.get('role')!r} != layer.yaml {decl['role']!r}", file=sys.stderr, ) return 2 hits = scan() if hits: print("FAIL: catalogued Tooling-layer client in an Engine that does not own it", file=sys.stderr) for path, module, what in hits: print(f" {path.relative_to(ROOT)}: imports {module!r} — {what}", file=sys.stderr) return 1 if args.report: print( f"maturity-engine — layer {intent['layer']} (INTENT.md, governs), role {decl['role']}" ) print(f" layer.yaml: derived from {decl['derived_from']}, layer: {decl['layer']}") print(f" tooling contacts: {len(decl.get('tooling_contacts') or [])}") print(f" non-tooling clients: {len(decl.get('non_tooling_clients') or [])}") print(" pep_stance: none") else: print(f"OK: Engine/PIP declaration holds; no catalogued Tooling client in {SRC.relative_to(ROOT)}") return 0 if __name__ == "__main__": raise SystemExit(main())