| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782 |
- #!/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
- RELEASE_TASK_SLUG = "door-percent"
- 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}")
- manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
- if manifest["bitstream_sha256"] != expected_manifest["bitstream_sha256"]:
- failures.append("bitstream_sha_manifest_mismatch")
- if "release_set_id" not in manifest:
- failures.append("missing_release_set_id_in_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")
- # 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")
- 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 "")
- release_set_id = pkg_prov.compute_release_set_id(
- artifact_commit=artifact_commit,
- delivery_commit=final_dev_commit,
- bitstream_sha256=bitstream_sha256,
- config_fingerprint=motor_polarity["sha256"],
- td_run_id=td_run_id,
- reference_set_fingerprint_sha256=reference_fp["sha256"],
- )
- 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,
- )
- td_verification_run_id = str(td_report.get("verification_run_id") or "")
- td_artifact_run_id = str(td_report.get("run_id") or td_run_id or "")
- if not td_artifact_run_id:
- raise PackagingError(
- "firmware package requires td_artifact_run_id from TD receipt run_id"
- )
- if td_artifact_run_id == "20260806T112210Z-3f2f5f2f":
- raise PackagingError(
- "refusing Round-10 hardcoded td_artifact_run_id fallback"
- )
- release_identity = {
- "schema": "prod2u-release-set-identity-v1",
- "algorithm_version": "prod2u-release-set-id-v1",
- "package_stage": "final-review",
- "non_final": False,
- "release_set_id": release_set_id,
- "base_dev_commit": BASE_DEV_COMMIT_DEFAULT,
- "artifact_source_commit": artifact_commit,
- "td_bound_commit": artifact_commit,
- "delivery_commit": final_dev_commit,
- "bitstream_sha256": bitstream_sha256,
- "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"],
- },
- "verification_run_id": td_verification_run_id or td_artifact_run_id,
- "td_artifact_run_id": td_artifact_run_id,
- "reference_set_fingerprint": reference_fp["sha256"],
- "hardware_validation": "not_run",
- "note": (
- "release_set_id uses td_artifact_run_id (= TD receipt run_id); "
- "FINAL-DEV-COMMIT.txt is a deprecated alias for delivery_commit."
- ),
- }
- 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"),
- "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] = []
- 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
- 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())
|