#!/usr/bin/env python3 """Generate deterministic native/WASM evidence for tripod kinematics.""" from __future__ import annotations import argparse import hashlib import json import re import subprocess from pathlib import Path INPUTS = { "source": "linuxcnc/src/emc/kinematics/tripodkins.c", "config": "linuxcnc/configs/sim/tklinuxcnc/tripod.ini", "hal": "linuxcnc/lib/hallib/tripodsim.hal", "implementation": "wasm-core/src/sim_kinematics.c", "header": "wasm-core/include/sim_kinematics.h", "test": "wasm-core/tests/sim_kinematics_test.c", } def sha256(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() def run_json(command: list[str], root: Path) -> dict[str, object]: completed = subprocess.run(command, cwd=root, check=False, text=True, capture_output=True) if completed.returncode != 0: raise RuntimeError(f"{command[0]} exited {completed.returncode}: {completed.stderr.strip()}") for line in reversed(completed.stdout.splitlines()): if line.lstrip().startswith("{"): return json.loads(line) raise RuntimeError(f"{command[0]} did not emit JSON") def hal_geometry(text: str) -> dict[str, float]: values: dict[str, float] = {} for name, value in re.findall(r"^setp\s+tripodkins\.(Bx|Cx|Cy)\s+([-+0-9.eE]+)\s*$", text, re.M): values[name] = float(value) return values def generate(root: Path, output: Path) -> dict[str, object]: root = root.resolve() native_all = run_json([str(root / "build-native/sim_kinematics_test")], root) wasm_all = run_json(["node", str(root / "build-wasm/sim_kinematics_wasm_test.js")], root) native = {"tripod": native_all["tripod"], "boundaries": native_all["delta_edges"]["tripod"]} wasm = {"tripod": wasm_all["tripod"], "boundaries": wasm_all["delta_edges"]["tripod"]} native_text = json.dumps(native, sort_keys=True, separators=(",", ":")) wasm_text = json.dumps(wasm, sort_keys=True, separators=(",", ":")) source_records = {name: {"path": path, "sha256": sha256(root / path)} for name, path in INPUTS.items()} config_text = (root / INPUTS["config"]).read_text(encoding="utf-8") hal_text = (root / INPUTS["hal"]).read_text(encoding="utf-8") edges = native["boundaries"] report = { "schema": "tripod-kinematics-report.v1", "status": "partial", "implementation_status": "verified", "source_records": source_records, "configuration_candidate": { "path": INPUTS["config"], "kinematics": "tripodkins", "joints": 3, "coordinates": "XYZ", "scan": "KINEMATICS = tripodkins" in config_text and "JOINTS = 3" in config_text, "hal_library": INPUTS["hal"], }, "geometry": {"base_A": [0.0, 0.0, 0.0], "base_B": [10.0, 0.0, 0.0], "base_C": [5.0, 7.071, 0.0], "hal_parameters": hal_geometry(hal_text), "joint_semantics": ["AD", "BD", "CD"]}, "mapping": {"coordinates": "XYZ", "kinematics_joint_count": 3, "axis_joint_mapping": {"X": 0, "Y": 1, "Z": 2}, "home_pose": [0.0, 0.0, 1.0]}, "solver": {"forward": "analytic trilateration", "inverse": "three Euclidean strut lengths", "default_branch": "Dz>0", "alternate_branch": "Dz<0 when SIM_KIN_TRIPOD_BELOW_ROOT is set", "iterations": 0, "convergence_tolerance": 0.0}, "workspace_and_boundaries": {"nominal": native["tripod"], "alternate_pose": edges["alternate_pose"], "root_branch": edges["branch"], "alternate_branch": edges["alternate_branch"], "no_solution_error": edges["no_solution"], "base_plane_singular_error": edges["singular"], "joint_limit_error": edges["limit_error"], "geometry_error": edges["geometry_error"], "iterations": edges["iterations"]}, "samples": {"native": native, "wasm": wasm, "byte_identical_json": native_text == wasm_text, "state_hash_identical": native["tripod"]["state_hash"] == wasm["tripod"]["state_hash"]}, "native_wasm": {"status": "passed", "native_command": "build-native/sim_kinematics_test", "wasm_command": "node build-wasm/sim_kinematics_wasm_test.js"}, "oracle": {"status": "blocked", "reason": "linuxcnc/unit_tests/kinematics is absent from the locked source", "blocked_samples": ["nominal above-root", "alternate below-root", "triangle-inequality no-solution", "base-plane singular", "joint-limit", "degenerate base geometry"]}, } report["report_sha256"] = hashlib.sha256(json.dumps(report, sort_keys=True, separators=(",", ":")).encode()).hexdigest() output.parent.mkdir(parents=True, exist_ok=True) output.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=Path("coverage/tripod-kinematics.report.json")) args = parser.parse_args() report = generate(args.repo_root, args.repo_root / args.output) print(f"tripod_kinematics={report['status']} native_wasm={report['native_wasm']['status']} oracle={report['oracle']['status']}") return 0 if __name__ == "__main__": raise SystemExit(main())