build_firmware_package.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  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. bit_names = [name for name in names if name.casefold().endswith(".bit")]
  337. if "fw.bit" in names and len(bit_names) != 1:
  338. failures.append(f"multiple_or_unexpected_bitstreams:{bit_names}")
  339. for name in names:
  340. lower = name.casefold()
  341. if lower.endswith((".brd", ".pdf", ".dsn")):
  342. failures.append(f"raw_reference_in_firmware:{name}")
  343. if name.startswith("td/") and "td_20260630" in name:
  344. failures.append(f"stale_td_log_in_package:{name}")
  345. if "PENDING" in name.upper() or "hook_ready" in lower:
  346. failures.append(f"forbidden_firmware_member:{name}")
  347. sums_text = ""
  348. if "SHA256SUMS.txt" in names:
  349. sums_text = zipf.read("SHA256SUMS.txt").decode("ascii", errors="replace")
  350. seen: dict[str, str] = {}
  351. for line in sums_text.splitlines():
  352. line = line.strip()
  353. if not line or line.startswith("#"):
  354. continue
  355. digest, _, member = line.partition(" ")
  356. if len(digest) != 64 or not member:
  357. failures.append(f"sha256sums_bad_line:{line}")
  358. continue
  359. if member in seen:
  360. failures.append(f"sha256sums_duplicate:{member}")
  361. continue
  362. seen[member] = digest.casefold()
  363. if member not in names:
  364. failures.append(f"sha256sums_missing_file:{member}")
  365. continue
  366. actual = _sha256_bytes(zipf.read(member))
  367. if actual != digest.casefold():
  368. failures.append(f"sha256sums_mismatch:{member}")
  369. for key in (
  370. "fw.bit",
  371. "BITSTREAM-SHA256.txt",
  372. "PACKAGE-MANIFEST.json",
  373. "meta/release-set-identity.json",
  374. "td/original-final_td_report.json",
  375. ):
  376. if key in names and key not in seen:
  377. failures.append(f"sha256sums_omitted_key:{key}")
  378. bit_digest = _sha256_bytes(zipf.read("fw.bit")) if "fw.bit" in names else ""
  379. if "BITSTREAM-SHA256.txt" in names and bit_digest:
  380. declared = zipf.read("BITSTREAM-SHA256.txt").decode("ascii", errors="replace").strip().split()[0]
  381. if declared.casefold() != bit_digest:
  382. failures.append("bitstream_sha_mismatch_txt")
  383. manifest = {}
  384. if "PACKAGE-MANIFEST.json" in names:
  385. manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
  386. if expected_manifest.get("bitstream_sha256") and manifest.get(
  387. "bitstream_sha256"
  388. ) != expected_manifest["bitstream_sha256"]:
  389. failures.append("bitstream_sha_manifest_mismatch")
  390. if bit_digest and str(manifest.get("bitstream_sha256") or "").casefold() != bit_digest:
  391. failures.append("bitstream_sha_mismatch_manifest")
  392. if "release_set_id" not in manifest:
  393. failures.append("missing_release_set_id_in_manifest")
  394. hw = str(manifest.get("hardware_validation") or "").casefold().replace(" ", "_")
  395. if hw not in {"not_run", "not-run"}:
  396. failures.append(f"manifest_hardware_not_not_run:{manifest.get('hardware_validation')}")
  397. identity: dict[str, Any] = {}
  398. if "meta/release-set-identity.json" in names:
  399. identity = json.loads(zipf.read("meta/release-set-identity.json"))
  400. ident_blob = json.dumps(identity)
  401. for token in ("PENDING", "pending_package", "hook_ready"):
  402. if token in ident_blob:
  403. failures.append(f"identity_forbidden_token:{token}")
  404. if bit_digest and str(identity.get("bitstream_sha256") or "").casefold() != bit_digest:
  405. failures.append("bitstream_sha_mismatch_release_identity")
  406. delivery_txt = ""
  407. if "DELIVERY-COMMIT.txt" in names:
  408. delivery_txt = zipf.read("DELIVERY-COMMIT.txt").decode("ascii", errors="replace").strip().split()[0]
  409. if delivery_txt and str(identity.get("delivery_commit") or "") != delivery_txt:
  410. failures.append("identity_delivery_mismatch_txt")
  411. if str(identity.get("base_dev_commit") or "") != BASE_DEV_COMMIT_DEFAULT:
  412. failures.append("identity_base_dev_mismatch")
  413. if not str(identity.get("td_artifact_run_id") or "").strip():
  414. failures.append("identity_missing_td_artifact_run_id")
  415. if not str(identity.get("td_receipt_sha256") or "").strip():
  416. failures.append("identity_missing_td_receipt_sha256")
  417. if not str(
  418. identity.get("matrix_verification_tip") or identity.get("verification_tip") or ""
  419. ).strip():
  420. failures.append("identity_missing_matrix_tip")
  421. if str(identity.get("package_stage") or "") == "final-review":
  422. if str(identity.get("td_binding_status") or "").casefold() != "pass":
  423. failures.append("identity_td_binding_not_pass")
  424. lut = identity.get("lut")
  425. mslice = identity.get("mslice")
  426. if (
  427. lut is not None
  428. and mslice is not None
  429. and lut == mslice
  430. and lut not in (0, 0.0, "0")
  431. ):
  432. failures.append("identity_mslice_equals_lut")
  433. if str(identity.get("release_set_id") or "") != str(manifest.get("release_set_id") or ""):
  434. failures.append("identity_release_set_id_mismatch_manifest")
  435. if "meta/release-set-sibling.json" in names:
  436. sibling = json.loads(zipf.read("meta/release-set-sibling.json"))
  437. if sibling.get("sha256") or sibling.get("zip_sha256"):
  438. failures.append("sibling_contains_cyclic_zip_sha")
  439. if sibling.get("release_set_id") != manifest.get("release_set_id"):
  440. failures.append("sibling_release_set_id_mismatch")
  441. if sibling.get("this_role") not in {None, "firmware"}:
  442. failures.append("sibling_role_unexpected")
  443. expected = str(sibling.get("sibling_expected_filename") or "")
  444. if expected:
  445. if "PENDING" in expected.upper():
  446. failures.append("sibling_filename_pending")
  447. if "door-percent" in expected.casefold() and "mse-a1" not in expected.casefold():
  448. failures.append("sibling_stale_door_percent")
  449. topic = pkg_prov.release_task_slug()
  450. if topic == "mse-a1" and "mse-a1" not in expected and expected:
  451. failures.append("sibling_topic_not_mse_a1")
  452. if "meta/source-closure-relations.json" in names:
  453. relations = json.loads(zipf.read("meta/source-closure-relations.json"))
  454. rel_check = pkg_prov.validate_source_closure_relations(relations)
  455. if rel_check.get("status") != "pass":
  456. failures.extend(
  457. f"relations:{item}" for item in (rel_check.get("failures") or ["fail"])
  458. )
  459. if "meta/REFERENCE-POINTER.json" in names:
  460. pointer = json.loads(zipf.read("meta/REFERENCE-POINTER.json"))
  461. if pointer.get("include_raw_reference") is True:
  462. failures.append("reference_pointer_includes_raw")
  463. return {
  464. "status": "fail" if failures else "pass",
  465. "failures": failures,
  466. "package_path": str(zip_path),
  467. "package_sha256": _sha256_file(zip_path),
  468. "td_root": str(td_root),
  469. }
  470. def run_firmware_zip_selftest(zip_path: Path) -> dict[str, Any]:
  471. """Public firmware ZIP selftest (tamper / sidecar reuse)."""
  472. zip_path = zip_path.expanduser().resolve(strict=True)
  473. with zipfile.ZipFile(zip_path, "r", allowZip64=True) as zipf:
  474. if "PACKAGE-MANIFEST.json" not in zipf.namelist():
  475. return {
  476. "status": "fail",
  477. "failures": ["missing_package_manifest"],
  478. "package_path": str(zip_path),
  479. }
  480. manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
  481. return _selftest_package(zip_path=zip_path, expected_manifest=manifest, td_root=zip_path.parent)
  482. def build_firmware_package(
  483. *,
  484. output_dir: Path,
  485. package_name: str | None,
  486. td_root: Path,
  487. artifact_commit: str,
  488. matrix_commit: str,
  489. final_dev_commit: str,
  490. source_closure_unchanged: bool,
  491. bitstream_path: Path | None = None,
  492. td_report_path: Path | None = None,
  493. matrix_receipt_path: Path | None = None,
  494. matrix_run_id: str | None = None,
  495. ) -> tuple[Path, Path]:
  496. """Build and selftest the final firmware ZIP."""
  497. td_root = _resolve_path(td_root)
  498. if bitstream_path is None:
  499. bitstream_path = _bitstream_path_from_td_root(td_root)
  500. if td_report_path is None:
  501. td_report_path = _report_path_from_td_root(td_root)
  502. bitstream_path = _resolve_path(bitstream_path)
  503. td_report_path = _resolve_path(td_report_path)
  504. _validate_td_root(td_root=td_root, bitstream_path=bitstream_path, td_report_path=td_report_path)
  505. if not bitstream_path.is_file():
  506. raise FileNotFoundError(f"bitstream not found: {bitstream_path}")
  507. if not td_report_path.is_file():
  508. raise FileNotFoundError(f"TD report not found: {td_report_path}")
  509. td_report = _read_json(td_report_path)
  510. bitstream_sha256 = _sha256_file(bitstream_path)
  511. # Strong binding checks
  512. report_bitstream_sha = td_report.get("bitstream_sha256")
  513. if report_bitstream_sha and report_bitstream_sha != bitstream_sha256:
  514. raise PackagingError(
  515. f"TD report bitstream_sha256 {report_bitstream_sha} does not match actual {bitstream_sha256}"
  516. )
  517. report_commit = td_report.get("commit_full") or td_report.get("commit")
  518. report_project_sha = td_report.get("project_config_sha256")
  519. current_project_sha = _sha256_file(ROOT / "projects" / "prod2u-door-temp" / "project.json")
  520. if report_project_sha and report_project_sha != current_project_sha:
  521. raise PackagingError(
  522. f"TD report project_config_sha256 {report_project_sha} does not match current {current_project_sha}"
  523. )
  524. motor_polarity = motor_polarity_config_identity(ROOT)
  525. reference_fp = pkg_prov.reference_set_fingerprint(ROOT)
  526. comparison = generate_source_closure_comparison(
  527. td_report=td_report,
  528. artifact_commit=artifact_commit,
  529. matrix_commit=matrix_commit,
  530. final_dev_commit=final_dev_commit,
  531. repo_root=ROOT,
  532. )
  533. # OLD baseline → ARTIFACT: polarity production inputs changed (docs identity).
  534. old_baseline_comparison = generate_source_closure_comparison(
  535. td_report=td_report,
  536. artifact_commit=OLD_BASELINE_COMMIT_DEFAULT,
  537. matrix_commit=OLD_BASELINE_COMMIT_DEFAULT,
  538. final_dev_commit=artifact_commit,
  539. repo_root=ROOT,
  540. )
  541. if comparison["mode"] == "comparison_unavailable_without_git":
  542. raise PackagingError(
  543. "source closure comparison unavailable without git; "
  544. "full packages require a git bundle so replay can restore commit-to-commit compare"
  545. )
  546. if not source_closure_unchanged and comparison["source_closure_equal"]:
  547. # Caller claimed changed but comparison says same: trust explicit flag
  548. pass
  549. if source_closure_unchanged and comparison["source_closure_equal"] is not True:
  550. raise PackagingError(
  551. f"source_closure_unchanged requested but comparison differs: {comparison['production_changed_paths']}"
  552. )
  553. # ARTIFACT-SOURCE identifies the production-input tip. TD may execute on a later
  554. # delivery tip when SOURCE-CLOSURE-UNCHANGED proves those inputs are identical.
  555. if report_commit and report_commit != artifact_commit:
  556. if not (
  557. source_closure_unchanged and comparison.get("source_closure_equal") is True
  558. ):
  559. raise PackagingError(
  560. f"TD report commit {report_commit} does not match artifact_source_commit "
  561. f"{artifact_commit} and source closure is not proven unchanged"
  562. )
  563. comparison_json = json.dumps(comparison, indent=2, sort_keys=True) + "\n"
  564. comparison_sha256 = _sha256_bytes(comparison_json.encode("utf-8"))
  565. provenance = generate_td_provenance(
  566. original_report=td_report,
  567. artifact_commit=artifact_commit,
  568. source_closure_comparison_sha256=comparison_sha256,
  569. bitstream_sha256=bitstream_sha256,
  570. matrix_run_id=matrix_run_id,
  571. )
  572. provenance_json = json.dumps(provenance, indent=2, sort_keys=True) + "\n"
  573. provenance_sha256 = _sha256_bytes(provenance_json.encode("utf-8"))
  574. timing = td_report.get("timing", {})
  575. resources_section = td_report.get("resources", {})
  576. utilization = resources_section.get("utilization", {})
  577. td_run_id = str(td_report.get("run_id") or "")
  578. if not td_run_id:
  579. raise PackagingError(
  580. "firmware package requires td_artifact_run_id from TD receipt run_id"
  581. )
  582. if td_run_id == "20260806T112210Z-3f2f5f2f":
  583. raise PackagingError(
  584. "refusing Round-10 hardcoded td_artifact_run_id fallback"
  585. )
  586. td_fields = pkg_prov.load_td_identity_fields(td_report_path, repo_root=ROOT)
  587. receipt_artifact = str(td_fields.get("artifact_source_commit") or "").strip()
  588. if receipt_artifact and receipt_artifact != artifact_commit:
  589. raise PackagingError(
  590. "TD receipt commit does not match artifact_commit "
  591. f"({receipt_artifact} != {artifact_commit})"
  592. )
  593. if str(td_fields.get("bitstream_sha256") or "") != bitstream_sha256:
  594. raise PackagingError(
  595. "TD identity bitstream_sha256 does not match packaged bitstream bytes"
  596. )
  597. if str(td_fields.get("td_artifact_run_id") or "") != td_run_id:
  598. raise PackagingError(
  599. "TD identity td_artifact_run_id does not match TD report run_id"
  600. )
  601. release_identity = pkg_prov.build_shared_release_identity(
  602. delivery_commit=final_dev_commit,
  603. package_stage="final-review",
  604. matrix_verification_tip=matrix_commit,
  605. software_verification_run_id=matrix_run_id,
  606. config_fingerprint=motor_polarity["sha256"],
  607. reference_set_fingerprint=reference_fp["sha256"],
  608. repo_root=ROOT,
  609. claim_bound_bitstream=True,
  610. non_final=False,
  611. td_fields=td_fields,
  612. extra={
  613. "production_polarity_config": {
  614. "limit_active_high": motor_polarity.get("limit_active_high"),
  615. "dir_close_level": motor_polarity.get("dir_close_level"),
  616. "close_limit_is_ls": motor_polarity.get("close_limit_is_ls"),
  617. "generated_masks": motor_polarity.get("masks"),
  618. "config_fingerprint": motor_polarity["sha256"],
  619. },
  620. "dir_close_level": motor_polarity.get("dir_close_level"),
  621. "note": (
  622. "Shared identity bound to the packaged TD receipt "
  623. "(load_td_identity_fields); release_set_id uses that receipt's "
  624. "run_id and bitstream SHA; FINAL-DEV-COMMIT.txt is a deprecated "
  625. "alias for delivery_commit."
  626. ),
  627. },
  628. )
  629. if str(release_identity.get("bitstream_sha256") or "") != bitstream_sha256:
  630. raise PackagingError(
  631. "shared identity bitstream_sha256 does not match packaged bitstream bytes"
  632. )
  633. if str(release_identity.get("td_artifact_run_id") or "") != td_run_id:
  634. raise PackagingError(
  635. "shared identity td_artifact_run_id does not match TD report run_id "
  636. f"({release_identity.get('td_artifact_run_id')} != {td_run_id})"
  637. )
  638. release_set_id = str(release_identity["release_set_id"])
  639. relations = pkg_prov.build_source_closure_relations(
  640. old_baseline_commit=OLD_BASELINE_COMMIT_DEFAULT,
  641. artifact_commit=artifact_commit,
  642. delivery_commit=final_dev_commit,
  643. old_to_artifact_unchanged=bool(old_baseline_comparison.get("source_closure_equal")),
  644. artifact_to_delivery_unchanged=bool(comparison.get("source_closure_equal")),
  645. old_to_artifact_changed_paths=list(
  646. old_baseline_comparison.get("production_changed_paths") or []
  647. ),
  648. artifact_to_delivery_changed_paths=list(comparison.get("production_changed_paths") or []),
  649. comparison_mode=str(comparison.get("mode") or "commit_compare"),
  650. )
  651. rel_check = pkg_prov.validate_source_closure_relations(relations)
  652. if rel_check["status"] != "pass":
  653. raise PackagingError(
  654. f"source-closure relations inconsistent: {rel_check['failures']}"
  655. )
  656. reference_pointer = pkg_prov.build_reference_pointer(
  657. artifact_commit=artifact_commit,
  658. delivery_commit=final_dev_commit,
  659. reference_changed=False,
  660. reference_reused=True,
  661. repo_root=ROOT,
  662. summary_only=True,
  663. )
  664. # Expected sibling filename uses delivery short + convention (no ZIP SHA).
  665. sibling_expected = pkg_prov.release_sibling_filename("review-compact", final_dev_commit)
  666. sibling = pkg_prov.sibling_role_stub(
  667. role="firmware",
  668. expected_filename=sibling_expected,
  669. release_set_id=release_set_id,
  670. )
  671. manifest: dict[str, Any] = {
  672. "schema": "prod2u-door-temp-final-package-manifest-v2",
  673. "package_name": package_name
  674. or f"prod2u-firmware-{RELEASE_TASK_SLUG}-{artifact_commit[:8]}-{bitstream_sha256[:8]}",
  675. "status": "VERIFIED_OFFLINE",
  676. "created_at": datetime.now(timezone.utc).isoformat(),
  677. "verification_scope": "offline",
  678. "hardware_validation": "not_run",
  679. "base_dev_commit": BASE_DEV_COMMIT_DEFAULT,
  680. "artifact_source_commit": artifact_commit,
  681. "matrix_commit": matrix_commit,
  682. "delivery_commit": final_dev_commit,
  683. # Compatibility alias — never means the git `dev` ref moved.
  684. "final_dev_commit": final_dev_commit,
  685. "td_run_id": td_report.get("run_id"),
  686. "matrix_run_id": matrix_run_id,
  687. "source_closure_unchanged": bool(comparison["source_closure_equal"]),
  688. "source_closure_comparison_mode": comparison["mode"],
  689. "project_config_sha256": current_project_sha,
  690. "motor_polarity_config": motor_polarity,
  691. "td_source_manifest_sha256": td_report.get("td_source_manifest_sha256"),
  692. "synthesis_input_manifest_sha256": td_report.get("synthesis_input_manifest", {}).get("sha256"),
  693. "source_closure_comparison_sha256": comparison_sha256,
  694. "bitstream_sha256": bitstream_sha256,
  695. "matrix_receipt_sha256": _sha256_file(matrix_receipt_path) if matrix_receipt_path and matrix_receipt_path.is_file() else None,
  696. "original_td_receipt_sha256": _sha256_file(td_report_path),
  697. "td_provenance_sha256": provenance_sha256,
  698. "release_set_id": release_set_id,
  699. "reference_set_fingerprint": reference_fp["sha256"],
  700. "resources": {
  701. "lut": utilization.get("lut", {}).get("used"),
  702. "register": utilization.get("reg", {}).get("used"),
  703. "mslice": resources_section.get("packing", {}).get("mslice"),
  704. "lslice": resources_section.get("packing", {}).get("lslice"),
  705. "total_slices": resources_section.get("packing", {}).get("total_slices"),
  706. "dsp": utilization.get("dsp", {}).get("used"),
  707. "bram": utilization.get("bram", {}).get("used"),
  708. # deprecated alias of total_slices; NEVER MSLICE
  709. "packed_slice": resources_section.get("packing", {}).get("total_slices"),
  710. },
  711. "timing": {
  712. "fmax_mhz": timing.get("fmax_mhz"),
  713. "setup_slack_ns": timing.get("worst_setup_slack_ns"),
  714. "hold_slack_ns": timing.get("worst_hold_slack_ns"),
  715. },
  716. }
  717. output_dir = _resolve_path(output_dir)
  718. output_dir.mkdir(parents=True, exist_ok=True)
  719. name = manifest["package_name"]
  720. zip_path = output_dir / f"{name}.zip"
  721. if zip_path.exists():
  722. zip_path.unlink()
  723. sha256_entries: list[str] = []
  724. relations_json = json.dumps(relations, indent=2, sort_keys=True) + "\n"
  725. reference_pointer_json = json.dumps(reference_pointer, indent=2, sort_keys=True) + "\n"
  726. sibling_json = json.dumps(sibling, indent=2, sort_keys=True) + "\n"
  727. release_identity_json = json.dumps(release_identity, indent=2, sort_keys=True) + "\n"
  728. with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as zipf:
  729. # Bitstream and provenance
  730. _add_file(zipf, bitstream_path, "fw.bit", sha256_entries)
  731. _add_text(zipf, bitstream_sha256, "BITSTREAM-SHA256.txt", sha256_entries)
  732. _add_text(zipf, artifact_commit, "ARTIFACT-SOURCE-COMMIT.txt", sha256_entries)
  733. _add_text(zipf, matrix_commit, "MATRIX-COMMIT.txt", sha256_entries)
  734. _add_text(zipf, final_dev_commit, "DELIVERY-COMMIT.txt", sha256_entries)
  735. _add_text(
  736. zipf,
  737. final_dev_commit + "\n# deprecated_alias for delivery_commit; not git-dev\n",
  738. "FINAL-DEV-COMMIT.txt",
  739. sha256_entries,
  740. )
  741. _add_text(
  742. zipf,
  743. "true" if comparison["source_closure_equal"] is True else "false",
  744. "SOURCE-CLOSURE-UNCHANGED.txt",
  745. sha256_entries,
  746. )
  747. # Original TD report and provenance
  748. _add_file(zipf, td_report_path, "td/original-final_td_report.json", sha256_entries)
  749. _add_text(zipf, provenance_json, "td/TD-PROVENANCE.json", sha256_entries)
  750. # Selected TD stage evidence from the explicit TD root
  751. for src, arcname in _collect_td_stage_files(td_root):
  752. _add_file(zipf, src, arcname, sha256_entries)
  753. # Project contract and protocol
  754. _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "project.json", "project.json", sha256_entries)
  755. _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "requirements.zh-CN.md", "requirements.zh-CN.md", sha256_entries)
  756. _add_file(zipf, ROOT / "docs" / "prod2u-door-temp-protocol.zh-CN.md", "docs/prod2u-door-temp-protocol.zh-CN.md", sha256_entries)
  757. # Generated artifacts
  758. for gen in (ROOT / "src" / "generated").iterdir():
  759. if gen.is_file():
  760. _add_file(zipf, gen, f"src/generated/{gen.name}", sha256_entries)
  761. # Constraints
  762. for adc in (ROOT / "constraints").iterdir():
  763. if adc.is_file():
  764. _add_file(zipf, adc, f"constraints/{adc.name}", sha256_entries)
  765. # Tracked TD inputs from the repo (not the build root)
  766. for td_input in REPO_TD_INPUTS:
  767. src = ROOT / td_input
  768. if src.is_file():
  769. _add_file(zipf, src, td_input, sha256_entries)
  770. # Source closure manifest
  771. _add_file(zipf, ROOT / "config" / "source_closure.json", "config/source_closure.json", sha256_entries)
  772. # Source-closure comparison
  773. _add_text(zipf, comparison_json, "evidence/SOURCE-CLOSURE-COMPARISON.json", sha256_entries)
  774. # Minimal provenance (relations / reference pointer summary / sibling stub)
  775. _add_text(zipf, relations_json, "meta/source-closure-relations.json", sha256_entries)
  776. _add_text(zipf, reference_pointer_json, "meta/REFERENCE-POINTER.json", sha256_entries)
  777. _add_text(zipf, sibling_json, "meta/release-set-sibling.json", sha256_entries)
  778. _add_text(zipf, release_identity_json, "meta/release-set-identity.json", sha256_entries)
  779. # Optional matrix receipt
  780. if matrix_receipt_path and matrix_receipt_path.is_file():
  781. _add_file(zipf, matrix_receipt_path, "evidence/matrix-receipt.json", sha256_entries)
  782. # Manifest and SHA256SUMS
  783. manifest_text = json.dumps(manifest, indent=2, sort_keys=True) + "\n"
  784. _add_text(zipf, manifest_text, "PACKAGE-MANIFEST.json", sha256_entries)
  785. _add_text(zipf, "\n".join(sha256_entries) + "\n", "SHA256SUMS.txt", sha256_entries)
  786. selftest = _selftest_package(zip_path=zip_path, expected_manifest=manifest, td_root=td_root)
  787. if selftest["status"] != "pass":
  788. zip_path.unlink(missing_ok=True)
  789. raise PackagingError(f"firmware package selftest failed: {selftest['failures']}")
  790. selftest["package_selftest_status"] = "pass"
  791. selftest["manifest"] = manifest
  792. pkg_prov.attach_shared_identity_fields(selftest, release_identity)
  793. sidecar_path = output_dir / f"{name}.selftest.json"
  794. sidecar_path.write_text(json.dumps(selftest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  795. return zip_path, sidecar_path
  796. def main(argv: list[str] | None = None) -> int:
  797. parser = argparse.ArgumentParser(description=__doc__)
  798. parser.add_argument("--output-dir", type=Path, default=Path.home() / "Downloads" / "CPLD-firmware")
  799. parser.add_argument("--package-name", help="package base name (default from commit/bitstream)")
  800. parser.add_argument("--td-root", type=Path, required=True)
  801. parser.add_argument("--bitstream", type=Path, default=None)
  802. parser.add_argument("--td-report", type=Path, default=None)
  803. parser.add_argument("--artifact-commit", required=True)
  804. parser.add_argument("--matrix-commit", required=True)
  805. parser.add_argument("--final-dev-commit", required=True)
  806. parser.add_argument("--source-closure-unchanged", action="store_true")
  807. parser.add_argument("--matrix-receipt", type=Path, default=None)
  808. parser.add_argument("--matrix-run-id", default=None)
  809. args = parser.parse_args(argv)
  810. try:
  811. zip_path, sidecar_path = build_firmware_package(
  812. output_dir=args.output_dir,
  813. package_name=args.package_name,
  814. td_root=args.td_root,
  815. artifact_commit=args.artifact_commit,
  816. matrix_commit=args.matrix_commit,
  817. final_dev_commit=args.final_dev_commit,
  818. source_closure_unchanged=args.source_closure_unchanged,
  819. bitstream_path=args.bitstream,
  820. td_report_path=args.td_report,
  821. matrix_receipt_path=args.matrix_receipt,
  822. matrix_run_id=args.matrix_run_id,
  823. )
  824. except (FileNotFoundError, PackagingError) as exc:
  825. print(f"error: {exc}", file=sys.stderr)
  826. return 1
  827. print(
  828. json.dumps(
  829. {"status": "pass", "package": str(zip_path), "selftest": str(sidecar_path)},
  830. indent=2,
  831. )
  832. )
  833. return 0
  834. if __name__ == "__main__":
  835. raise SystemExit(main())