build_firmware_package.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724
  1. #!/usr/bin/env python3
  2. """Build the Prod2U door-temperature final firmware delivery package.
  3. This is a deterministic wrapper that collects:
  4. - the canonical bitstream from an explicit TD root,
  5. - original and provenance-augmented TD reports,
  6. - source-closure comparison across artifact/matrix/final dev commits,
  7. - selected TD stage evidence (syn/phy/bitgen reports and logs),
  8. - source/contracts/TD inputs,
  9. - generated host contract and golden vectors,
  10. - verification receipts (when available),
  11. - package manifest, SHA-256 sums, and an external selftest sidecar.
  12. It does not access COM/JTAG or program hardware.
  13. """
  14. from __future__ import annotations
  15. import argparse
  16. import hashlib
  17. import json
  18. import shutil
  19. import subprocess
  20. import sys
  21. import zipfile
  22. from datetime import datetime, timezone
  23. from pathlib import Path
  24. from typing import Any
  25. ROOT = Path(__file__).resolve().parents[1]
  26. TOOLS = Path(__file__).resolve().parent
  27. if str(TOOLS) not in sys.path:
  28. sys.path.insert(0, str(TOOLS))
  29. import package_provenance as pkg_prov # noqa: E402
  30. TD_STAGE_SUFFIXES = {".rpt", ".timing", ".area", ".qor", ".log", ".logw"}
  31. REPO_TD_INPUTS = [
  32. "td/prod2u_p4_normal_v3.prj",
  33. "td/syn/prod2u_p4_normal_v3.tcl",
  34. "td/phy/prod2u_p4_normal_v3.tcl",
  35. "td/bitgen/prod2u_p4_normal_v3.tcl",
  36. ]
  37. # Historical baseline tip used for OLD→ARTIFACT relation (docs/activity identity).
  38. OLD_BASELINE_COMMIT_DEFAULT = "0de9f93988344e3c11931482902196b02ac7a713"
  39. class PackagingError(RuntimeError):
  40. """Raised when the firmware package cannot be produced safely."""
  41. def _sha256_file(path: Path) -> str:
  42. digest = hashlib.sha256()
  43. with path.open("rb") as stream:
  44. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  45. digest.update(chunk)
  46. return digest.hexdigest()
  47. def _sha256_bytes(data: bytes) -> str:
  48. return hashlib.sha256(data).hexdigest()
  49. def _read_json(path: Path) -> Any:
  50. return json.loads(path.read_text(encoding="utf-8-sig"))
  51. def _mask_define_from_params(params_text: str, name: str) -> str:
  52. needle = f"`define {name} "
  53. for line in params_text.splitlines():
  54. if line.startswith(needle):
  55. return line[len(needle) :].strip()
  56. raise PackagingError(f"missing `{name}` in prod2u_door_temp_params.vh")
  57. def _axis_mask_literal_from_values(values: list[Any], axis_count: int = 3) -> str:
  58. if len(values) != axis_count:
  59. raise PackagingError(f"axis mask length mismatch: expected {axis_count}, got {len(values)}")
  60. bits = "".join("1" if bool(v) else "0" for v in reversed(values))
  61. return f"{axis_count}'b{bits}"
  62. def motor_polarity_config_identity(repo_root: Path | None = None) -> dict[str, Any]:
  63. """Fingerprint motor polarity masks from project.json and bind to params.vh.
  64. Fail-closed when checked-in params drift from the project contract.
  65. """
  66. root = repo_root or ROOT
  67. project = _read_json(root / "projects" / "prod2u-door-temp" / "project.json")
  68. params_path = root / "src" / "generated" / "prod2u_door_temp_params.vh"
  69. params_text = params_path.read_text(encoding="utf-8")
  70. expected = {
  71. "limit_active_high_mask": _axis_mask_literal_from_values(
  72. list(project["limits"]["limit_active_high"])
  73. ),
  74. "dir_close_level_mask": _axis_mask_literal_from_values(
  75. list(project["motors"]["dir_close_level"])
  76. ),
  77. "close_limit_is_ls_mask": _axis_mask_literal_from_values(
  78. list(project["limits"]["close_limit_is_ls"])
  79. ),
  80. }
  81. observed = {
  82. "limit_active_high_mask": _mask_define_from_params(params_text, "P4_LIMIT_ACTIVE_HIGH_MASK"),
  83. "dir_close_level_mask": _mask_define_from_params(params_text, "P4_DIR_CLOSE_LEVEL_MASK"),
  84. "close_limit_is_ls_mask": _mask_define_from_params(params_text, "P4_CLOSE_LIMIT_IS_LS_MASK"),
  85. }
  86. if observed != expected:
  87. raise PackagingError(
  88. f"motor polarity masks mismatch project.json vs params.vh: "
  89. f"expected={expected} observed={observed}"
  90. )
  91. fingerprint_payload = json.dumps(expected, sort_keys=True, separators=(",", ":")).encode("utf-8")
  92. return {
  93. "limit_active_high": list(project["limits"]["limit_active_high"]),
  94. "dir_close_level": list(project["motors"]["dir_close_level"]),
  95. "close_limit_is_ls": list(project["limits"]["close_limit_is_ls"]),
  96. "masks": expected,
  97. "sha256": _sha256_bytes(fingerprint_payload),
  98. }
  99. def _git_show_file(repo_root: Path, commit: str, relative_path: str) -> bytes:
  100. """Return the contents of a tracked path at a specific commit."""
  101. completed = subprocess.run(
  102. ["git", "-C", str(repo_root), "show", f"{commit}:{relative_path}"],
  103. stdout=subprocess.PIPE,
  104. stderr=subprocess.PIPE,
  105. check=False,
  106. )
  107. if completed.returncode != 0:
  108. raise PackagingError(
  109. f"git show failed for {commit}:{relative_path}: {completed.stderr.decode('utf-8', errors='ignore').strip()}"
  110. )
  111. return completed.stdout
  112. def _resolve_path(path: Path) -> Path:
  113. return Path(path).expanduser().resolve()
  114. def _inside(root: Path, candidate: Path) -> bool:
  115. """Return True if candidate is root or under root."""
  116. root = _resolve_path(root)
  117. candidate = _resolve_path(candidate)
  118. try:
  119. candidate.relative_to(root)
  120. return True
  121. except ValueError:
  122. return False
  123. def _validate_td_root(
  124. *,
  125. td_root: Path,
  126. bitstream_path: Path,
  127. td_report_path: Path,
  128. ) -> None:
  129. """Ensure bitstream and report belong to the selected TD root."""
  130. if not _inside(td_root, bitstream_path):
  131. raise PackagingError(f"bitstream {bitstream_path} is outside selected td_root {td_root}")
  132. if not _inside(td_root, td_report_path):
  133. raise PackagingError(f"td report {td_report_path} is outside selected td_root {td_root}")
  134. def _bitstream_path_from_td_root(td_root: Path) -> Path:
  135. return _resolve_path(td_root / "td" / "prod2u_p4_normal_v3" / "bitgen" / "prod2u_p4_normal_v3.bit")
  136. def _report_path_from_td_root(td_root: Path) -> Path:
  137. return _resolve_path(td_root / "report.json")
  138. def generate_source_closure_comparison(
  139. *,
  140. td_report: dict[str, Any],
  141. artifact_commit: str,
  142. matrix_commit: str,
  143. final_dev_commit: str,
  144. repo_root: Path = ROOT,
  145. snapshot_hashes: dict[str, dict[str, str]] | None = None,
  146. ) -> dict[str, Any]:
  147. """Compare synthesis inputs across artifact, matrix, and final dev commits.
  148. Modes:
  149. - ``commit_compare``: live repo ``git show`` commit-to-commit (default).
  150. - ``snapshot_hash``: compare caller-supplied SHA-256 maps (no git required).
  151. - ``comparison_unavailable_without_git``: every ``git show`` failed; do **not**
  152. report ``source_closure_equal=false`` with an empty ``production_changed_paths``
  153. as if that were a real commit diff. Full delivery packages must include a git
  154. bundle so replay can restore commit-to-commit comparison.
  155. """
  156. inputs = td_report.get("synthesis_input_manifest", {}).get("inputs", {})
  157. if not inputs:
  158. raise PackagingError("TD report has no synthesis_input_manifest.inputs")
  159. entries: list[dict[str, Any]] = []
  160. production_changed_paths: list[str] = []
  161. all_same = True
  162. commit_keys = (
  163. ("artifact_source_sha256", artifact_commit, "artifact"),
  164. ("matrix_commit_sha256", matrix_commit, "matrix"),
  165. ("final_dev_commit_sha256", final_dev_commit, "final_dev"),
  166. )
  167. if snapshot_hashes is not None:
  168. mode = "snapshot_hash"
  169. for relative_path, artifact_sha in sorted(inputs.items()):
  170. row: dict[str, Any] = {
  171. "path": relative_path,
  172. "artifact_expected_sha256": artifact_sha,
  173. }
  174. values: list[str | None] = []
  175. for key, _commit, label in commit_keys:
  176. sha = snapshot_hashes.get(label, {}).get(relative_path)
  177. row[key] = sha
  178. values.append(sha)
  179. if any(value is None for value in values):
  180. row["status"] = "unavailable"
  181. all_same = False
  182. elif values[0] == values[1] == values[2]:
  183. row["status"] = "same"
  184. else:
  185. row["status"] = "different"
  186. all_same = False
  187. if values[0] != values[2]:
  188. production_changed_paths.append(relative_path)
  189. entries.append(row)
  190. source_closure_equal: bool | None = all_same and all(
  191. entry["status"] == "same" for entry in entries
  192. )
  193. else:
  194. mode = "commit_compare"
  195. for relative_path, artifact_sha in sorted(inputs.items()):
  196. row = {"path": relative_path, "artifact_expected_sha256": artifact_sha}
  197. values = []
  198. for key, commit, _label in commit_keys:
  199. try:
  200. content = _git_show_file(repo_root, commit, relative_path)
  201. sha = _sha256_bytes(content)
  202. except PackagingError:
  203. sha = None
  204. row[key] = sha
  205. values.append(sha)
  206. if values[0] is None and values[1] is None and values[2] is None:
  207. # git show failed for every commit: not a fake "different" commit diff
  208. row["status"] = "unavailable"
  209. elif values[0] == values[1] == values[2] and values[0] is not None:
  210. row["status"] = "same"
  211. else:
  212. row["status"] = "different"
  213. all_same = False
  214. if values[0] != values[2]:
  215. production_changed_paths.append(relative_path)
  216. entries.append(row)
  217. if entries and all(entry["status"] == "unavailable" for entry in entries):
  218. mode = "comparison_unavailable_without_git"
  219. source_closure_equal = None
  220. production_changed_paths = []
  221. all_same = False
  222. else:
  223. if any(entry["status"] == "unavailable" for entry in entries):
  224. all_same = False
  225. source_closure_equal = all_same and all(
  226. entry["status"] == "same" for entry in entries
  227. )
  228. comparison_text = json.dumps(
  229. {
  230. "artifact_source_commit": artifact_commit,
  231. "matrix_commit": matrix_commit,
  232. "final_dev_commit": final_dev_commit,
  233. "mode": mode,
  234. "source_closure_equal": source_closure_equal,
  235. "production_changed_paths": production_changed_paths,
  236. "entries": entries,
  237. },
  238. sort_keys=True,
  239. )
  240. source_set_sha256 = _sha256_bytes(comparison_text.encode("utf-8"))
  241. return {
  242. "schema": "prod2u-source-closure-comparison-v1",
  243. "mode": mode,
  244. "artifact_source_commit": artifact_commit,
  245. "matrix_commit": matrix_commit,
  246. "final_dev_commit": final_dev_commit,
  247. "source_closure_equal": source_closure_equal,
  248. "production_changed_paths": production_changed_paths,
  249. "source_set_sha256": source_set_sha256,
  250. "inputs": entries,
  251. }
  252. def generate_td_provenance(
  253. *,
  254. original_report: dict[str, Any],
  255. artifact_commit: str,
  256. source_closure_comparison_sha256: str,
  257. bitstream_sha256: str,
  258. matrix_run_id: str | None,
  259. ) -> dict[str, Any]:
  260. """Bind the original TD run to the current matrix and source closure."""
  261. return {
  262. "schema": "prod2u-td-provenance-v1",
  263. "status": "bound_by_source_closure_comparison",
  264. "artifact_source_commit": artifact_commit,
  265. "original_td_run_id": original_report.get("run_id"),
  266. "original_placeholder_verification_run_id": original_report.get("verification_run_id"),
  267. "matrix_run_id": matrix_run_id,
  268. "source_closure_comparison_sha256": source_closure_comparison_sha256,
  269. "bitstream_sha256": bitstream_sha256,
  270. "original_report_path": "td/original-final_td_report.json",
  271. "project_config_sha256": original_report.get("project_config_sha256"),
  272. "td_source_manifest_sha256": original_report.get("td_source_manifest_sha256"),
  273. "synthesis_input_manifest_sha256": original_report.get("synthesis_input_manifest", {}).get("sha256"),
  274. }
  275. def _add_file(zipf: zipfile.ZipFile, src: Path, arcname: str, sha256_entries: list[str]) -> None:
  276. zipf.write(src, arcname)
  277. sha256_entries.append(f"{_sha256_file(src)} {arcname}")
  278. def _add_text(zipf: zipfile.ZipFile, text: str, arcname: str, sha256_entries: list[str]) -> None:
  279. payload = text.encode("utf-8")
  280. zipf.writestr(arcname, payload)
  281. sha256_entries.append(f"{_sha256_bytes(payload)} {arcname}")
  282. def _collect_td_stage_files(td_root: Path) -> list[tuple[Path, str]]:
  283. """Collect allowed evidence files from the selected TD build stages."""
  284. collected: list[tuple[Path, str]] = []
  285. stages = ["syn", "phy", "bitgen"]
  286. for stage in stages:
  287. stage_dir = _resolve_path(td_root / "td" / "prod2u_p4_normal_v3" / stage)
  288. if not stage_dir.is_dir():
  289. continue
  290. for item in stage_dir.iterdir():
  291. if item.is_file() and item.suffix.casefold() in TD_STAGE_SUFFIXES:
  292. collected.append((item, f"td/{stage}/{item.name}"))
  293. return collected
  294. def _selftest_package(
  295. *,
  296. zip_path: Path,
  297. expected_manifest: dict[str, Any],
  298. td_root: Path,
  299. ) -> dict[str, Any]:
  300. """Verify the built firmware package before writing the sidecar."""
  301. failures: list[str] = []
  302. with zipfile.ZipFile(zip_path, "r", allowZip64=True) as zipf:
  303. names = set(zipf.namelist())
  304. required = {
  305. "fw.bit",
  306. "BITSTREAM-SHA256.txt",
  307. "ARTIFACT-SOURCE-COMMIT.txt",
  308. "MATRIX-COMMIT.txt",
  309. "FINAL-DEV-COMMIT.txt",
  310. "SOURCE-CLOSURE-UNCHANGED.txt",
  311. "PACKAGE-MANIFEST.json",
  312. "SHA256SUMS.txt",
  313. "td/original-final_td_report.json",
  314. "td/TD-PROVENANCE.json",
  315. "evidence/SOURCE-CLOSURE-COMPARISON.json",
  316. "meta/source-closure-relations.json",
  317. "meta/REFERENCE-POINTER.json",
  318. "meta/release-set-sibling.json",
  319. "project.json",
  320. "config/source_closure.json",
  321. }
  322. missing = sorted(required - names)
  323. if missing:
  324. failures.append(f"missing_required_files:{missing}")
  325. bad = zipf.testzip()
  326. if bad is not None:
  327. failures.append(f"crc_failed:{bad}")
  328. manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
  329. if manifest["bitstream_sha256"] != expected_manifest["bitstream_sha256"]:
  330. failures.append("bitstream_sha_manifest_mismatch")
  331. if "release_set_id" not in manifest:
  332. failures.append("missing_release_set_id_in_manifest")
  333. if "meta/release-set-sibling.json" in names:
  334. sibling = json.loads(zipf.read("meta/release-set-sibling.json"))
  335. if sibling.get("sha256") or sibling.get("zip_sha256"):
  336. failures.append("sibling_contains_cyclic_zip_sha")
  337. if sibling.get("release_set_id") != manifest.get("release_set_id"):
  338. failures.append("sibling_release_set_id_mismatch")
  339. # Detect stale repo TD logs from ROOT/td that should not be present
  340. for name in names:
  341. if name.startswith("td/") and "td_20260630" in name:
  342. failures.append(f"stale_td_log_in_package:{name}")
  343. return {
  344. "status": "fail" if failures else "pass",
  345. "failures": failures,
  346. "package_path": str(zip_path),
  347. "package_sha256": _sha256_file(zip_path),
  348. "td_root": str(td_root),
  349. }
  350. def build_firmware_package(
  351. *,
  352. output_dir: Path,
  353. package_name: str | None,
  354. td_root: Path,
  355. artifact_commit: str,
  356. matrix_commit: str,
  357. final_dev_commit: str,
  358. source_closure_unchanged: bool,
  359. bitstream_path: Path | None = None,
  360. td_report_path: Path | None = None,
  361. matrix_receipt_path: Path | None = None,
  362. matrix_run_id: str | None = None,
  363. ) -> tuple[Path, Path]:
  364. """Build and selftest the final firmware ZIP."""
  365. td_root = _resolve_path(td_root)
  366. if bitstream_path is None:
  367. bitstream_path = _bitstream_path_from_td_root(td_root)
  368. if td_report_path is None:
  369. td_report_path = _report_path_from_td_root(td_root)
  370. bitstream_path = _resolve_path(bitstream_path)
  371. td_report_path = _resolve_path(td_report_path)
  372. _validate_td_root(td_root=td_root, bitstream_path=bitstream_path, td_report_path=td_report_path)
  373. if not bitstream_path.is_file():
  374. raise FileNotFoundError(f"bitstream not found: {bitstream_path}")
  375. if not td_report_path.is_file():
  376. raise FileNotFoundError(f"TD report not found: {td_report_path}")
  377. td_report = _read_json(td_report_path)
  378. bitstream_sha256 = _sha256_file(bitstream_path)
  379. # Strong binding checks
  380. report_bitstream_sha = td_report.get("bitstream_sha256")
  381. if report_bitstream_sha and report_bitstream_sha != bitstream_sha256:
  382. raise PackagingError(
  383. f"TD report bitstream_sha256 {report_bitstream_sha} does not match actual {bitstream_sha256}"
  384. )
  385. report_commit = td_report.get("commit_full") or td_report.get("commit")
  386. report_project_sha = td_report.get("project_config_sha256")
  387. current_project_sha = _sha256_file(ROOT / "projects" / "prod2u-door-temp" / "project.json")
  388. if report_project_sha and report_project_sha != current_project_sha:
  389. raise PackagingError(
  390. f"TD report project_config_sha256 {report_project_sha} does not match current {current_project_sha}"
  391. )
  392. motor_polarity = motor_polarity_config_identity(ROOT)
  393. reference_fp = pkg_prov.reference_set_fingerprint(ROOT)
  394. comparison = generate_source_closure_comparison(
  395. td_report=td_report,
  396. artifact_commit=artifact_commit,
  397. matrix_commit=matrix_commit,
  398. final_dev_commit=final_dev_commit,
  399. repo_root=ROOT,
  400. )
  401. # OLD baseline → ARTIFACT: polarity production inputs changed (docs identity).
  402. old_baseline_comparison = generate_source_closure_comparison(
  403. td_report=td_report,
  404. artifact_commit=OLD_BASELINE_COMMIT_DEFAULT,
  405. matrix_commit=OLD_BASELINE_COMMIT_DEFAULT,
  406. final_dev_commit=artifact_commit,
  407. repo_root=ROOT,
  408. )
  409. if comparison["mode"] == "comparison_unavailable_without_git":
  410. raise PackagingError(
  411. "source closure comparison unavailable without git; "
  412. "full packages require a git bundle so replay can restore commit-to-commit compare"
  413. )
  414. if not source_closure_unchanged and comparison["source_closure_equal"]:
  415. # Caller claimed changed but comparison says same: trust explicit flag
  416. pass
  417. if source_closure_unchanged and comparison["source_closure_equal"] is not True:
  418. raise PackagingError(
  419. f"source_closure_unchanged requested but comparison differs: {comparison['production_changed_paths']}"
  420. )
  421. # ARTIFACT-SOURCE identifies the production-input tip. TD may execute on a later
  422. # delivery tip when SOURCE-CLOSURE-UNCHANGED proves those inputs are identical.
  423. if report_commit and report_commit != artifact_commit:
  424. if not (
  425. source_closure_unchanged and comparison.get("source_closure_equal") is True
  426. ):
  427. raise PackagingError(
  428. f"TD report commit {report_commit} does not match artifact_source_commit "
  429. f"{artifact_commit} and source closure is not proven unchanged"
  430. )
  431. comparison_json = json.dumps(comparison, indent=2, sort_keys=True) + "\n"
  432. comparison_sha256 = _sha256_bytes(comparison_json.encode("utf-8"))
  433. provenance = generate_td_provenance(
  434. original_report=td_report,
  435. artifact_commit=artifact_commit,
  436. source_closure_comparison_sha256=comparison_sha256,
  437. bitstream_sha256=bitstream_sha256,
  438. matrix_run_id=matrix_run_id,
  439. )
  440. provenance_json = json.dumps(provenance, indent=2, sort_keys=True) + "\n"
  441. provenance_sha256 = _sha256_bytes(provenance_json.encode("utf-8"))
  442. timing = td_report.get("timing", {})
  443. resources_section = td_report.get("resources", {})
  444. utilization = resources_section.get("utilization", {})
  445. td_run_id = str(td_report.get("run_id") or "")
  446. release_set_id = pkg_prov.compute_release_set_id(
  447. artifact_commit=artifact_commit,
  448. delivery_commit=final_dev_commit,
  449. bitstream_sha256=bitstream_sha256,
  450. config_fingerprint=motor_polarity["sha256"],
  451. td_run_id=td_run_id,
  452. reference_set_fingerprint_sha256=reference_fp["sha256"],
  453. )
  454. relations = pkg_prov.build_source_closure_relations(
  455. old_baseline_commit=OLD_BASELINE_COMMIT_DEFAULT,
  456. artifact_commit=artifact_commit,
  457. delivery_commit=final_dev_commit,
  458. old_to_artifact_unchanged=bool(old_baseline_comparison.get("source_closure_equal")),
  459. artifact_to_delivery_unchanged=bool(comparison.get("source_closure_equal")),
  460. old_to_artifact_changed_paths=list(
  461. old_baseline_comparison.get("production_changed_paths") or []
  462. ),
  463. artifact_to_delivery_changed_paths=list(comparison.get("production_changed_paths") or []),
  464. comparison_mode=str(comparison.get("mode") or "commit_compare"),
  465. )
  466. reference_pointer = pkg_prov.build_reference_pointer(
  467. artifact_commit=artifact_commit,
  468. delivery_commit=final_dev_commit,
  469. reference_changed=False,
  470. reference_reused=True,
  471. repo_root=ROOT,
  472. summary_only=True,
  473. )
  474. # Expected sibling filename uses delivery short + convention (no ZIP SHA).
  475. sibling_expected = f"prod2u-review-compact-altconfig-{final_dev_commit[:8]}.zip"
  476. sibling = pkg_prov.sibling_role_stub(
  477. role="firmware",
  478. expected_filename=sibling_expected,
  479. release_set_id=release_set_id,
  480. )
  481. manifest: dict[str, Any] = {
  482. "schema": "prod2u-door-temp-final-package-manifest-v2",
  483. "package_name": package_name or f"prod2u-door-temp-final-{artifact_commit[:8]}-{bitstream_sha256[:8]}",
  484. "status": "VERIFIED_OFFLINE",
  485. "created_at": datetime.now(timezone.utc).isoformat(),
  486. "verification_scope": "offline",
  487. "hardware_validation": "not_run",
  488. "artifact_source_commit": artifact_commit,
  489. "matrix_commit": matrix_commit,
  490. "final_dev_commit": final_dev_commit,
  491. "td_run_id": td_report.get("run_id"),
  492. "matrix_run_id": matrix_run_id,
  493. "source_closure_unchanged": bool(comparison["source_closure_equal"]),
  494. "source_closure_comparison_mode": comparison["mode"],
  495. "project_config_sha256": current_project_sha,
  496. "motor_polarity_config": motor_polarity,
  497. "td_source_manifest_sha256": td_report.get("td_source_manifest_sha256"),
  498. "synthesis_input_manifest_sha256": td_report.get("synthesis_input_manifest", {}).get("sha256"),
  499. "source_closure_comparison_sha256": comparison_sha256,
  500. "bitstream_sha256": bitstream_sha256,
  501. "matrix_receipt_sha256": _sha256_file(matrix_receipt_path) if matrix_receipt_path and matrix_receipt_path.is_file() else None,
  502. "original_td_receipt_sha256": _sha256_file(td_report_path),
  503. "td_provenance_sha256": provenance_sha256,
  504. "release_set_id": release_set_id,
  505. "reference_set_fingerprint": reference_fp["sha256"],
  506. "resources": {
  507. "lut": utilization.get("lut", {}).get("used"),
  508. "register": utilization.get("reg", {}).get("used"),
  509. "packed_slice": resources_section.get("packing", {}).get("total_slices"),
  510. "bram": utilization.get("bram", {}).get("used"),
  511. "dsp": utilization.get("dsp", {}).get("used"),
  512. },
  513. "timing": {
  514. "fmax_mhz": timing.get("fmax_mhz"),
  515. "setup_slack_ns": timing.get("worst_setup_slack_ns"),
  516. "hold_slack_ns": timing.get("worst_hold_slack_ns"),
  517. },
  518. }
  519. output_dir = _resolve_path(output_dir)
  520. output_dir.mkdir(parents=True, exist_ok=True)
  521. name = manifest["package_name"]
  522. zip_path = output_dir / f"{name}.zip"
  523. if zip_path.exists():
  524. zip_path.unlink()
  525. sha256_entries: list[str] = []
  526. relations_json = json.dumps(relations, indent=2, sort_keys=True) + "\n"
  527. reference_pointer_json = json.dumps(reference_pointer, indent=2, sort_keys=True) + "\n"
  528. sibling_json = json.dumps(sibling, indent=2, sort_keys=True) + "\n"
  529. with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as zipf:
  530. # Bitstream and provenance
  531. _add_file(zipf, bitstream_path, "fw.bit", sha256_entries)
  532. _add_text(zipf, bitstream_sha256, "BITSTREAM-SHA256.txt", sha256_entries)
  533. _add_text(zipf, artifact_commit, "ARTIFACT-SOURCE-COMMIT.txt", sha256_entries)
  534. _add_text(zipf, matrix_commit, "MATRIX-COMMIT.txt", sha256_entries)
  535. _add_text(zipf, final_dev_commit, "FINAL-DEV-COMMIT.txt", sha256_entries)
  536. _add_text(
  537. zipf,
  538. "true" if comparison["source_closure_equal"] is True else "false",
  539. "SOURCE-CLOSURE-UNCHANGED.txt",
  540. sha256_entries,
  541. )
  542. # Original TD report and provenance
  543. _add_file(zipf, td_report_path, "td/original-final_td_report.json", sha256_entries)
  544. _add_text(zipf, provenance_json, "td/TD-PROVENANCE.json", sha256_entries)
  545. # Selected TD stage evidence from the explicit TD root
  546. for src, arcname in _collect_td_stage_files(td_root):
  547. _add_file(zipf, src, arcname, sha256_entries)
  548. # Project contract and protocol
  549. _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "project.json", "project.json", sha256_entries)
  550. _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "requirements.zh-CN.md", "requirements.zh-CN.md", sha256_entries)
  551. _add_file(zipf, ROOT / "docs" / "prod2u-door-temp-protocol.zh-CN.md", "docs/prod2u-door-temp-protocol.zh-CN.md", sha256_entries)
  552. # Generated artifacts
  553. for gen in (ROOT / "src" / "generated").iterdir():
  554. if gen.is_file():
  555. _add_file(zipf, gen, f"src/generated/{gen.name}", sha256_entries)
  556. # Constraints
  557. for adc in (ROOT / "constraints").iterdir():
  558. if adc.is_file():
  559. _add_file(zipf, adc, f"constraints/{adc.name}", sha256_entries)
  560. # Tracked TD inputs from the repo (not the build root)
  561. for td_input in REPO_TD_INPUTS:
  562. src = ROOT / td_input
  563. if src.is_file():
  564. _add_file(zipf, src, td_input, sha256_entries)
  565. # Source closure manifest
  566. _add_file(zipf, ROOT / "config" / "source_closure.json", "config/source_closure.json", sha256_entries)
  567. # Source-closure comparison
  568. _add_text(zipf, comparison_json, "evidence/SOURCE-CLOSURE-COMPARISON.json", sha256_entries)
  569. # Minimal provenance (relations / reference pointer summary / sibling stub)
  570. _add_text(zipf, relations_json, "meta/source-closure-relations.json", sha256_entries)
  571. _add_text(zipf, reference_pointer_json, "meta/REFERENCE-POINTER.json", sha256_entries)
  572. _add_text(zipf, sibling_json, "meta/release-set-sibling.json", sha256_entries)
  573. # Optional matrix receipt
  574. if matrix_receipt_path and matrix_receipt_path.is_file():
  575. _add_file(zipf, matrix_receipt_path, "evidence/matrix-receipt.json", sha256_entries)
  576. # Manifest and SHA256SUMS
  577. manifest_text = json.dumps(manifest, indent=2, sort_keys=True) + "\n"
  578. _add_text(zipf, manifest_text, "PACKAGE-MANIFEST.json", sha256_entries)
  579. _add_text(zipf, "\n".join(sha256_entries) + "\n", "SHA256SUMS.txt", sha256_entries)
  580. selftest = _selftest_package(zip_path=zip_path, expected_manifest=manifest, td_root=td_root)
  581. if selftest["status"] != "pass":
  582. zip_path.unlink(missing_ok=True)
  583. raise PackagingError(f"firmware package selftest failed: {selftest['failures']}")
  584. selftest["package_selftest_status"] = "pass"
  585. selftest["manifest"] = manifest
  586. sidecar_path = output_dir / f"{name}.selftest.json"
  587. sidecar_path.write_text(json.dumps(selftest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  588. return zip_path, sidecar_path
  589. def main(argv: list[str] | None = None) -> int:
  590. parser = argparse.ArgumentParser(description=__doc__)
  591. parser.add_argument("--output-dir", type=Path, default=Path.home() / "Downloads" / "CPLD-firmware")
  592. parser.add_argument("--package-name", help="package base name (default from commit/bitstream)")
  593. parser.add_argument("--td-root", type=Path, required=True)
  594. parser.add_argument("--bitstream", type=Path, default=None)
  595. parser.add_argument("--td-report", type=Path, default=None)
  596. parser.add_argument("--artifact-commit", required=True)
  597. parser.add_argument("--matrix-commit", required=True)
  598. parser.add_argument("--final-dev-commit", required=True)
  599. parser.add_argument("--source-closure-unchanged", action="store_true")
  600. parser.add_argument("--matrix-receipt", type=Path, default=None)
  601. parser.add_argument("--matrix-run-id", default=None)
  602. args = parser.parse_args(argv)
  603. try:
  604. zip_path, sidecar_path = build_firmware_package(
  605. output_dir=args.output_dir,
  606. package_name=args.package_name,
  607. td_root=args.td_root,
  608. artifact_commit=args.artifact_commit,
  609. matrix_commit=args.matrix_commit,
  610. final_dev_commit=args.final_dev_commit,
  611. source_closure_unchanged=args.source_closure_unchanged,
  612. bitstream_path=args.bitstream,
  613. td_report_path=args.td_report,
  614. matrix_receipt_path=args.matrix_receipt,
  615. matrix_run_id=args.matrix_run_id,
  616. )
  617. except (FileNotFoundError, PackagingError) as exc:
  618. print(f"error: {exc}", file=sys.stderr)
  619. return 1
  620. print(
  621. json.dumps(
  622. {"status": "pass", "package": str(zip_path), "selftest": str(sidecar_path)},
  623. indent=2,
  624. )
  625. )
  626. return 0
  627. if __name__ == "__main__":
  628. raise SystemExit(main())