package_prod2u.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. }
  49. for closure in (ROOT/"config/source_closure.json", ROOT/"products/6400-front-rear/source-closure.json"):
  50. data = json.loads(closure.read_text(encoding="utf-8"))
  51. wanted.add(closure.relative_to(ROOT).as_posix())
  52. wanted.update(str(x).replace("\\", "/") for x in data.get("sources", []))
  53. for root in (ROOT/"src/generated", ROOT/"generated/6400"):
  54. if root.is_dir():
  55. wanted.update(p.relative_to(ROOT).as_posix() for p in root.rglob("*") if p.is_file())
  56. 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")))
  57. def _dual_current(output: Path, base_zip: Path) -> Path:
  58. from tools.package_6400_canonical import base_metadata
  59. base_id, _manifest, base_manifest_sha = base_metadata(base_zip)
  60. files = {p: (ROOT/p).read_bytes() for p in _dual_paths()}
  61. commits = __import__("subprocess").check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
  62. contract_shas = []
  63. for p in (ROOT/"src/generated/host-contract.json", ROOT/"generated/6400/host-contract.json"):
  64. if p.is_file(): contract_shas.append(sha(p))
  65. snapshot = hashlib.sha256((commits + "".join(sorted(contract_shas)) + base_id).encode()).hexdigest()[:16]
  66. required = {"schema":"prod2u-base-required-v1","base_id":base_id,"base_manifest_sha256":base_manifest_sha,"base_zip_sha256":sha(base_zip)}
  67. files["BASE-REQUIRED.json"] = (json.dumps(required, indent=2, sort_keys=True)+"\n").encode()
  68. items = [{"path":p,"sha256":hashlib.sha256(data).hexdigest(),"size":len(data)} for p,data in sorted(files.items())]
  69. 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}
  70. files["PACKAGE-MANIFEST.json"]=(json.dumps(manifest,indent=2,sort_keys=True)+"\n").encode()
  71. 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()
  72. 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()
  73. 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()
  74. files["SHA256SUMS"]="".join(f"{hashlib.sha256(data).hexdigest()} {name}\n" for name,data in sorted(files.items())).encode()
  75. return _zip(output/(f"Prod2U-CPLD-Analysis-Current-{snapshot}-base-{base_id}.zip"), files)
  76. def _dual_overlay(base_zip: Path, current_zip: Path, output: Path) -> Path:
  77. """Replay a dual Current over its matching Base without path escapes."""
  78. from tools.package_6400_canonical import extract_safe, base_metadata
  79. from tools.package_6400_canonical import sha_file as _sha_file
  80. base_id, _manifest, _base_manifest_sha = base_metadata(base_zip)
  81. with zipfile.ZipFile(current_zip) as z:
  82. manifest = json.loads(z.read("PACKAGE-MANIFEST.json"))
  83. if manifest.get("schema") != "prod2u-dual-current-manifest-v1" or manifest.get("base_id") != base_id:
  84. raise SystemExit("BASE_ID_MISMATCH")
  85. if output.exists() and any(output.iterdir()): raise SystemExit("output directory must be empty")
  86. output.mkdir(parents=True, exist_ok=True)
  87. extract_safe(base_zip, output)
  88. with zipfile.ZipFile(current_zip) as z:
  89. for info in z.infolist():
  90. name = _safe(info.filename)
  91. dest = output / name
  92. dest.parent.mkdir(parents=True, exist_ok=True)
  93. dest.write_bytes(z.read(info))
  94. selfcheck = __import__("subprocess").run([sys.executable, "PACKAGE-SELF-CHECK.py"], cwd=output, text=True, capture_output=True)
  95. if selfcheck.returncode != 0: raise SystemExit("DUAL_OVERLAY_SELF_CHECK_FAILED")
  96. required = (output/"projects/prod2u-door-temp/project.json", output/"products/6400-front-rear/project.json")
  97. if not all(p.is_file() for p in required): raise SystemExit("DUAL_OVERLAY_CLOSURE_INCOMPLETE")
  98. 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()}
  99. (output/"OVERLAY-RECEIPT.json").write_text(json.dumps(receipt, indent=2, sort_keys=True)+"\n", encoding="utf-8")
  100. return output
  101. def verify(path: Path) -> dict:
  102. raw_archive = path.read_bytes()
  103. with zipfile.ZipFile(path) as z:
  104. names = z.namelist()
  105. if names != sorted(names) or len(names) != len(set(names)): raise SystemExit("invalid ZIP ordering or duplicate members")
  106. if any(n.startswith("/") or ".." in Path(n).parts for n in names): raise SystemExit("unsafe ZIP member")
  107. with tempfile.TemporaryDirectory() as t:
  108. d=Path(t); z.extractall(d)
  109. sums=d/"SHA256SUMS"
  110. if sums.is_file():
  111. for line in sums.read_text(encoding="utf-8").splitlines():
  112. digest,name=line.split(" ",1)
  113. if not (d/name).is_file() or sha(d/name)!=digest: raise SystemExit("HASH_MISMATCH "+name)
  114. try: schema = json.loads((d/"PACKAGE-MANIFEST.json").read_text(encoding="utf-8")).get("schema")
  115. except Exception: schema = None
  116. if schema == "prod2u-dual-current-manifest-v1":
  117. canonical = _zip(d/".canonical.zip", {n: (d/n).read_bytes() for n in names})
  118. if canonical.read_bytes() != raw_archive: raise SystemExit("NON_CANONICAL_OR_TAMPERED_ARCHIVE")
  119. return {"status":"PASS","package":str(path.resolve()),"sha256":sha(path)}
  120. def dispatch_legacy(args: argparse.Namespace) -> Path:
  121. from tools import package_6400_canonical as c
  122. if args.action == "base": return c.package_base(args.output_dir)
  123. if args.action == "current": return _dual_current(args.output_dir, args.base_zip)
  124. if args.action == "overlay":
  125. with zipfile.ZipFile(args.current_zip) as z:
  126. try: current_schema = json.loads(z.read("PACKAGE-MANIFEST.json")).get("schema")
  127. except Exception: current_schema = None
  128. if current_schema == "prod2u-dual-current-manifest-v1":
  129. return _dual_overlay(args.base_zip, args.current_zip, args.output_dir)
  130. from tools.overlay_6400_packages import run
  131. run(args.base_zip, args.current_zip, args.output_dir)
  132. return args.output_dir
  133. raise SystemExit("unsupported legacy action")
  134. def main(argv=None) -> int:
  135. ap=argparse.ArgumentParser(description=__doc__); sp=ap.add_subparsers(dest="action",required=True)
  136. for name in ("base","current"):
  137. p=sp.add_parser(name); p.add_argument("--output-dir",type=Path,default=ROOT/"dist")
  138. if name=="current": p.add_argument("--base-zip",type=Path,required=True)
  139. p=sp.add_parser("verify"); p.add_argument("package",type=Path)
  140. 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)
  141. 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)
  142. a=ap.parse_args(argv)
  143. if a.action=="verify": print(json.dumps(verify(a.package),indent=2)); return 0
  144. if a.action in ("base","current","overlay"):
  145. result=dispatch_legacy(a)
  146. if a.action == "overlay":
  147. receipt = result / "OVERLAY-RECEIPT.json"
  148. payload = json.loads(receipt.read_text(encoding="utf-8")) if receipt.is_file() else {"status":"PASS"}
  149. print(json.dumps({**payload, "action": a.action, "output_dir": str(result.resolve())}, indent=2))
  150. else:
  151. print(json.dumps({**verify(result),"action":a.action},indent=2))
  152. return 0
  153. if a.action=="delivery":
  154. if a.product=="6400-v1.1":
  155. 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")
  156. from tools.package_target import package_6400_canonical
  157. result=package_6400_canonical.package_delivery(a.output_dir,a.td_receipt,a.gui_exe,a.gui_zip,a.status_json)
  158. else:
  159. required=(a.td_receipt,a.gui_exe,a.gui_zip)
  160. if not all(required): ap.error("mrdimm delivery requires --td-receipt --gui-exe --gui-zip")
  161. 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)); stage=Path(tempfile.mkdtemp(prefix="mrdimm-delivery-"))
  162. for src,name in ((a.td_receipt,"TD-RECEIPT.json"),(a.gui_exe,a.gui_exe.name),(a.gui_zip,a.gui_zip.name),(ROOT/"projects/prod2u-door-temp/requirements.zh-CN.md","Wire-Contract.md"),(ROOT/"src/generated/host-contract.json","Snapshot-Contract.json")):
  163. shutil.copy2(src,stage/name)
  164. manifest={"schema":"prod2u-delivery-v1","product":"mrdimm-chamber","board":"FCB V1.2","commit":commit,"hardware":"NOT RUN","members":sorted(p.name for p in stage.iterdir())}; (stage/"RELEASE-IDENTITY.json").write_text(json.dumps(manifest,indent=2)+"\n",encoding="utf-8"); (stage/"SHA256SUMS").write_text("".join(f"{sha(p)} {p.name}\n" for p in sorted(stage.iterdir())),encoding="utf-8"); result=a.output_dir/f"Prod2U-MRDIMM-V1.2-Delivery-{commit[:8]}.zip"; shutil.make_archive(str(result.with_suffix("")),"zip",root_dir=stage); shutil.rmtree(stage,ignore_errors=True)
  165. print(json.dumps({**verify(result),"action":"delivery","product":a.product},indent=2)); return 0
  166. return 2
  167. if __name__=="__main__": raise SystemExit(main())