#!/usr/bin/env python3 """Audit locked official kinematics/recovery oracle inputs for K8-REL-10.""" from __future__ import annotations import argparse import hashlib import json import subprocess from pathlib import Path from typing import Any CONTEXT = Path("context-lock.json") KIN_CLOSURE = Path("coverage/kinematics-source-closure.report.json") KIN_ORACLE = Path("coverage/kinematics-oracle.report.json") RECOVERY = Path("coverage/workspace-recovery.report.json") COMPATIBILITY = Path("coverage/compatibility-matrix.report.json") GATE = Path("coverage/release-candidate-gate.report.json") INTAKE = Path("coverage/release-remediation-intake.report.json") OUTPUT = Path("coverage/official-oracle-remediation.report.json") def canonical(value: Any) -> str: return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")) def digest(value: Any) -> str: return hashlib.sha256(canonical(value).encode("utf-8")).hexdigest() def file_digest(path: Path) -> str | None: if not path.is_file(): return None handle = hashlib.sha256() with path.open("rb") as stream: for block in iter(lambda: stream.read(1024 * 1024), b""): handle.update(block) return handle.hexdigest() def read_json(root: Path, path: Path) -> tuple[dict[str, Any], str | None]: try: value = json.loads((root / path).read_text(encoding="utf-8")) if not isinstance(value, dict): raise ValueError(f"{path} must contain an object") return value, None except (OSError, UnicodeError, json.JSONDecodeError, ValueError) as exc: return {}, str(exc) def artifact(root: Path, path: Path, role: str) -> dict[str, Any]: full = root / path sha = file_digest(full) if sha is None: return {"path": path.as_posix(), "role": role, "status": "missing"} return {"path": path.as_posix(), "role": role, "status": "present", "bytes": full.stat().st_size, "sha256": sha} def locked_path_exists(root: Path, relative: str) -> bool: try: result = subprocess.run( ["git", "-C", str(root / "linuxcnc"), "cat-file", "-e", f"HEAD:{relative}"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, ) except OSError: return False return result.returncode == 0 def locked_head(root: Path) -> str | None: try: return subprocess.check_output(["git", "-C", str(root / "linuxcnc"), "rev-parse", "HEAD"], text=True).strip() except (OSError, subprocess.CalledProcessError): return None def generate(root: Path, output: Path = OUTPUT) -> dict[str, Any]: root = root.resolve() paths = (CONTEXT, KIN_CLOSURE, KIN_ORACLE, RECOVERY, COMPATIBILITY, GATE, INTAKE) documents: dict[Path, dict[str, Any]] = {} errors: dict[str, str] = {} for path in paths: documents[path], error = read_json(root, path) if error: errors[path.as_posix()] = error lock = documents[CONTEXT] closure = documents[KIN_CLOSURE] oracle = documents[KIN_ORACLE] recovery = documents[RECOVERY] compatibility = documents[COMPATIBILITY] gate = documents[GATE] intake = documents[INTAKE] context_id = lock.get("context_id") source_sha = lock.get("linuxcnc_source_sha") actual_head = locked_head(root) kin_root = "linuxcnc/unit_tests/kinematics" recovery_roots = ["linuxcnc/unit_tests/recovery", "linuxcnc/tests/recovery"] kin_present = locked_path_exists(root, kin_root) recovery_present = {path: locked_path_exists(root, path) for path in recovery_roots} matrixkins = closure.get("tests", {}).get("files", []) if isinstance(closure.get("tests"), dict) else [] matrixkins_candidate = [ {"path": row.get("path"), "sha256": row.get("sha256"), "official_unit_test": row.get("official_unit_test")} for row in matrixkins ] recovery_oracle = recovery.get("oracle", {}) checks = { "locked_source_commit": {"status": "verified" if source_sha and actual_head == source_sha else "blocked", "expected": source_sha, "actual": actual_head}, "kinematics_official_root": {"status": "verified" if not kin_present and kin_root in closure.get("missing_required_test_roots", []) else "blocked", "path": kin_root, "present": kin_present}, "recovery_official_root": {"status": "verified" if not any(recovery_present.values()) and recovery_oracle.get("status") == "blocked" else "blocked", "paths": recovery_present}, "candidate_tests_not_promoted": {"status": "verified" if matrixkins_candidate and all(row.get("official_unit_test") is False for row in matrixkins_candidate) else "blocked", "count": len(matrixkins_candidate)}, "no_official_goldens_generated": {"status": "verified" if oracle.get("ready_count") == 0 and oracle.get("status") == "blocked" else "blocked", "ready_count": oracle.get("ready_count"), "oracle_status": oracle.get("status")}, "release_stop_preserved": {"status": "verified" if gate.get("release_action") == "STOP_RELEASE" and gate.get("candidate_eligible") is False and gate.get("blocked_count") == 6 and intake.get("release_action") == "STOP_RELEASE" else "blocked", "release_action": "STOP_RELEASE" if gate.get("release_action") == "STOP_RELEASE" else None}, "context_consistency": {"status": "verified" if context_id and compatibility.get("context_id") == context_id and gate.get("context_id") == context_id else "blocked", "context_id": context_id}, } checks_ok = not errors and all(value["status"] == "verified" for value in checks.values()) report: dict[str, Any] = { "schema": "official-oracle-remediation.v1", "context_id": context_id, "task_id": "K8-REL-10", "status": "complete" if checks_ok else "blocked", "remediation_status": "blocked_missing_locked_inputs", "release_decision": "blocked_not_release_candidate", "release_action": "STOP_RELEASE", "candidate_eligible": False, "locked_source": { "linuxcnc_source_sha": source_sha, "actual_head": actual_head, "kinematics_root": {"path": kin_root, "present": kin_present}, "recovery_roots": recovery_present, }, "oracle_inventory": { "kinematics_samples": oracle.get("sample_count", 0), "kinematics_ready": oracle.get("ready_count", 0), "kinematics_blocked": oracle.get("blocked_count", 0), "recovery_blocked_samples": recovery_oracle.get("blocked_samples", []), "matrixkins_candidate_files": matrixkins_candidate, "official_inputs_added": 0, "official_goldens_added": 0, }, "checks": checks, "inputs": [artifact(root, path, path.stem.replace("-", "_")) for path in paths], "review_policy": { "required_to_unblock": ["official kinematics unit-test root in a locked source", "official recovery oracle inputs or approved contract replacement", "native/WASM comparison rerun", "new context_id if source or schema changes"], "forbidden": ["promote_matrixkins_to_official", "generate_fake_goldens", "delete_blocked_samples", "lower_tolerances", "overwrite_context_lock_in_place"], }, "errors": errors, "report_sha256": None, } report["report_sha256"] = digest({key: value for key, value in report.items() if key != "report_sha256"}) destination = output if output.is_absolute() else root / output destination.parent.mkdir(parents=True, exist_ok=True) destination.write_text(json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8") return report def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo-root", type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument("--output", type=Path, default=OUTPUT) args = parser.parse_args() report = generate(args.repo_root, args.output) print("official_oracle_remediation=" + report["status"] + " release=" + report["release_action"] + " added=" + str(report["oracle_inventory"]["official_inputs_added"])) return 0 if __name__ == "__main__": raise SystemExit(main())