package_prod2u.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. #!/usr/bin/env python3
  2. """Single canonical Base/Current/Delivery package dispatcher.
  3. Product-specific legacy packagers remain implementation details; this entrypoint
  4. is the only supported command surface and performs fail-closed ZIP verification.
  5. """
  6. from __future__ import annotations
  7. import argparse, hashlib, json, shutil, stat, sys, tempfile, zipfile
  8. from pathlib import Path, PurePosixPath
  9. ROOT = Path(__file__).resolve().parents[1]
  10. if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))
  11. def sha(p: Path) -> str: return hashlib.sha256(p.read_bytes()).hexdigest()
  12. FIXED_TIME = (1980, 1, 1, 0, 0, 0)
  13. def _safe(name: str) -> str:
  14. p = PurePosixPath(name)
  15. if not name or name.startswith("/") or ".." in p.parts or "\\" in name:
  16. raise ValueError(f"unsafe package path: {name}")
  17. return name
  18. def _zip(path: Path, files: dict[str, bytes]) -> Path:
  19. path.parent.mkdir(parents=True, exist_ok=True)
  20. with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as z:
  21. for name in sorted(files):
  22. _safe(name)
  23. info = zipfile.ZipInfo(name, FIXED_TIME); info.create_system = 3
  24. info.external_attr = (stat.S_IFREG | 0o644) << 16
  25. z.writestr(info, files[name], compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)
  26. return path
  27. def _dual_paths() -> list[str]:
  28. """Current-only closure for both products, excluding build/cache/secrets."""
  29. wanted = {
  30. "projects/registry.json", "projects/mrdimm-chamber/project.json",
  31. "products/6400-front-rear/project.json", "products/6400-front-rear/source-closure.json",
  32. "products/6400-front-rear/analysis-replay-closure.json",
  33. "docs/prod2u-6400-front-back-protocol.zh-CN.md",
  34. "contracts/6400-manual.yaml", "contracts/6400-wire.yaml", "contracts/6400-snapshot.yaml",
  35. "contracts/6400-fixed-point.yaml", "contracts/channel-map.yaml",
  36. "contracts/host-i2c-pin-evidence.json", "contracts/mrdimm-wire.yaml",
  37. "constraints/prod2u_mrdimm.adc", "constraints/prod2u_mrdimm.sdc",
  38. "td/prod2u_mrdimm.prj", "td/syn/prod2u_mrdimm.tcl",
  39. "td/phy/prod2u_mrdimm.tcl", "td/bitgen/prod2u_mrdimm.tcl",
  40. "tools/generate_mrdimm_adc.py", "tools/generate_mrdimm_params.py",
  41. "constraints/prod2u_6400_front_back.adc", "constraints/prod2u_6400_front_back.sdc",
  42. "constraints/prod2u_p4_normal_v3.adc", "constraints/prod2u_p4_normal_v3.sdc",
  43. "td/prod2u_6400_front_back.prj", "td/syn/prod2u_6400_front_back.tcl",
  44. "td/phy/prod2u_6400_front_back.tcl", "td/bitgen/prod2u_6400_front_back.tcl",
  45. "td/prod2u_p4_normal_v3.prj", "td/syn/prod2u_p4_normal_v3.tcl",
  46. "td/phy/prod2u_p4_normal_v3.tcl", "td/bitgen/prod2u_p4_normal_v3.tcl",
  47. "tools/generate_target.py", "tools/generate_project.py", "tools/generate_6400_manual.py",
  48. "tools/target_registry.py", "tools/fw_cli.py", "tools/package_prod2u.py",
  49. "tools/mrdimm_hex_gui.py", "tools/build_mrdimm_hex_gui.py", "tools/6400_hex_gui.py",
  50. "tools/build_6400_hex_gui.py", "tools/overlay_6400_packages.py",
  51. "tools/_vendor/hth_protocol.py", "tools/_vendor/hth_protocol.sha256",
  52. "tools/fw_targets.py",
  53. "tests/sim/frame_rx_tb.v", "tests/sim/frame_tx_tb.v",
  54. "tests/sim/prod2u_6400_uart_e2e_tb.v",
  55. "tests/sim/motor_engine_tb.v", "tests/sim/prod2u_mrdimm_uart_e2e_tb.v",
  56. "tests/legacy/README.md",
  57. "generated/mrdimm/prod2u_mrdimm_params.vh",
  58. "src/top/prod2u_mrdimm_rs232_only_top.v",
  59. "src/control/mrdimm_output_core.v",
  60. "src/telemetry/mrdimm_snapshot_mux.v",
  61. "ACTIVE_GOAL_LOCK.yaml", "EXECUTION_PLAN.md", "PHASE_STATE.json",
  62. "TEST_IMPACT_MAP.yaml", "DECISION_TRACE.md", "RECOVERY_LOG.md", "EVIDENCE_INDEX.json",
  63. "evidence/solver-map.yaml",
  64. }
  65. for closure in (ROOT/"config/source_closure.json",
  66. ROOT/"products/6400-front-rear/source-closure.json",
  67. ROOT/"products/mrdimm-chamber/source-closure.json"):
  68. data = json.loads(closure.read_text(encoding="utf-8"))
  69. wanted.add(closure.relative_to(ROOT).as_posix())
  70. wanted.update(str(x).replace("\\", "/") for x in data.get("sources", []))
  71. wanted.update(str(x).replace("\\", "/") for x in data.get("files", []))
  72. for root in (ROOT/"src/generated", ROOT/"generated/6400"):
  73. if root.is_dir():
  74. wanted.update(p.relative_to(ROOT).as_posix() for p in root.rglob("*") if p.is_file())
  75. return sorted(p for p in wanted if (ROOT/p).is_file() and not any(x in p.lower() for x in ("__pycache__", ".pyc", ".pytest_cache", "secret", "token", "password")))
  76. def _dual_current(output: Path, base_zip: Path) -> Path:
  77. from tools.package_6400_canonical import base_metadata
  78. base_id, _manifest, base_manifest_sha = base_metadata(base_zip)
  79. files = {p: (ROOT/p).read_bytes() for p in _dual_paths()}
  80. import subprocess
  81. def _git(repo: Path, *args: str) -> str:
  82. return subprocess.check_output(["git", *args], cwd=repo, text=True).strip()
  83. commits = _git(ROOT, "rev-parse", "HEAD")
  84. repos = []
  85. for name, rel in (("cpld-temperature-control", ROOT),
  86. ("hth-platform", ROOT.parent / "hth-platform"),
  87. ("engineering-manifests", ROOT.parent / "engineering-manifests")):
  88. if (rel / ".git").exists():
  89. repos.append({"name": name, "commit": _git(rel, "rev-parse", "HEAD"),
  90. "tree": _git(rel, "rev-parse", "HEAD^{tree}")})
  91. contract_shas = []
  92. for p in (ROOT/"src/generated/host-contract.json", ROOT/"generated/6400/host-contract.json",
  93. ROOT/"generated/mrdimm/prod2u_mrdimm_params.vh"):
  94. if p.is_file(): contract_shas.append(sha(p))
  95. identity = {"repos": repos, "contract_shas": sorted(contract_shas), "base_id": base_id}
  96. snapshot = hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest()[:16]
  97. # Explicit overlay declarations (D08): every Current file that also
  98. # exists in Base with different content is a declared replacement.
  99. import zipfile as _zf
  100. base_hashes: dict[str, str] = {}
  101. with _zf.ZipFile(base_zip) as bz:
  102. for info in bz.infolist():
  103. name = info.filename
  104. if name in ("SHA256SUMS", "PACKAGE-MANIFEST.json", "PACKAGE-SELF-CHECK.py",
  105. "BASE-REQUIRED.json", "OVERLAY-RECEIPT.json"):
  106. continue
  107. base_hashes[name] = hashlib.sha256(bz.read(info)).hexdigest()
  108. replacements = [{"path": pth, "base_sha256": base_hashes[pth],
  109. "current_sha256": hashlib.sha256(data).hexdigest()}
  110. for pth, data in sorted(files.items())
  111. if pth in base_hashes and base_hashes[pth] != hashlib.sha256(data).hexdigest()]
  112. additions = sorted(p for p in files if p not in base_hashes)
  113. required = {"schema":"prod2u-base-required-v1","base_id":base_id,"base_manifest_sha256":base_manifest_sha,"base_zip_sha256":sha(base_zip)}
  114. files["BASE-REQUIRED.json"] = (json.dumps(required, indent=2, sort_keys=True)+"\n").encode()
  115. ws = {"schema":"prod2u-workspace-snapshot-v1", **identity, "snapshot_id": snapshot}
  116. files["WORKSPACE-SNAPSHOT.json"] = (json.dumps(ws, indent=2, sort_keys=True)+"\n").encode()
  117. files["OVERLAY-REPLACEMENTS.json"] = (json.dumps({"schema":"prod2u-overlay-replacements-v1","count":len(replacements),"replacements":replacements}, indent=2, sort_keys=True)+"\n").encode()
  118. files["OVERLAY-ADDITIONS.json"] = (json.dumps({"schema":"prod2u-overlay-additions-v1","count":len(additions),"additions":additions}, indent=2, sort_keys=True)+"\n").encode()
  119. files["EXCLUSIONS.json"]=(json.dumps({"excluded":[".git","venv","node_modules","__pycache__","BIT/GUI binaries","tokens/secrets/licenses","raw board files","large logs"]},indent=2,ensure_ascii=False)+"\n").encode()
  120. files["PACKAGE-SELF-CHECK.py"]=("import hashlib,json,pathlib,sys\nroot=pathlib.Path(__file__).parent\nm=json.loads((root/'PACKAGE-MANIFEST.json').read_text())\ndeclared={i['path'] for i in m['items']}\nactual={p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file()}\nmissing=declared-actual\nif missing:\n print('FILESET_MISMATCH missing='+str(sorted(missing)))\n sys.exit(2)\nfor i in m['items']:\n p=root/i['path']\n if not p.is_file() or hashlib.sha256(p.read_bytes()).hexdigest()!=i['sha256']:\n print('HASH_MISMATCH '+i['path'])\n sys.exit(2)\nprint('archive integrity OK; full replay requires Base '+m['base_id'])\nsys.exit(3)\n").encode()
  121. items = [{"path":p,"sha256":hashlib.sha256(data).hexdigest(),"size":len(data)} for p,data in sorted(files.items())]
  122. manifest = {"schema":"prod2u-dual-current-manifest-v1","profile":"current","products":["6400-front-rear","mrdimm-chamber"],"source_commit":commits,"snapshot_id":snapshot,"base_id":base_id,"repos":repos,"overlay_replacements_count":len(replacements),"items":items}
  123. files["PACKAGE-MANIFEST.json"]=(json.dumps(manifest,indent=2,sort_keys=True)+"\n").encode()
  124. files["SHA256SUMS"]="".join(f"{hashlib.sha256(data).hexdigest()} {name}\n" for name,data in sorted(files.items())).encode()
  125. return _zip(output/(f"Prod2U-CPLD-Analysis-Current-{snapshot}-base-{base_id}.zip"), files)
  126. def _dual_overlay(base_zip: Path, current_zip: Path, output: Path) -> Path:
  127. """Replay a dual Current over its matching Base without path escapes."""
  128. from tools.package_6400_canonical import extract_safe, base_metadata
  129. from tools.package_6400_canonical import sha_file as _sha_file
  130. base_id, _manifest, _base_manifest_sha = base_metadata(base_zip)
  131. with zipfile.ZipFile(current_zip) as z:
  132. manifest = json.loads(z.read("PACKAGE-MANIFEST.json"))
  133. reps_declared = json.loads(z.read("OVERLAY-REPLACEMENTS.json"))["replacements"] if "OVERLAY-REPLACEMENTS.json" in z.namelist() else []
  134. if manifest.get("schema") != "prod2u-dual-current-manifest-v1" or manifest.get("base_id") != base_id:
  135. raise SystemExit("BASE_ID_MISMATCH")
  136. if output.exists() and any(output.iterdir()): raise SystemExit("output directory must be empty")
  137. output.mkdir(parents=True, exist_ok=True)
  138. extract_safe(base_zip, output)
  139. with zipfile.ZipFile(current_zip) as z:
  140. for info in z.infolist():
  141. name = _safe(info.filename)
  142. dest = output / name
  143. dest.parent.mkdir(parents=True, exist_ok=True)
  144. dest.write_bytes(z.read(info))
  145. selfcheck = __import__("subprocess").run([sys.executable, "PACKAGE-SELF-CHECK.py"], cwd=output, text=True, capture_output=True)
  146. if selfcheck.returncode not in (0, 3): raise SystemExit("DUAL_OVERLAY_SELF_CHECK_FAILED: "+selfcheck.stdout+selfcheck.stderr)
  147. # declared replacements must match the actual Base/Current content diff
  148. for r in reps_declared:
  149. overlaid = output / r["path"]
  150. if not overlaid.is_file() or hashlib.sha256(overlaid.read_bytes()).hexdigest() != r["current_sha256"]:
  151. raise SystemExit("OVERLAY_REPLACEMENT_MISMATCH "+r["path"])
  152. required = (output/"products/6400-front-rear/project.json",
  153. output/"products/mrdimm-chamber/source-closure.json",
  154. output/"projects/mrdimm-chamber/project.json",
  155. output/"contracts/mrdimm-wire.yaml",
  156. output/"constraints/prod2u_mrdimm.adc",
  157. output/"src/top/prod2u_mrdimm_rs232_only_top.v",
  158. output/"src/motor/motor_engine.v")
  159. missing = [str(q) for q in required if not q.is_file()]
  160. if missing: raise SystemExit("DUAL_OVERLAY_CLOSURE_INCOMPLETE "+", ".join(missing))
  161. receipt = {"schema":"prod2u-dual-overlay-receipt-v1","status":"PASS","base_id":base_id,"base_zip_sha256":_sha_file(base_zip),"current_zip_sha256":_sha_file(current_zip),"self_check":selfcheck.stdout.strip()}
  162. (output/"OVERLAY-RECEIPT.json").write_text(json.dumps(receipt, indent=2, sort_keys=True)+"\n", encoding="utf-8")
  163. return output
  164. def verify(path: Path) -> dict:
  165. raw_archive = path.read_bytes()
  166. with zipfile.ZipFile(path) as z:
  167. names = z.namelist()
  168. if names != sorted(names) or len(names) != len(set(names)): raise SystemExit("invalid ZIP ordering or duplicate members")
  169. if any(n.startswith("/") or ".." in Path(n).parts for n in names): raise SystemExit("unsafe ZIP member")
  170. with tempfile.TemporaryDirectory() as t:
  171. d=Path(t); z.extractall(d)
  172. sums=d/"SHA256SUMS"
  173. if sums.is_file():
  174. for line in sums.read_text(encoding="utf-8").splitlines():
  175. digest,name=line.split(" ",1)
  176. if not (d/name).is_file() or sha(d/name)!=digest: raise SystemExit("HASH_MISMATCH "+name)
  177. try: manifest = json.loads((d/"PACKAGE-MANIFEST.json").read_text(encoding="utf-8"))
  178. except Exception: manifest = None
  179. if isinstance(manifest, dict) and manifest.get("schema") == "prod2u-dual-current-manifest-v1":
  180. # manifest item set must equal the archive file set exactly
  181. declared = {i["path"] for i in manifest["items"]}
  182. actual = {n for n in names if n not in ("PACKAGE-MANIFEST.json", "SHA256SUMS")}
  183. if declared != actual:
  184. raise SystemExit(f"MANIFEST_FILESET_MISMATCH missing={sorted(declared-actual)} extra={sorted(actual-declared)}")
  185. for i in manifest["items"]:
  186. fp = d/i["path"]
  187. if not fp.is_file() or sha(fp) != i["sha256"]:
  188. raise SystemExit("MANIFEST_HASH_MISMATCH "+i["path"])
  189. # case-insensitive filesystem collision guard
  190. lowered = [n.lower() for n in names]
  191. if len(lowered) != len(set(lowered)): raise SystemExit("CASE_COLLISION_MEMBERS")
  192. # declared overlay replacements must match reality
  193. reps_file = d/"OVERLAY-REPLACEMENTS.json"
  194. if reps_file.is_file():
  195. reps = {r["path"]: r["base_sha256"] for r in json.loads(reps_file.read_text(encoding="utf-8"))["replacements"]}
  196. if manifest.get("overlay_replacements_count") != len(reps):
  197. raise SystemExit("OVERLAY_REPLACEMENTS_COUNT_MISMATCH")
  198. canonical = _zip(d/".canonical.zip", {n: (d/n).read_bytes() for n in names})
  199. if canonical.read_bytes() != raw_archive: raise SystemExit("NON_CANONICAL_OR_TAMPERED_ARCHIVE")
  200. return {"status":"PASS","package":str(path.resolve()),"sha256":sha(path)}
  201. def dispatch_legacy(args: argparse.Namespace) -> Path:
  202. from tools import package_6400_canonical as c
  203. if args.action == "base": return c.package_base(args.output_dir)
  204. if args.action == "current": return _dual_current(args.output_dir, args.base_zip)
  205. if args.action == "overlay":
  206. with zipfile.ZipFile(args.current_zip) as z:
  207. try: current_schema = json.loads(z.read("PACKAGE-MANIFEST.json")).get("schema")
  208. except Exception: current_schema = None
  209. if current_schema == "prod2u-dual-current-manifest-v1":
  210. return _dual_overlay(args.base_zip, args.current_zip, args.output_dir)
  211. from tools.overlay_6400_packages import run
  212. run(args.base_zip, args.current_zip, args.output_dir)
  213. return args.output_dir
  214. raise SystemExit("unsupported legacy action")
  215. def main(argv=None) -> int:
  216. ap=argparse.ArgumentParser(description=__doc__); sp=ap.add_subparsers(dest="action",required=True)
  217. for name in ("base","current","all"):
  218. p=sp.add_parser(name); p.add_argument("--output-dir",type=Path,default=ROOT/"dist")
  219. if name=="current": p.add_argument("--base-zip",type=Path,required=True)
  220. p=sp.add_parser("verify"); p.add_argument("package",type=Path)
  221. p=sp.add_parser("overlay"); p.add_argument("--base-zip",type=Path,required=True); p.add_argument("--current-zip",type=Path,required=True); p.add_argument("--output-dir",type=Path,required=True)
  222. p=sp.add_parser("delivery"); p.add_argument("--product",choices=("6400-v1.1","mrdimm-v1.2"),required=True); p.add_argument("--output-dir",type=Path,default=ROOT/"dist"); p.add_argument("--td-receipt",type=Path); p.add_argument("--gui-exe",type=Path); p.add_argument("--gui-zip",type=Path); p.add_argument("--status-json",type=Path)
  223. a=ap.parse_args(argv)
  224. if a.action=="verify": print(json.dumps(verify(a.package),indent=2)); return 0
  225. if a.action == "all":
  226. base = dispatch_legacy(argparse.Namespace(action="base", output_dir=a.output_dir))
  227. current = dispatch_legacy(argparse.Namespace(action="current", output_dir=a.output_dir, base_zip=base))
  228. print(json.dumps({"status":"PASS","base":verify(base),"current":verify(current)}, indent=2))
  229. return 0
  230. if a.action in ("base","current","overlay"):
  231. result=dispatch_legacy(a)
  232. if a.action == "overlay":
  233. receipt = result / "OVERLAY-RECEIPT.json"
  234. payload = json.loads(receipt.read_text(encoding="utf-8")) if receipt.is_file() else {"status":"PASS"}
  235. print(json.dumps({**payload, "action": a.action, "output_dir": str(result.resolve())}, indent=2))
  236. else:
  237. print(json.dumps({**verify(result),"action":a.action},indent=2))
  238. return 0
  239. if a.action=="delivery":
  240. if a.product=="6400-v1.1":
  241. if not all((a.td_receipt,a.gui_exe,a.gui_zip,a.status_json)): ap.error("6400 delivery requires --td-receipt --gui-exe --gui-zip --status-json")
  242. from tools.package_target import package_6400_canonical
  243. result=package_6400_canonical.package_delivery(a.output_dir,a.td_receipt,a.gui_exe,a.gui_zip,a.status_json)
  244. else:
  245. required=(a.td_receipt,a.gui_exe,a.gui_zip)
  246. if not all(required): ap.error("mrdimm delivery requires --td-receipt --gui-exe --gui-zip")
  247. a.output_dir.mkdir(parents=True,exist_ok=True); commit="unknown"; receipt=json.loads(a.td_receipt.read_text(encoding="utf-8")); commit=str(receipt.get("commit",commit))
  248. # TD receipts retain the Linux artifact path. Resolve the copied
  249. # bitstream beside the receipt (the Windows fetch step preserves
  250. # this basename) so Delivery always contains the actual BIT.
  251. bit = None
  252. bit_meta = receipt.get("measurement_artifacts", {}).get("bitstream", {})
  253. bit_name = Path(str(bit_meta.get("path", ""))).name
  254. candidates = [a.td_receipt.parent / bit_name] if bit_name else []
  255. candidates += sorted(a.td_receipt.parent.glob("*.bit"))
  256. for candidate in candidates:
  257. if candidate.is_file(): bit = candidate; break
  258. if bit is None: ap.error("MRDIMM delivery requires fetched TD bitstream beside receipt")
  259. status = str(receipt.get("status", "unknown")).upper()
  260. candidate_status = {"status": "PASS" if status == "PASS" else "PARTIAL", "td_status": status, "timing_gate": receipt.get("timing_gate", {}), "structural_gate": receipt.get("structural_gate", {})}
  261. files = {
  262. "prod2u-mrdimm-v1.2.bit": bit.read_bytes(),
  263. "TD-RECEIPT.json": a.td_receipt.read_bytes(),
  264. a.gui_exe.name: a.gui_exe.read_bytes(),
  265. a.gui_zip.name: a.gui_zip.read_bytes(),
  266. "Wire-Contract.md": (ROOT/"projects/prod2u-door-temp/requirements.zh-CN.md").read_bytes(),
  267. "Snapshot-Contract.json": (ROOT/"src/generated/host-contract.json").read_bytes(),
  268. "CANDIDATE-STATUS.json": json.dumps(candidate_status,indent=2,sort_keys=True).encode()+b"\n",
  269. }
  270. manifest={"schema":"prod2u-delivery-v1","product":"mrdimm-chamber","board":"FCB V1.2","commit":commit,"status":"PASS" if status == "PASS" else "PARTIAL","hardware":"NOT RUN","members":sorted(files)}
  271. files["RELEASE-IDENTITY.json"] = (json.dumps(manifest,indent=2,sort_keys=True)+"\n").encode()
  272. files["SHA256SUMS"] = "".join(f"{hashlib.sha256(data).hexdigest()} {name}\n" for name,data in sorted(files.items())).encode()
  273. result=a.output_dir/f"Prod2U-MRDIMM-V1.2-Delivery-{commit[:8]}.zip"; _zip(result, files)
  274. print(json.dumps({**verify(result),"action":"delivery","product":a.product},indent=2)); return 0
  275. return 2
  276. if __name__=="__main__": raise SystemExit(main())