#!/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] TOOLS = Path(__file__).resolve().parent if str(TOOLS) not in sys.path: sys.path.insert(0, str(TOOLS)) import package_provenance as pkg_prov # noqa: E402 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", ] # Round-9 door-percent base: locked immutable `dev` tip. OLD_BASELINE_COMMIT_DEFAULT = "d4f3df2549efeb1e9227f62d1d71c6179c9f9160" BASE_DEV_COMMIT_DEFAULT = OLD_BASELINE_COMMIT_DEFAULT try: from tools.package_provenance import release_task_slug as _release_task_slug except ImportError: # pragma: no cover from package_provenance import release_task_slug as _release_task_slug # type: ignore RELEASE_TASK_SLUG = _release_task_slug() 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 _mask_define_from_params(params_text: str, name: str) -> str: needle = f"`define {name} " for line in params_text.splitlines(): if line.startswith(needle): return line[len(needle) :].strip() raise PackagingError(f"missing `{name}` in prod2u_door_temp_params.vh") def _axis_mask_literal_from_values(values: list[Any], axis_count: int = 3) -> str: if len(values) != axis_count: raise PackagingError(f"axis mask length mismatch: expected {axis_count}, got {len(values)}") bits = "".join("1" if bool(v) else "0" for v in reversed(values)) return f"{axis_count}'b{bits}" def motor_polarity_config_identity(repo_root: Path | None = None) -> dict[str, Any]: """Fingerprint motor polarity masks from project.json and bind to params.vh. Fail-closed when checked-in params drift from the project contract. """ root = repo_root or ROOT project = _read_json(root / "projects" / "prod2u-door-temp" / "project.json") params_path = root / "src" / "generated" / "prod2u_door_temp_params.vh" params_text = params_path.read_text(encoding="utf-8") expected = { "limit_active_high_mask": _axis_mask_literal_from_values( list(project["limits"]["limit_active_high"]) ), "dir_close_level_mask": _axis_mask_literal_from_values( list(project["motors"]["dir_close_level"]) ), "close_limit_is_ls_mask": _axis_mask_literal_from_values( list(project["limits"]["close_limit_is_ls"]) ), } observed = { "limit_active_high_mask": _mask_define_from_params(params_text, "P4_LIMIT_ACTIVE_HIGH_MASK"), "dir_close_level_mask": _mask_define_from_params(params_text, "P4_DIR_CLOSE_LEVEL_MASK"), "close_limit_is_ls_mask": _mask_define_from_params(params_text, "P4_CLOSE_LIMIT_IS_LS_MASK"), } if observed != expected: raise PackagingError( f"motor polarity masks mismatch project.json vs params.vh: " f"expected={expected} observed={observed}" ) fingerprint_payload = json.dumps(expected, sort_keys=True, separators=(",", ":")).encode("utf-8") return { "limit_active_high": list(project["limits"]["limit_active_high"]), "dir_close_level": list(project["motors"]["dir_close_level"]), "close_limit_is_ls": list(project["limits"]["close_limit_is_ls"]), "masks": expected, "sha256": _sha256_bytes(fingerprint_payload), } 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, snapshot_hashes: dict[str, dict[str, str]] | None = None, ) -> dict[str, Any]: """Compare synthesis inputs across artifact, matrix, and final dev commits. Modes: - ``commit_compare``: live repo ``git show`` commit-to-commit (default). - ``snapshot_hash``: compare caller-supplied SHA-256 maps (no git required). - ``comparison_unavailable_without_git``: every ``git show`` failed; do **not** report ``source_closure_equal=false`` with an empty ``production_changed_paths`` as if that were a real commit diff. Full delivery packages must include a git bundle so replay can restore commit-to-commit comparison. """ 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 commit_keys = ( ("artifact_source_sha256", artifact_commit, "artifact"), ("matrix_commit_sha256", matrix_commit, "matrix"), ("final_dev_commit_sha256", final_dev_commit, "final_dev"), ) if snapshot_hashes is not None: mode = "snapshot_hash" 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 key, _commit, label in commit_keys: sha = snapshot_hashes.get(label, {}).get(relative_path) row[key] = sha values.append(sha) if any(value is None for value in values): row["status"] = "unavailable" all_same = False elif values[0] == values[1] == values[2]: row["status"] = "same" else: row["status"] = "different" all_same = False if values[0] != values[2]: production_changed_paths.append(relative_path) entries.append(row) source_closure_equal: bool | None = all_same and all( entry["status"] == "same" for entry in entries ) else: mode = "commit_compare" for relative_path, artifact_sha in sorted(inputs.items()): row = {"path": relative_path, "artifact_expected_sha256": artifact_sha} values = [] for key, commit, _label in commit_keys: 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] is None and values[1] is None and values[2] is None: # git show failed for every commit: not a fake "different" commit diff row["status"] = "unavailable" elif 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) if entries and all(entry["status"] == "unavailable" for entry in entries): mode = "comparison_unavailable_without_git" source_closure_equal = None production_changed_paths = [] all_same = False else: if any(entry["status"] == "unavailable" for entry in entries): all_same = False source_closure_equal = all_same and all( entry["status"] == "same" for entry in entries ) comparison_text = json.dumps( { "artifact_source_commit": artifact_commit, "matrix_commit": matrix_commit, "final_dev_commit": final_dev_commit, "mode": mode, "source_closure_equal": source_closure_equal, "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", "mode": mode, "artifact_source_commit": artifact_commit, "matrix_commit": matrix_commit, "final_dev_commit": final_dev_commit, "source_closure_equal": source_closure_equal, "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", "DELIVERY-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", "meta/source-closure-relations.json", "meta/REFERENCE-POINTER.json", "meta/release-set-sibling.json", "meta/release-set-identity.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}") bit_names = [name for name in names if name.casefold().endswith(".bit")] if "fw.bit" in names and len(bit_names) != 1: failures.append(f"multiple_or_unexpected_bitstreams:{bit_names}") for name in names: lower = name.casefold() if lower.endswith((".brd", ".pdf", ".dsn")): failures.append(f"raw_reference_in_firmware:{name}") if name.startswith("td/") and "td_20260630" in name: failures.append(f"stale_td_log_in_package:{name}") if "PENDING" in name.upper() or "hook_ready" in lower: failures.append(f"forbidden_firmware_member:{name}") sums_text = "" if "SHA256SUMS.txt" in names: sums_text = zipf.read("SHA256SUMS.txt").decode("ascii", errors="replace") seen: dict[str, str] = {} for line in sums_text.splitlines(): line = line.strip() if not line or line.startswith("#"): continue digest, _, member = line.partition(" ") if len(digest) != 64 or not member: failures.append(f"sha256sums_bad_line:{line}") continue if member in seen: failures.append(f"sha256sums_duplicate:{member}") continue seen[member] = digest.casefold() if member not in names: failures.append(f"sha256sums_missing_file:{member}") continue actual = _sha256_bytes(zipf.read(member)) if actual != digest.casefold(): failures.append(f"sha256sums_mismatch:{member}") for key in ( "fw.bit", "BITSTREAM-SHA256.txt", "PACKAGE-MANIFEST.json", "meta/release-set-identity.json", "td/original-final_td_report.json", ): if key in names and key not in seen: failures.append(f"sha256sums_omitted_key:{key}") bit_digest = _sha256_bytes(zipf.read("fw.bit")) if "fw.bit" in names else "" if "BITSTREAM-SHA256.txt" in names and bit_digest: declared = zipf.read("BITSTREAM-SHA256.txt").decode("ascii", errors="replace").strip().split()[0] if declared.casefold() != bit_digest: failures.append("bitstream_sha_mismatch_txt") manifest = {} if "PACKAGE-MANIFEST.json" in names: manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json")) if expected_manifest.get("bitstream_sha256") and manifest.get( "bitstream_sha256" ) != expected_manifest["bitstream_sha256"]: failures.append("bitstream_sha_manifest_mismatch") if bit_digest and str(manifest.get("bitstream_sha256") or "").casefold() != bit_digest: failures.append("bitstream_sha_mismatch_manifest") if "release_set_id" not in manifest: failures.append("missing_release_set_id_in_manifest") hw = str(manifest.get("hardware_validation") or "").casefold().replace(" ", "_") if hw not in {"not_run", "not-run"}: failures.append(f"manifest_hardware_not_not_run:{manifest.get('hardware_validation')}") identity: dict[str, Any] = {} if "meta/release-set-identity.json" in names: identity = json.loads(zipf.read("meta/release-set-identity.json")) ident_blob = json.dumps(identity) for token in ("PENDING", "pending_package", "hook_ready"): if token in ident_blob: failures.append(f"identity_forbidden_token:{token}") if bit_digest and str(identity.get("bitstream_sha256") or "").casefold() != bit_digest: failures.append("bitstream_sha_mismatch_release_identity") delivery_txt = "" if "DELIVERY-COMMIT.txt" in names: delivery_txt = zipf.read("DELIVERY-COMMIT.txt").decode("ascii", errors="replace").strip().split()[0] if delivery_txt and str(identity.get("delivery_commit") or "") != delivery_txt: failures.append("identity_delivery_mismatch_txt") if str(identity.get("base_dev_commit") or "") != BASE_DEV_COMMIT_DEFAULT: failures.append("identity_base_dev_mismatch") if not str(identity.get("td_artifact_run_id") or "").strip(): failures.append("identity_missing_td_artifact_run_id") if not str(identity.get("td_receipt_sha256") or "").strip(): failures.append("identity_missing_td_receipt_sha256") if not str( identity.get("matrix_verification_tip") or identity.get("verification_tip") or "" ).strip(): failures.append("identity_missing_matrix_tip") if str(identity.get("package_stage") or "") == "final-review": if str(identity.get("td_binding_status") or "").casefold() != "pass": failures.append("identity_td_binding_not_pass") lut = identity.get("lut") mslice = identity.get("mslice") if ( lut is not None and mslice is not None and lut == mslice and lut not in (0, 0.0, "0") ): failures.append("identity_mslice_equals_lut") if str(identity.get("release_set_id") or "") != str(manifest.get("release_set_id") or ""): failures.append("identity_release_set_id_mismatch_manifest") if "meta/release-set-sibling.json" in names: sibling = json.loads(zipf.read("meta/release-set-sibling.json")) if sibling.get("sha256") or sibling.get("zip_sha256"): failures.append("sibling_contains_cyclic_zip_sha") if sibling.get("release_set_id") != manifest.get("release_set_id"): failures.append("sibling_release_set_id_mismatch") if sibling.get("this_role") not in {None, "firmware"}: failures.append("sibling_role_unexpected") expected = str(sibling.get("sibling_expected_filename") or "") if expected: if "PENDING" in expected.upper(): failures.append("sibling_filename_pending") if "door-percent" in expected.casefold() and "mse-a1" not in expected.casefold(): failures.append("sibling_stale_door_percent") topic = pkg_prov.release_task_slug() if topic == "mse-a1" and "mse-a1" not in expected and expected: failures.append("sibling_topic_not_mse_a1") if "meta/source-closure-relations.json" in names: relations = json.loads(zipf.read("meta/source-closure-relations.json")) rel_check = pkg_prov.validate_source_closure_relations(relations) if rel_check.get("status") != "pass": failures.extend( f"relations:{item}" for item in (rel_check.get("failures") or ["fail"]) ) if "meta/REFERENCE-POINTER.json" in names: pointer = json.loads(zipf.read("meta/REFERENCE-POINTER.json")) if pointer.get("include_raw_reference") is True: failures.append("reference_pointer_includes_raw") 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 run_firmware_zip_selftest(zip_path: Path) -> dict[str, Any]: """Public firmware ZIP selftest (tamper / sidecar reuse).""" zip_path = zip_path.expanduser().resolve(strict=True) with zipfile.ZipFile(zip_path, "r", allowZip64=True) as zipf: if "PACKAGE-MANIFEST.json" not in zipf.namelist(): return { "status": "fail", "failures": ["missing_package_manifest"], "package_path": str(zip_path), } manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json")) return _selftest_package(zip_path=zip_path, expected_manifest=manifest, td_root=zip_path.parent) 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") 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}" ) motor_polarity = motor_polarity_config_identity(ROOT) reference_fp = pkg_prov.reference_set_fingerprint(ROOT) 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, ) # OLD baseline → ARTIFACT: polarity production inputs changed (docs identity). old_baseline_comparison = generate_source_closure_comparison( td_report=td_report, artifact_commit=OLD_BASELINE_COMMIT_DEFAULT, matrix_commit=OLD_BASELINE_COMMIT_DEFAULT, final_dev_commit=artifact_commit, repo_root=ROOT, ) if comparison["mode"] == "comparison_unavailable_without_git": raise PackagingError( "source closure comparison unavailable without git; " "full packages require a git bundle so replay can restore commit-to-commit compare" ) 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 comparison["source_closure_equal"] is not True: raise PackagingError( f"source_closure_unchanged requested but comparison differs: {comparison['production_changed_paths']}" ) # ARTIFACT-SOURCE identifies the production-input tip. TD may execute on a later # delivery tip when SOURCE-CLOSURE-UNCHANGED proves those inputs are identical. if report_commit and report_commit != artifact_commit: if not ( source_closure_unchanged and comparison.get("source_closure_equal") is True ): raise PackagingError( f"TD report commit {report_commit} does not match artifact_source_commit " f"{artifact_commit} and source closure is not proven unchanged" ) 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", {}) td_run_id = str(td_report.get("run_id") or "") if not td_run_id: raise PackagingError( "firmware package requires td_artifact_run_id from TD receipt run_id" ) if td_run_id == "20260806T112210Z-3f2f5f2f": raise PackagingError( "refusing Round-10 hardcoded td_artifact_run_id fallback" ) td_fields = pkg_prov.load_td_identity_fields(td_report_path, repo_root=ROOT) receipt_artifact = str(td_fields.get("artifact_source_commit") or "").strip() if receipt_artifact and receipt_artifact != artifact_commit: raise PackagingError( "TD receipt commit does not match artifact_commit " f"({receipt_artifact} != {artifact_commit})" ) if str(td_fields.get("bitstream_sha256") or "") != bitstream_sha256: raise PackagingError( "TD identity bitstream_sha256 does not match packaged bitstream bytes" ) if str(td_fields.get("td_artifact_run_id") or "") != td_run_id: raise PackagingError( "TD identity td_artifact_run_id does not match TD report run_id" ) release_identity = pkg_prov.build_shared_release_identity( delivery_commit=final_dev_commit, package_stage="final-review", matrix_verification_tip=matrix_commit, software_verification_run_id=matrix_run_id, config_fingerprint=motor_polarity["sha256"], reference_set_fingerprint=reference_fp["sha256"], repo_root=ROOT, claim_bound_bitstream=True, non_final=False, td_fields=td_fields, extra={ "production_polarity_config": { "limit_active_high": motor_polarity.get("limit_active_high"), "dir_close_level": motor_polarity.get("dir_close_level"), "close_limit_is_ls": motor_polarity.get("close_limit_is_ls"), "generated_masks": motor_polarity.get("masks"), "config_fingerprint": motor_polarity["sha256"], }, "dir_close_level": motor_polarity.get("dir_close_level"), "note": ( "Shared identity bound to the packaged TD receipt " "(load_td_identity_fields); release_set_id uses that receipt's " "run_id and bitstream SHA; FINAL-DEV-COMMIT.txt is a deprecated " "alias for delivery_commit." ), }, ) if str(release_identity.get("bitstream_sha256") or "") != bitstream_sha256: raise PackagingError( "shared identity bitstream_sha256 does not match packaged bitstream bytes" ) if str(release_identity.get("td_artifact_run_id") or "") != td_run_id: raise PackagingError( "shared identity td_artifact_run_id does not match TD report run_id " f"({release_identity.get('td_artifact_run_id')} != {td_run_id})" ) release_set_id = str(release_identity["release_set_id"]) relations = pkg_prov.build_source_closure_relations( old_baseline_commit=OLD_BASELINE_COMMIT_DEFAULT, artifact_commit=artifact_commit, delivery_commit=final_dev_commit, old_to_artifact_unchanged=bool(old_baseline_comparison.get("source_closure_equal")), artifact_to_delivery_unchanged=bool(comparison.get("source_closure_equal")), old_to_artifact_changed_paths=list( old_baseline_comparison.get("production_changed_paths") or [] ), artifact_to_delivery_changed_paths=list(comparison.get("production_changed_paths") or []), comparison_mode=str(comparison.get("mode") or "commit_compare"), ) rel_check = pkg_prov.validate_source_closure_relations(relations) if rel_check["status"] != "pass": raise PackagingError( f"source-closure relations inconsistent: {rel_check['failures']}" ) reference_pointer = pkg_prov.build_reference_pointer( artifact_commit=artifact_commit, delivery_commit=final_dev_commit, reference_changed=False, reference_reused=True, repo_root=ROOT, summary_only=True, ) # Expected sibling filename uses delivery short + convention (no ZIP SHA). sibling_expected = pkg_prov.release_sibling_filename("review-compact", final_dev_commit) sibling = pkg_prov.sibling_role_stub( role="firmware", expected_filename=sibling_expected, release_set_id=release_set_id, ) manifest: dict[str, Any] = { "schema": "prod2u-door-temp-final-package-manifest-v2", "package_name": package_name or f"prod2u-firmware-{RELEASE_TASK_SLUG}-{artifact_commit[:8]}-{bitstream_sha256[:8]}", "status": "VERIFIED_OFFLINE", "created_at": datetime.now(timezone.utc).isoformat(), "verification_scope": "offline", "hardware_validation": "not_run", "base_dev_commit": BASE_DEV_COMMIT_DEFAULT, "artifact_source_commit": artifact_commit, "matrix_commit": matrix_commit, "delivery_commit": final_dev_commit, # Compatibility alias — never means the git `dev` ref moved. "final_dev_commit": final_dev_commit, "td_run_id": td_report.get("run_id"), "matrix_run_id": matrix_run_id, "source_closure_unchanged": bool(comparison["source_closure_equal"]), "source_closure_comparison_mode": comparison["mode"], "project_config_sha256": current_project_sha, "motor_polarity_config": motor_polarity, "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, "release_set_id": release_set_id, "reference_set_fingerprint": reference_fp["sha256"], "resources": { "lut": utilization.get("lut", {}).get("used"), "register": utilization.get("reg", {}).get("used"), "mslice": resources_section.get("packing", {}).get("mslice"), "lslice": resources_section.get("packing", {}).get("lslice"), "total_slices": resources_section.get("packing", {}).get("total_slices"), "dsp": utilization.get("dsp", {}).get("used"), "bram": utilization.get("bram", {}).get("used"), # deprecated alias of total_slices; NEVER MSLICE "packed_slice": resources_section.get("packing", {}).get("total_slices"), }, "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] = [] relations_json = json.dumps(relations, indent=2, sort_keys=True) + "\n" reference_pointer_json = json.dumps(reference_pointer, indent=2, sort_keys=True) + "\n" sibling_json = json.dumps(sibling, indent=2, sort_keys=True) + "\n" release_identity_json = json.dumps(release_identity, indent=2, sort_keys=True) + "\n" 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, "DELIVERY-COMMIT.txt", sha256_entries) _add_text( zipf, final_dev_commit + "\n# deprecated_alias for delivery_commit; not git-dev\n", "FINAL-DEV-COMMIT.txt", sha256_entries, ) _add_text( zipf, "true" if comparison["source_closure_equal"] is True 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) # Minimal provenance (relations / reference pointer summary / sibling stub) _add_text(zipf, relations_json, "meta/source-closure-relations.json", sha256_entries) _add_text(zipf, reference_pointer_json, "meta/REFERENCE-POINTER.json", sha256_entries) _add_text(zipf, sibling_json, "meta/release-set-sibling.json", sha256_entries) _add_text(zipf, release_identity_json, "meta/release-set-identity.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 pkg_prov.attach_shared_identity_fields(selftest, release_identity) 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) parser.add_argument("--target", default="mrdimm", help="firmware target alias (default mrdimm)") args = parser.parse_args(argv) if args.target != "mrdimm": from tools.target_registry import release_blocked, resolve_target target = resolve_target(args.target) blocked, pins = release_blocked(target) if blocked: print("error: production firmware package fail-closed", file=sys.stderr) for name in pins: print(f"{name} pin unresolved", file=sys.stderr) print("release_blocked", file=sys.stderr) return 1 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())