#!/usr/bin/env python3 """Build the Prod2U door-temperature final firmware delivery package. This is a deterministic wrapper that collects: - the canonical bitstream from an explicit TD root, - original and provenance-augmented TD reports, - source-closure comparison across artifact/matrix/final dev commits, - selected TD stage evidence (syn/phy/bitgen reports and logs), - source/contracts/TD inputs, - generated host contract and golden vectors, - verification receipts (when available), - package manifest, SHA-256 sums, and an external selftest sidecar. It does not access COM/JTAG or program hardware. """ from __future__ import annotations import argparse import hashlib import json import shutil import subprocess import sys import zipfile from datetime import datetime, timezone from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parents[1] TD_STAGE_SUFFIXES = {".rpt", ".timing", ".area", ".qor", ".log", ".logw"} REPO_TD_INPUTS = [ "td/prod2u_p4_normal_v3.prj", "td/syn/prod2u_p4_normal_v3.tcl", "td/phy/prod2u_p4_normal_v3.tcl", "td/bitgen/prod2u_p4_normal_v3.tcl", ] class PackagingError(RuntimeError): """Raised when the firmware package cannot be produced safely.""" def _sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _sha256_bytes(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def _read_json(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8-sig")) def _git_show_file(repo_root: Path, commit: str, relative_path: str) -> bytes: """Return the contents of a tracked path at a specific commit.""" completed = subprocess.run( ["git", "-C", str(repo_root), "show", f"{commit}:{relative_path}"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, ) if completed.returncode != 0: raise PackagingError( f"git show failed for {commit}:{relative_path}: {completed.stderr.decode('utf-8', errors='ignore').strip()}" ) return completed.stdout def _resolve_path(path: Path) -> Path: return Path(path).expanduser().resolve() def _inside(root: Path, candidate: Path) -> bool: """Return True if candidate is root or under root.""" root = _resolve_path(root) candidate = _resolve_path(candidate) try: candidate.relative_to(root) return True except ValueError: return False def _validate_td_root( *, td_root: Path, bitstream_path: Path, td_report_path: Path, ) -> None: """Ensure bitstream and report belong to the selected TD root.""" if not _inside(td_root, bitstream_path): raise PackagingError(f"bitstream {bitstream_path} is outside selected td_root {td_root}") if not _inside(td_root, td_report_path): raise PackagingError(f"td report {td_report_path} is outside selected td_root {td_root}") def _bitstream_path_from_td_root(td_root: Path) -> Path: return _resolve_path(td_root / "td" / "prod2u_p4_normal_v3" / "bitgen" / "prod2u_p4_normal_v3.bit") def _report_path_from_td_root(td_root: Path) -> Path: return _resolve_path(td_root / "report.json") def generate_source_closure_comparison( *, td_report: dict[str, Any], artifact_commit: str, matrix_commit: str, final_dev_commit: str, repo_root: Path = ROOT, ) -> dict[str, Any]: """Compare synthesis inputs across artifact, matrix, and final dev commits.""" inputs = td_report.get("synthesis_input_manifest", {}).get("inputs", {}) if not inputs: raise PackagingError("TD report has no synthesis_input_manifest.inputs") entries: list[dict[str, Any]] = [] production_changed_paths: list[str] = [] all_same = True for relative_path, artifact_sha in sorted(inputs.items()): row: dict[str, Any] = {"path": relative_path, "artifact_expected_sha256": artifact_sha} values: list[str | None] = [] for commit, key in [ (artifact_commit, "artifact_source_sha256"), (matrix_commit, "matrix_commit_sha256"), (final_dev_commit, "final_dev_commit_sha256"), ]: try: content = _git_show_file(repo_root, commit, relative_path) sha = _sha256_bytes(content) except PackagingError: sha = None row[key] = sha values.append(sha) if values[0] == values[1] == values[2] and values[0] is not None: row["status"] = "same" else: row["status"] = "different" all_same = False if values[0] != values[2]: production_changed_paths.append(relative_path) entries.append(row) comparison_text = json.dumps( { "artifact_source_commit": artifact_commit, "matrix_commit": matrix_commit, "final_dev_commit": final_dev_commit, "source_closure_equal": all_same, "production_changed_paths": production_changed_paths, "entries": entries, }, sort_keys=True, ) source_set_sha256 = _sha256_bytes(comparison_text.encode("utf-8")) return { "schema": "prod2u-source-closure-comparison-v1", "artifact_source_commit": artifact_commit, "matrix_commit": matrix_commit, "final_dev_commit": final_dev_commit, "source_closure_equal": all_same, "production_changed_paths": production_changed_paths, "source_set_sha256": source_set_sha256, "inputs": entries, } def generate_td_provenance( *, original_report: dict[str, Any], artifact_commit: str, source_closure_comparison_sha256: str, bitstream_sha256: str, matrix_run_id: str | None, ) -> dict[str, Any]: """Bind the original TD run to the current matrix and source closure.""" return { "schema": "prod2u-td-provenance-v1", "status": "bound_by_source_closure_comparison", "artifact_source_commit": artifact_commit, "original_td_run_id": original_report.get("run_id"), "original_placeholder_verification_run_id": original_report.get("verification_run_id"), "matrix_run_id": matrix_run_id, "source_closure_comparison_sha256": source_closure_comparison_sha256, "bitstream_sha256": bitstream_sha256, "original_report_path": "td/original-final_td_report.json", "project_config_sha256": original_report.get("project_config_sha256"), "td_source_manifest_sha256": original_report.get("td_source_manifest_sha256"), "synthesis_input_manifest_sha256": original_report.get("synthesis_input_manifest", {}).get("sha256"), } def _add_file(zipf: zipfile.ZipFile, src: Path, arcname: str, sha256_entries: list[str]) -> None: zipf.write(src, arcname) sha256_entries.append(f"{_sha256_file(src)} {arcname}") def _add_text(zipf: zipfile.ZipFile, text: str, arcname: str, sha256_entries: list[str]) -> None: payload = text.encode("utf-8") zipf.writestr(arcname, payload) sha256_entries.append(f"{_sha256_bytes(payload)} {arcname}") def _collect_td_stage_files(td_root: Path) -> list[tuple[Path, str]]: """Collect allowed evidence files from the selected TD build stages.""" collected: list[tuple[Path, str]] = [] stages = ["syn", "phy", "bitgen"] for stage in stages: stage_dir = _resolve_path(td_root / "td" / "prod2u_p4_normal_v3" / stage) if not stage_dir.is_dir(): continue for item in stage_dir.iterdir(): if item.is_file() and item.suffix.casefold() in TD_STAGE_SUFFIXES: collected.append((item, f"td/{stage}/{item.name}")) return collected def _selftest_package( *, zip_path: Path, expected_manifest: dict[str, Any], td_root: Path, ) -> dict[str, Any]: """Verify the built firmware package before writing the sidecar.""" failures: list[str] = [] with zipfile.ZipFile(zip_path, "r", allowZip64=True) as zipf: names = set(zipf.namelist()) required = { "fw.bit", "BITSTREAM-SHA256.txt", "ARTIFACT-SOURCE-COMMIT.txt", "MATRIX-COMMIT.txt", "FINAL-DEV-COMMIT.txt", "SOURCE-CLOSURE-UNCHANGED.txt", "PACKAGE-MANIFEST.json", "SHA256SUMS.txt", "td/original-final_td_report.json", "td/TD-PROVENANCE.json", "evidence/SOURCE-CLOSURE-COMPARISON.json", "project.json", "config/source_closure.json", } missing = sorted(required - names) if missing: failures.append(f"missing_required_files:{missing}") bad = zipf.testzip() if bad is not None: failures.append(f"crc_failed:{bad}") manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json")) if manifest["bitstream_sha256"] != expected_manifest["bitstream_sha256"]: failures.append("bitstream_sha_manifest_mismatch") # Detect stale repo TD logs from ROOT/td that should not be present for name in names: if name.startswith("td/") and "td_20260630" in name: failures.append(f"stale_td_log_in_package:{name}") return { "status": "fail" if failures else "pass", "failures": failures, "package_path": str(zip_path), "package_sha256": _sha256_file(zip_path), "td_root": str(td_root), } def build_firmware_package( *, output_dir: Path, package_name: str | None, td_root: Path, artifact_commit: str, matrix_commit: str, final_dev_commit: str, source_closure_unchanged: bool, bitstream_path: Path | None = None, td_report_path: Path | None = None, matrix_receipt_path: Path | None = None, matrix_run_id: str | None = None, ) -> tuple[Path, Path]: """Build and selftest the final firmware ZIP.""" td_root = _resolve_path(td_root) if bitstream_path is None: bitstream_path = _bitstream_path_from_td_root(td_root) if td_report_path is None: td_report_path = _report_path_from_td_root(td_root) bitstream_path = _resolve_path(bitstream_path) td_report_path = _resolve_path(td_report_path) _validate_td_root(td_root=td_root, bitstream_path=bitstream_path, td_report_path=td_report_path) if not bitstream_path.is_file(): raise FileNotFoundError(f"bitstream not found: {bitstream_path}") if not td_report_path.is_file(): raise FileNotFoundError(f"TD report not found: {td_report_path}") td_report = _read_json(td_report_path) bitstream_sha256 = _sha256_file(bitstream_path) # Strong binding checks report_bitstream_sha = td_report.get("bitstream_sha256") if report_bitstream_sha and report_bitstream_sha != bitstream_sha256: raise PackagingError( f"TD report bitstream_sha256 {report_bitstream_sha} does not match actual {bitstream_sha256}" ) report_commit = td_report.get("commit_full") or td_report.get("commit") if report_commit and report_commit != artifact_commit: raise PackagingError( f"TD report commit {report_commit} does not match artifact_source_commit {artifact_commit}" ) report_project_sha = td_report.get("project_config_sha256") current_project_sha = _sha256_file(ROOT / "projects" / "prod2u-door-temp" / "project.json") if report_project_sha and report_project_sha != current_project_sha: raise PackagingError( f"TD report project_config_sha256 {report_project_sha} does not match current {current_project_sha}" ) comparison = generate_source_closure_comparison( td_report=td_report, artifact_commit=artifact_commit, matrix_commit=matrix_commit, final_dev_commit=final_dev_commit, repo_root=ROOT, ) if not source_closure_unchanged and comparison["source_closure_equal"]: # Caller claimed changed but comparison says same: trust explicit flag pass if source_closure_unchanged and not comparison["source_closure_equal"]: raise PackagingError( f"source_closure_unchanged requested but comparison differs: {comparison['production_changed_paths']}" ) comparison_json = json.dumps(comparison, indent=2, sort_keys=True) + "\n" comparison_sha256 = _sha256_bytes(comparison_json.encode("utf-8")) provenance = generate_td_provenance( original_report=td_report, artifact_commit=artifact_commit, source_closure_comparison_sha256=comparison_sha256, bitstream_sha256=bitstream_sha256, matrix_run_id=matrix_run_id, ) provenance_json = json.dumps(provenance, indent=2, sort_keys=True) + "\n" provenance_sha256 = _sha256_bytes(provenance_json.encode("utf-8")) timing = td_report.get("timing", {}) resources_section = td_report.get("resources", {}) utilization = resources_section.get("utilization", {}) manifest: dict[str, Any] = { "schema": "prod2u-door-temp-final-package-manifest-v2", "package_name": package_name or f"prod2u-door-temp-final-{artifact_commit[:8]}-{bitstream_sha256[:8]}", "status": "VERIFIED_OFFLINE", "created_at": datetime.now(timezone.utc).isoformat(), "verification_scope": "offline", "hardware_validation": "not_run", "artifact_source_commit": artifact_commit, "matrix_commit": matrix_commit, "final_dev_commit": final_dev_commit, "td_run_id": td_report.get("run_id"), "matrix_run_id": matrix_run_id, "source_closure_unchanged": comparison["source_closure_equal"], "project_config_sha256": current_project_sha, "td_source_manifest_sha256": td_report.get("td_source_manifest_sha256"), "synthesis_input_manifest_sha256": td_report.get("synthesis_input_manifest", {}).get("sha256"), "source_closure_comparison_sha256": comparison_sha256, "bitstream_sha256": bitstream_sha256, "matrix_receipt_sha256": _sha256_file(matrix_receipt_path) if matrix_receipt_path and matrix_receipt_path.is_file() else None, "original_td_receipt_sha256": _sha256_file(td_report_path), "td_provenance_sha256": provenance_sha256, "resources": { "lut": utilization.get("lut", {}).get("used"), "register": utilization.get("reg", {}).get("used"), "packed_slice": resources_section.get("packing", {}).get("total_slices"), "bram": utilization.get("bram", {}).get("used"), "dsp": utilization.get("dsp", {}).get("used"), }, "timing": { "fmax_mhz": timing.get("fmax_mhz"), "setup_slack_ns": timing.get("worst_setup_slack_ns"), "hold_slack_ns": timing.get("worst_hold_slack_ns"), }, } output_dir = _resolve_path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) name = manifest["package_name"] zip_path = output_dir / f"{name}.zip" if zip_path.exists(): zip_path.unlink() sha256_entries: list[str] = [] with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as zipf: # Bitstream and provenance _add_file(zipf, bitstream_path, "fw.bit", sha256_entries) _add_text(zipf, bitstream_sha256, "BITSTREAM-SHA256.txt", sha256_entries) _add_text(zipf, artifact_commit, "ARTIFACT-SOURCE-COMMIT.txt", sha256_entries) _add_text(zipf, matrix_commit, "MATRIX-COMMIT.txt", sha256_entries) _add_text(zipf, final_dev_commit, "FINAL-DEV-COMMIT.txt", sha256_entries) _add_text(zipf, "true" if comparison["source_closure_equal"] else "false", "SOURCE-CLOSURE-UNCHANGED.txt", sha256_entries) # Original TD report and provenance _add_file(zipf, td_report_path, "td/original-final_td_report.json", sha256_entries) _add_text(zipf, provenance_json, "td/TD-PROVENANCE.json", sha256_entries) # Selected TD stage evidence from the explicit TD root for src, arcname in _collect_td_stage_files(td_root): _add_file(zipf, src, arcname, sha256_entries) # Project contract and protocol _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "project.json", "project.json", sha256_entries) _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "requirements.zh-CN.md", "requirements.zh-CN.md", sha256_entries) _add_file(zipf, ROOT / "docs" / "prod2u-door-temp-protocol.zh-CN.md", "docs/prod2u-door-temp-protocol.zh-CN.md", sha256_entries) # Generated artifacts for gen in (ROOT / "src" / "generated").iterdir(): if gen.is_file(): _add_file(zipf, gen, f"src/generated/{gen.name}", sha256_entries) # Constraints for adc in (ROOT / "constraints").iterdir(): if adc.is_file(): _add_file(zipf, adc, f"constraints/{adc.name}", sha256_entries) # Tracked TD inputs from the repo (not the build root) for td_input in REPO_TD_INPUTS: src = ROOT / td_input if src.is_file(): _add_file(zipf, src, td_input, sha256_entries) # Source closure manifest _add_file(zipf, ROOT / "config" / "source_closure.json", "config/source_closure.json", sha256_entries) # Source-closure comparison _add_text(zipf, comparison_json, "evidence/SOURCE-CLOSURE-COMPARISON.json", sha256_entries) # Optional matrix receipt if matrix_receipt_path and matrix_receipt_path.is_file(): _add_file(zipf, matrix_receipt_path, "evidence/matrix-receipt.json", sha256_entries) # Manifest and SHA256SUMS manifest_text = json.dumps(manifest, indent=2, sort_keys=True) + "\n" _add_text(zipf, manifest_text, "PACKAGE-MANIFEST.json", sha256_entries) _add_text(zipf, "\n".join(sha256_entries) + "\n", "SHA256SUMS.txt", sha256_entries) selftest = _selftest_package(zip_path=zip_path, expected_manifest=manifest, td_root=td_root) if selftest["status"] != "pass": zip_path.unlink(missing_ok=True) raise PackagingError(f"firmware package selftest failed: {selftest['failures']}") selftest["package_selftest_status"] = "pass" selftest["manifest"] = manifest sidecar_path = output_dir / f"{name}.selftest.json" sidecar_path.write_text(json.dumps(selftest, indent=2, sort_keys=True) + "\n", encoding="utf-8") return zip_path, sidecar_path def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output-dir", type=Path, default=Path.home() / "Downloads" / "CPLD-firmware") parser.add_argument("--package-name", help="package base name (default from commit/bitstream)") parser.add_argument("--td-root", type=Path, required=True) parser.add_argument("--bitstream", type=Path, default=None) parser.add_argument("--td-report", type=Path, default=None) parser.add_argument("--artifact-commit", required=True) parser.add_argument("--matrix-commit", required=True) parser.add_argument("--final-dev-commit", required=True) parser.add_argument("--source-closure-unchanged", action="store_true") parser.add_argument("--matrix-receipt", type=Path, default=None) parser.add_argument("--matrix-run-id", default=None) args = parser.parse_args(argv) try: zip_path, sidecar_path = build_firmware_package( output_dir=args.output_dir, package_name=args.package_name, td_root=args.td_root, artifact_commit=args.artifact_commit, matrix_commit=args.matrix_commit, final_dev_commit=args.final_dev_commit, source_closure_unchanged=args.source_closure_unchanged, bitstream_path=args.bitstream, td_report_path=args.td_report, matrix_receipt_path=args.matrix_receipt, matrix_run_id=args.matrix_run_id, ) except (FileNotFoundError, PackagingError) as exc: print(f"error: {exc}", file=sys.stderr) return 1 print( json.dumps( {"status": "pass", "package": str(zip_path), "selftest": str(sidecar_path)}, indent=2, ) ) return 0 if __name__ == "__main__": raise SystemExit(main())