package_unified_analysis.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. #!/usr/bin/env python3
  2. """Package current sources, qualified firmware, native GUI and actual debug evidence.
  3. No dated default BITs, invented hardware results, or implicit delivery/cleanup.
  4. All inputs are explicit and hashes are checked before any firmware is included.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. from datetime import datetime, timezone
  9. import hashlib
  10. import json
  11. from pathlib import Path
  12. import subprocess
  13. import sys
  14. import tempfile
  15. ROOT = Path(__file__).resolve().parents[1]
  16. if str(ROOT) not in sys.path:
  17. sys.path.insert(0, str(ROOT))
  18. from tools.package_archive import encode, finalize, read_archive, write_archive
  19. PRODUCTS = {"6400-v2", "mrdimm-chamber"}
  20. DEFAULT_PROTOCOL_DOC = Path("docs/CPLD_通讯协议v2.0.md")
  21. def digest(data: bytes) -> str:
  22. return hashlib.sha256(data).hexdigest()
  23. def git(repo: Path, *args: str) -> bytes:
  24. return subprocess.check_output(["git", *args], cwd=repo)
  25. def snapshot(repo: Path, label: str) -> tuple[dict, dict]:
  26. """Include every tracked working file and a recoverable committed history."""
  27. files = {}
  28. missing = []
  29. for name in git(repo, "ls-files", "-z").decode().split("\0"):
  30. if not name:
  31. continue
  32. path = repo / name
  33. if path.is_file():
  34. files[f"sources/{label}/{name}"] = path.read_bytes()
  35. else:
  36. missing.append(name)
  37. identity = {
  38. "path": str(repo), "commit": git(repo, "rev-parse", "HEAD").decode().strip(),
  39. "branch": git(repo, "branch", "--show-current").decode().strip(),
  40. "tree": git(repo, "rev-parse", "HEAD^{tree}").decode().strip(),
  41. "working_status": git(repo, "status", "--porcelain").decode(),
  42. "missing_tracked_files": missing,
  43. }
  44. files[f"changes/{label}-working.diff"] = git(repo, "diff", "HEAD", "--binary")
  45. files[f"changes/{label}-status.txt"] = identity["working_status"].encode()
  46. with tempfile.TemporaryDirectory() as temporary:
  47. bundle = Path(temporary) / "source.bundle"
  48. git(repo, "bundle", "create", str(bundle), "HEAD")
  49. files[f"history/{label}.bundle"] = bundle.read_bytes()
  50. return files, identity
  51. def verified_td(run: Path) -> tuple[dict, Path]:
  52. receipt = json.loads((run / "td-receipt.json").read_text())
  53. if (receipt.get("profile") not in PRODUCTS or receipt.get("status") != "PASS"
  54. or receipt.get("production") is not True or receipt.get("simulation_only") is not False
  55. or not receipt.get("timing_pass_25mhz")
  56. or receipt.get("warning_audit", {}).get("status") != "PASS"):
  57. raise ValueError("unqualified TD run: " + str(run))
  58. inputs = receipt.get("inputs", {})
  59. if not inputs or any(digest((ROOT / name).read_bytes()) != sha for name, sha in inputs.items()):
  60. raise ValueError("TD source differs from current files: " + str(run))
  61. actual_manifest = digest(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode())
  62. if receipt.get("source_manifest_sha256") != actual_manifest:
  63. raise ValueError("invalid TD input manifest: " + str(run))
  64. bit = Path(receipt["bitstream"])
  65. if not bit.is_absolute():
  66. bit = run / bit
  67. if digest(bit.read_bytes()) != receipt.get("bitstream_sha256"):
  68. raise ValueError("BIT differs from TD receipt: " + str(bit))
  69. return receipt, bit
  70. def collect_evidence(root: Path, prefix: str) -> dict[str, bytes]:
  71. files = {}
  72. # Retain logs, receipts, timing/area reports, fixture sources and raw captures.
  73. # Tool databases, waveforms and runnable compiler intermediates are reproducible.
  74. omit = {".db", ".vvp", ".vcd", ".fst", ".exe", ".bit", ".tar", ".pyc"}
  75. for path in sorted(root.rglob("*")):
  76. if path.is_file() and path.suffix.lower() not in omit:
  77. if any(part in {"__pycache__", "pytest-temp", "pytest-cache"} for part in path.relative_to(root).parts):
  78. continue
  79. files[prefix + "/" + path.relative_to(root).as_posix()] = path.read_bytes()
  80. return files
  81. def package(path: Path, files: dict, identity: dict) -> dict:
  82. files = {**files, "PACKAGE-SELF-CHECK.py": (ROOT / "tools/package_archive.py").read_bytes()}
  83. payload, modes = finalize(files, {"schema": "prod2u-analysis-manifest-v3", **identity})
  84. write_archive(path, payload, modes)
  85. checked = read_archive(path)
  86. return {"file": path.name, "sha256": checked["sha256"],
  87. "size_bytes": path.stat().st_size, "members": len(checked["files"]),
  88. "archive_integrity": "PASS"}
  89. def main(argv=None) -> int:
  90. parser = argparse.ArgumentParser(description=__doc__)
  91. parser.add_argument("--output-dir", type=Path, required=True)
  92. parser.add_argument("--td-run", action="append", type=Path, default=[])
  93. parser.add_argument("--td-blocker-receipt", type=Path, default=None,
  94. help="Explicit TD blocker JSON when vendor TD bitgen is blocked (no .bit bundled)")
  95. parser.add_argument("--gui-dir", type=Path, required=True)
  96. parser.add_argument("--review-dir", type=Path, required=True)
  97. parser.add_argument("--related-repo", action="append", default=[], metavar="NAME=PATH")
  98. parser.add_argument("--hardware-file", action="append", type=Path, default=[])
  99. parser.add_argument("--protocol-doc", type=Path, default=None,
  100. help="Maintained protocol document to bundle at release root and inside archives (defaults to docs/CPLD_通讯协议v2.0.md if present)")
  101. parser.add_argument("--hardware-status", type=Path, required=True,
  102. help="actual connection/programming/test result JSON, including NOT_RUN when unavailable")
  103. args = parser.parse_args(argv)
  104. if not args.td_run and args.td_blocker_receipt is None:
  105. parser.error("requires --td-run or explicit --td-blocker-receipt")
  106. out = args.output_dir.resolve()
  107. out.mkdir(parents=True, exist_ok=True)
  108. version = (ROOT / "VERSION").read_text().strip()
  109. sources, identity = snapshot(ROOT, "cpld")
  110. repos = {"cpld": identity}
  111. for value in args.related_repo:
  112. label, separator, path = value.partition("=")
  113. if not separator or not label or "/" in label or "\\" in label or label in repos:
  114. parser.error("invalid or duplicate NAME=PATH: " + value)
  115. extra, extra_identity = snapshot(Path(path).resolve(), label)
  116. sources.update(extra)
  117. repos[label] = extra_identity
  118. stamp = datetime.now(timezone.utc).isoformat()
  119. td_blocker = None
  120. if args.td_blocker_receipt is not None:
  121. td_blocker = json.loads(args.td_blocker_receipt.read_text(encoding="utf-8"))
  122. if not str(td_blocker.get("status", "")).startswith("BLOCKED_"):
  123. raise ValueError("td_blocker_receipt status must start with BLOCKED_")
  124. run = {"release_version": version, "commit": identity["commit"], "branch": identity["branch"],
  125. "created_utc": stamp, "repositories": repos, "firmware": [], "td_blocker": td_blocker, "gui": {},
  126. "hardware": json.loads(args.hardware_status.read_text()),
  127. "verification_scope": "See individual receipts; archive integrity is not hardware validation"}
  128. products, debug = {}, collect_evidence(args.review_dir, "debug/review")
  129. seen = set()
  130. for path in args.td_run:
  131. path = path.resolve()
  132. receipt, bit = verified_td(path)
  133. product = receipt["profile"]
  134. baud = receipt["build_parameters"]["host_baud"]
  135. if (product, baud) in seen:
  136. parser.error("duplicate product and baud TD run")
  137. seen.add((product, baud))
  138. name = f"products/{product}/{baud}"
  139. products[name + "/firmware.bit"] = bit.read_bytes()
  140. mask = bit.with_suffix(".bmk")
  141. if mask.is_file():
  142. products[name + "/firmware.bmk"] = mask.read_bytes()
  143. products[name + "/td-receipt.json"] = (path / "td-receipt.json").read_bytes()
  144. debug.update(collect_evidence(path, "debug/td/" + product + "/" + str(baud)))
  145. run["firmware"].append({"product": product, "host_baud": baud,
  146. "bitstream_sha256": receipt["bitstream_sha256"], "td_run": str(path),
  147. "metrics": receipt.get("metrics", {}), "source_commit": receipt["commit"]})
  148. if td_blocker is None and not all((p, 921600) in seen for p in PRODUCTS):
  149. parser.error("both current products require a qualified default 921600 run")
  150. if td_blocker is not None:
  151. products["TD-LICENSE-BLOCKER.json"] = encode(td_blocker)
  152. gui = json.loads((args.gui_dir / "BUILD-SUMMARY.json").read_text())
  153. if set(gui.get("products", {})) != PRODUCTS:
  154. parser.error("native GUI summary must contain both current products")
  155. for product, result in gui["products"].items():
  156. exe = args.gui_dir / result["exe"]
  157. metadata = result["metadata"]
  158. if (result.get("status") != "PASS" or result.get("self_test_exit") != 0
  159. or digest(exe.read_bytes()) != result["sha256"]
  160. or metadata.get("release_version") != version):
  161. raise ValueError("unqualified native GUI: " + product)
  162. if td_blocker is None:
  163. matches = [r for r in run["firmware"] if r["product"] == product and r["host_baud"] == metadata["host_baud"]]
  164. if not matches or metadata["bitstream_sha256"] != matches[0]["bitstream_sha256"]:
  165. raise ValueError("GUI and firmware identity mismatch: " + product)
  166. else:
  167. if metadata.get("bitstream_sha256") is not None:
  168. raise ValueError("blocked-TD GUI must not carry a fabricated bitstream_sha256: " + product)
  169. products[f"products/{product}/{exe.name}"] = exe.read_bytes()
  170. run["gui"][product] = {"exe": exe.name, "sha256": result["sha256"], "metadata": metadata,
  171. "self_test": "PASS", "visual_gui_validation": gui.get("visual_gui_validation", "NOT_RUN")}
  172. debug.update(collect_evidence(args.gui_dir, "debug/native-gui"))
  173. hardware = {}
  174. for path in args.hardware_file:
  175. path = path.resolve()
  176. try:
  177. key = "sources/cpld/" + path.relative_to(ROOT.resolve()).as_posix()
  178. except ValueError:
  179. key = "hardware/originals/" + path.name
  180. data = path.read_bytes()
  181. if ((key in hardware and hardware[key] != data)
  182. or (key in sources and sources[key] != data)):
  183. raise ValueError("conflicting hardware file: " + key)
  184. hardware[key] = data
  185. start = (ROOT / f"docs/releases/v{version}.md").read_bytes()
  186. protocol_doc_path = args.protocol_doc.resolve() if args.protocol_doc is not None else (ROOT / DEFAULT_PROTOCOL_DOC)
  187. protocol_doc_bytes = None
  188. if protocol_doc_path.is_file():
  189. protocol_doc_bytes = protocol_doc_path.read_bytes()
  190. try:
  191. proto_rel = protocol_doc_path.relative_to(ROOT.resolve()).as_posix()
  192. except ValueError:
  193. proto_rel = protocol_doc_path.name
  194. run["protocol_doc"] = {
  195. "file": protocol_doc_path.name,
  196. "source_path": proto_rel,
  197. "sha256": digest(protocol_doc_bytes),
  198. "size_bytes": len(protocol_doc_bytes),
  199. }
  200. elif args.protocol_doc is not None:
  201. parser.error("missing --protocol-doc: " + str(protocol_doc_path))
  202. common = {"START-HERE.zh-CN.md": start, "RUN.json": encode(run),
  203. "EXCLUSIONS.json": encode({"excluded": ["working untracked user files except explicit --hardware-file inputs", "tool databases and vvp/vcd/fst intermediates", "ignored caches", "Git local config (including remote credentials)"],
  204. "source_scope": "All Git-tracked working files; explicit hardware originals included with repository-relative paths preserved; committed history in history/*.bundle"})}
  205. if protocol_doc_bytes is not None:
  206. common[protocol_doc_path.name] = protocol_doc_bytes
  207. tag = f"v{version}-{identity['commit'][:8]}"
  208. results = [
  209. package(out / f"Prod2U-Source-{tag}.zip", {**sources, **hardware, **common}, {"kind": "source", "version": version}),
  210. package(out / f"Prod2U-Debug-Logs-{tag}.zip", {**debug, **common}, {"kind": "debug", "version": version}),
  211. package(out / f"Prod2U-Analysis-{tag}.zip", {**sources, **products, **debug, **hardware, **common},
  212. {"kind": "analysis", "version": version}),
  213. ]
  214. # Convenient unpacked product folders and exact local delivery checksums.
  215. for name, data in products.items():
  216. target = out / name
  217. target.parent.mkdir(parents=True, exist_ok=True)
  218. target.write_bytes(data)
  219. (out / "START-HERE.zh-CN.md").write_bytes(start)
  220. if protocol_doc_bytes is not None:
  221. (out / protocol_doc_path.name).write_bytes(protocol_doc_bytes)
  222. (out / "RUN.json").write_bytes(encode(run))
  223. (out / "PACKAGE-RESULTS.json").write_bytes(encode(results))
  224. inventory = [{"path": p.relative_to(out).as_posix(), "sha256": digest(p.read_bytes()), "size_bytes": p.stat().st_size}
  225. for p in sorted(out.rglob("*")) if p.is_file() and p.name != "DELIVERY-SHA256.json"]
  226. (out / "DELIVERY-SHA256.json").write_bytes(encode(inventory))
  227. print(json.dumps(results, ensure_ascii=False, indent=2))
  228. return 0
  229. if __name__ == "__main__":
  230. raise SystemExit(main())