package_prod2u.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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/prod2u-door-temp/project.json",
  31. "projects/prod2u-door-temp/requirements.zh-CN.md",
  32. "products/6400-front-rear/project.json", "products/6400-front-rear/source-closure.json",
  33. "products/6400-front-rear/analysis-replay-closure.json",
  34. "docs/prod2u-6400-front-back-protocol.zh-CN.md",
  35. "contracts/6400-manual.yaml", "contracts/6400-wire.yaml", "contracts/6400-snapshot.yaml",
  36. "constraints/prod2u_6400_front_back.adc", "constraints/prod2u_6400_front_back.sdc",
  37. "constraints/prod2u_p4_normal_v3.adc", "constraints/prod2u_p4_normal_v3.sdc",
  38. "td/prod2u_6400_front_back.prj", "td/syn/prod2u_6400_front_back.tcl",
  39. "td/phy/prod2u_6400_front_back.tcl", "td/bitgen/prod2u_6400_front_back.tcl",
  40. "td/prod2u_p4_normal_v3.prj", "td/syn/prod2u_p4_normal_v3.tcl",
  41. "td/phy/prod2u_p4_normal_v3.tcl", "td/bitgen/prod2u_p4_normal_v3.tcl",
  42. "tools/generate_target.py", "tools/generate_project.py", "tools/generate_6400_manual.py",
  43. "tools/target_registry.py", "tools/fw_cli.py", "tools/package_prod2u.py",
  44. "tools/mrdimm_hex_gui.py", "tools/build_mrdimm_hex_gui.py", "tools/6400_hex_gui.py",
  45. "tools/build_6400_hex_gui.py", "tools/overlay_6400_packages.py",
  46. "ACTIVE_GOAL_LOCK.yaml", "EXECUTION_PLAN.md", "PHASE_STATE.json",
  47. "TEST_IMPACT_MAP.yaml", "DECISION_TRACE.md", "RECOVERY_LOG.md", "EVIDENCE_INDEX.json",
  48. "evidence/solver-map.yaml",
  49. }
  50. for closure in (ROOT/"config/source_closure.json", ROOT/"products/6400-front-rear/source-closure.json"):
  51. data = json.loads(closure.read_text(encoding="utf-8"))
  52. wanted.add(closure.relative_to(ROOT).as_posix())
  53. wanted.update(str(x).replace("\\", "/") for x in data.get("sources", []))
  54. for root in (ROOT/"src/generated", ROOT/"generated/6400"):
  55. if root.is_dir():
  56. wanted.update(p.relative_to(ROOT).as_posix() for p in root.rglob("*") if p.is_file())
  57. 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")))
  58. def _dual_current(output: Path, base_zip: Path) -> Path:
  59. from tools.package_6400_canonical import base_metadata
  60. base_id, _manifest, base_manifest_sha = base_metadata(base_zip)
  61. files = {p: (ROOT/p).read_bytes() for p in _dual_paths()}
  62. commits = __import__("subprocess").check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
  63. contract_shas = []
  64. for p in (ROOT/"src/generated/host-contract.json", ROOT/"generated/6400/host-contract.json"):
  65. if p.is_file(): contract_shas.append(sha(p))
  66. snapshot = hashlib.sha256((commits + "".join(sorted(contract_shas)) + base_id).encode()).hexdigest()[:16]
  67. required = {"schema":"prod2u-base-required-v1","base_id":base_id,"base_manifest_sha256":base_manifest_sha,"base_zip_sha256":sha(base_zip)}
  68. files["BASE-REQUIRED.json"] = (json.dumps(required, indent=2, sort_keys=True)+"\n").encode()
  69. items = [{"path":p,"sha256":hashlib.sha256(data).hexdigest(),"size":len(data)} for p,data in sorted(files.items())]
  70. 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,"items":items}
  71. files["PACKAGE-MANIFEST.json"]=(json.dumps(manifest,indent=2,sort_keys=True)+"\n").encode()
  72. files["PACKAGE-SELF-CHECK.py"]=("import hashlib,json,pathlib\nroot=pathlib.Path(__file__).parent\nm=json.loads((root/'PACKAGE-MANIFEST.json').read_text())\nfor i in m['items']:\n p=root/i['path']; assert p.is_file() and hashlib.sha256(p.read_bytes()).hexdigest()==i['sha256']\nprint('PASS')\n").encode()
  73. files["START-HERE.zh-CN.md"]=("# Prod2U 双产品 Current\n\n包含 6400 V1.1 与 MRDIMM V1.2 Source Closure;需匹配 Base ZIP 后 Overlay。硬件与 Fresh TD 状态以候选记录为准。\n").encode()
  74. 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()
  75. files["SHA256SUMS"]="".join(f"{hashlib.sha256(data).hexdigest()} {name}\n" for name,data in sorted(files.items())).encode()
  76. return _zip(output/(f"Prod2U-CPLD-Analysis-Current-{snapshot}-base-{base_id}.zip"), files)
  77. def _dual_overlay(base_zip: Path, current_zip: Path, output: Path) -> Path:
  78. """Replay a dual Current over its matching Base without path escapes."""
  79. from tools.package_6400_canonical import extract_safe, base_metadata
  80. from tools.package_6400_canonical import sha_file as _sha_file
  81. base_id, _manifest, _base_manifest_sha = base_metadata(base_zip)
  82. with zipfile.ZipFile(current_zip) as z:
  83. manifest = json.loads(z.read("PACKAGE-MANIFEST.json"))
  84. if manifest.get("schema") != "prod2u-dual-current-manifest-v1" or manifest.get("base_id") != base_id:
  85. raise SystemExit("BASE_ID_MISMATCH")
  86. if output.exists() and any(output.iterdir()): raise SystemExit("output directory must be empty")
  87. output.mkdir(parents=True, exist_ok=True)
  88. extract_safe(base_zip, output)
  89. with zipfile.ZipFile(current_zip) as z:
  90. for info in z.infolist():
  91. name = _safe(info.filename)
  92. dest = output / name
  93. dest.parent.mkdir(parents=True, exist_ok=True)
  94. dest.write_bytes(z.read(info))
  95. selfcheck = __import__("subprocess").run([sys.executable, "PACKAGE-SELF-CHECK.py"], cwd=output, text=True, capture_output=True)
  96. if selfcheck.returncode != 0: raise SystemExit("DUAL_OVERLAY_SELF_CHECK_FAILED")
  97. required = (output/"projects/prod2u-door-temp/project.json", output/"products/6400-front-rear/project.json")
  98. if not all(p.is_file() for p in required): raise SystemExit("DUAL_OVERLAY_CLOSURE_INCOMPLETE")
  99. 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()}
  100. (output/"OVERLAY-RECEIPT.json").write_text(json.dumps(receipt, indent=2, sort_keys=True)+"\n", encoding="utf-8")
  101. return output
  102. def verify(path: Path) -> dict:
  103. raw_archive = path.read_bytes()
  104. with zipfile.ZipFile(path) as z:
  105. names = z.namelist()
  106. if names != sorted(names) or len(names) != len(set(names)): raise SystemExit("invalid ZIP ordering or duplicate members")
  107. if any(n.startswith("/") or ".." in Path(n).parts for n in names): raise SystemExit("unsafe ZIP member")
  108. with tempfile.TemporaryDirectory() as t:
  109. d=Path(t); z.extractall(d)
  110. sums=d/"SHA256SUMS"
  111. if sums.is_file():
  112. for line in sums.read_text(encoding="utf-8").splitlines():
  113. digest,name=line.split(" ",1)
  114. if not (d/name).is_file() or sha(d/name)!=digest: raise SystemExit("HASH_MISMATCH "+name)
  115. try: schema = json.loads((d/"PACKAGE-MANIFEST.json").read_text(encoding="utf-8")).get("schema")
  116. except Exception: schema = None
  117. if schema == "prod2u-dual-current-manifest-v1":
  118. canonical = _zip(d/".canonical.zip", {n: (d/n).read_bytes() for n in names})
  119. if canonical.read_bytes() != raw_archive: raise SystemExit("NON_CANONICAL_OR_TAMPERED_ARCHIVE")
  120. return {"status":"PASS","package":str(path.resolve()),"sha256":sha(path)}
  121. def dispatch_legacy(args: argparse.Namespace) -> Path:
  122. from tools import package_6400_canonical as c
  123. if args.action == "base": return c.package_base(args.output_dir)
  124. if args.action == "current": return _dual_current(args.output_dir, args.base_zip)
  125. if args.action == "overlay":
  126. with zipfile.ZipFile(args.current_zip) as z:
  127. try: current_schema = json.loads(z.read("PACKAGE-MANIFEST.json")).get("schema")
  128. except Exception: current_schema = None
  129. if current_schema == "prod2u-dual-current-manifest-v1":
  130. return _dual_overlay(args.base_zip, args.current_zip, args.output_dir)
  131. from tools.overlay_6400_packages import run
  132. run(args.base_zip, args.current_zip, args.output_dir)
  133. return args.output_dir
  134. raise SystemExit("unsupported legacy action")
  135. def main(argv=None) -> int:
  136. ap=argparse.ArgumentParser(description=__doc__); sp=ap.add_subparsers(dest="action",required=True)
  137. for name in ("base","current","all"):
  138. p=sp.add_parser(name); p.add_argument("--output-dir",type=Path,default=ROOT/"dist")
  139. if name=="current": p.add_argument("--base-zip",type=Path,required=True)
  140. p=sp.add_parser("verify"); p.add_argument("package",type=Path)
  141. 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)
  142. 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)
  143. a=ap.parse_args(argv)
  144. if a.action=="verify": print(json.dumps(verify(a.package),indent=2)); return 0
  145. if a.action == "all":
  146. base = dispatch_legacy(argparse.Namespace(action="base", output_dir=a.output_dir))
  147. current = dispatch_legacy(argparse.Namespace(action="current", output_dir=a.output_dir, base_zip=base))
  148. print(json.dumps({"status":"PASS","base":verify(base),"current":verify(current)}, indent=2))
  149. return 0
  150. if a.action in ("base","current","overlay"):
  151. result=dispatch_legacy(a)
  152. if a.action == "overlay":
  153. receipt = result / "OVERLAY-RECEIPT.json"
  154. payload = json.loads(receipt.read_text(encoding="utf-8")) if receipt.is_file() else {"status":"PASS"}
  155. print(json.dumps({**payload, "action": a.action, "output_dir": str(result.resolve())}, indent=2))
  156. else:
  157. print(json.dumps({**verify(result),"action":a.action},indent=2))
  158. return 0
  159. if a.action=="delivery":
  160. if a.product=="6400-v1.1":
  161. 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")
  162. from tools.package_target import package_6400_canonical
  163. result=package_6400_canonical.package_delivery(a.output_dir,a.td_receipt,a.gui_exe,a.gui_zip,a.status_json)
  164. else:
  165. required=(a.td_receipt,a.gui_exe,a.gui_zip)
  166. if not all(required): ap.error("mrdimm delivery requires --td-receipt --gui-exe --gui-zip")
  167. 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))
  168. # TD receipts retain the Linux artifact path. Resolve the copied
  169. # bitstream beside the receipt (the Windows fetch step preserves
  170. # this basename) so Delivery always contains the actual BIT.
  171. bit = None
  172. bit_meta = receipt.get("measurement_artifacts", {}).get("bitstream", {})
  173. bit_name = Path(str(bit_meta.get("path", ""))).name
  174. candidates = [a.td_receipt.parent / bit_name] if bit_name else []
  175. candidates += sorted(a.td_receipt.parent.glob("*.bit"))
  176. for candidate in candidates:
  177. if candidate.is_file(): bit = candidate; break
  178. if bit is None: ap.error("MRDIMM delivery requires fetched TD bitstream beside receipt")
  179. status = str(receipt.get("status", "unknown")).upper()
  180. candidate_status = {"status": "PASS" if status == "PASS" else "PARTIAL", "td_status": status, "timing_gate": receipt.get("timing_gate", {}), "structural_gate": receipt.get("structural_gate", {})}
  181. files = {
  182. "prod2u-mrdimm-v1.2.bit": bit.read_bytes(),
  183. "TD-RECEIPT.json": a.td_receipt.read_bytes(),
  184. a.gui_exe.name: a.gui_exe.read_bytes(),
  185. a.gui_zip.name: a.gui_zip.read_bytes(),
  186. "Wire-Contract.md": (ROOT/"projects/prod2u-door-temp/requirements.zh-CN.md").read_bytes(),
  187. "Snapshot-Contract.json": (ROOT/"src/generated/host-contract.json").read_bytes(),
  188. "CANDIDATE-STATUS.json": json.dumps(candidate_status,indent=2,sort_keys=True).encode()+b"\n",
  189. }
  190. 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)}
  191. files["RELEASE-IDENTITY.json"] = (json.dumps(manifest,indent=2,sort_keys=True)+"\n").encode()
  192. files["SHA256SUMS"] = "".join(f"{hashlib.sha256(data).hexdigest()} {name}\n" for name,data in sorted(files.items())).encode()
  193. result=a.output_dir/f"Prod2U-MRDIMM-V1.2-Delivery-{commit[:8]}.zip"; _zip(result, files)
  194. print(json.dumps({**verify(result),"action":"delivery","product":a.product},indent=2)); return 0
  195. return 2
  196. if __name__=="__main__": raise SystemExit(main())