#!/usr/bin/env python3 """Replay synthetic bytes through sg_decode_sense; never opens a device.""" import argparse import hashlib import json import pathlib import platform import shutil import subprocess from datetime import datetime, timezone ROOT = pathlib.Path(__file__).resolve().parent def check(results, fixtures): if results.get("kind") != "synthetic-offline-decoder-observations": raise ValueError("Wrong evidence kind") rows = results.get("observations", []) if [r.get("id") for r in rows] != [f["id"] for f in fixtures]: raise ValueError("Missing, reordered or duplicate observations") for row, fixture in zip(rows, fixtures): if row.get("hex") != fixture["hex"] or row.get("returncode") != 0: raise ValueError(f"Input or execution mismatch: {fixture['id']}") if row.get("received_bytes") != len(bytes.fromhex(fixture["hex"])): raise ValueError("Received-length mismatch") output = row.get("stdout", "") if row.get("stderr") or not all(s in output for s in fixture["contains"]): raise ValueError(f"Missing expected output: {fixture['id']}") if any(s in output for s in fixture["excludes"]): raise ValueError(f"Unexpected output: {fixture['id']}") return len(rows) def capture(fixtures): executable = shutil.which("sg_decode_sense") if not executable: raise RuntimeError("sg_decode_sense is required; no device access is needed") version = subprocess.run([executable, "--version"], capture_output=True, text=True, check=True) rows = [] for fixture in fixtures: result = subprocess.run([executable, *fixture["hex"].split()], capture_output=True, text=True, timeout=10) rows.append({"id": fixture["id"], "hex": fixture["hex"], "received_bytes": len(bytes.fromhex(fixture["hex"])), "returncode": result.returncode, "stdout": result.stdout, "stderr": result.stderr}) return {"schema_version": 1, "kind": "synthetic-offline-decoder-observations", "generated_at": datetime.now(timezone.utc).isoformat(), "platform": platform.platform(), "python": platform.python_version(), "executable": executable, "executable_sha256": hashlib.sha256(pathlib.Path(executable).read_bytes()).hexdigest(), "decoder_version": (version.stdout + version.stderr).strip(), "limitations": "Invented buffers, not device responses. One installed decoder build; not a standards-conformance or hardware test.", "observations": rows} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--verify", type=pathlib.Path) parser.add_argument("--output", type=pathlib.Path) args = parser.parse_args() fixtures = json.loads((ROOT / "fixtures.json").read_text()) results = json.loads(args.verify.read_text()) if args.verify else capture(fixtures) count = check(results, fixtures) if args.verify: print(f"PASS: {count} retained offline observations") elif args.output: args.output.write_text(json.dumps(results, indent=2) + "\n") print(f"PASS: {count} native offline observations") else: print(json.dumps(results, indent=2)) if __name__ == "__main__": main()