build_firmware_package.py 32 KB

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