package_6400_canonical.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. #!/usr/bin/env python3
  2. """Deterministic Base/Current/Delivery packager for 6400-front-rear."""
  3. from __future__ import annotations
  4. import hashlib
  5. import json
  6. import os
  7. import shutil
  8. import stat
  9. import subprocess
  10. import sys
  11. import tempfile
  12. import zipfile
  13. from pathlib import Path, PurePosixPath
  14. ROOT = Path(__file__).resolve().parents[1]
  15. FIXED_TIME = (1980, 1, 1, 0, 0, 0)
  16. COMMON = (
  17. "PACKAGE-MANIFEST.json",
  18. "SHA256SUMS",
  19. "PACKAGE-SELF-CHECK.py",
  20. "START-HERE.zh-CN.md",
  21. "EXCLUSIONS.json",
  22. )
  23. BASE_IDENTITY_FILES = ("BASE-IDENTITY.json", "BASE-PACKAGE-MANIFEST.json", "BASE-SHA256SUMS")
  24. EXCLUSION_RULES = [
  25. ".git/.repo/worktrees", ".cursor/.codex/Playwright cache", "__pycache__/pytest cache",
  26. "venv/node_modules", "build/dist/TD/Formal workdir", "fuzz corpus/raw dataset",
  27. "raw BRD/PDF/DSN", "old bitstream/GUI/logs", "unrelated products",
  28. "agent scratch/stale progress", "nested archives unless explicitly selected",
  29. ]
  30. def sha_bytes(data: bytes) -> str:
  31. return hashlib.sha256(data).hexdigest()
  32. def sha_file(path: Path) -> str:
  33. digest = hashlib.sha256()
  34. with path.open("rb") as handle:
  35. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  36. digest.update(chunk)
  37. return digest.hexdigest()
  38. def git(*args: str) -> str:
  39. return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
  40. def clean_identity() -> tuple[str, str]:
  41. if git("status", "--porcelain"):
  42. raise SystemExit("canonical package requires an exact clean commit")
  43. return git("rev-parse", "HEAD"), git("rev-parse", "HEAD^{tree}")
  44. def safe_name(name: str) -> str:
  45. if not name or "\\" in name or name.startswith("/"):
  46. raise ValueError(f"unsafe ZIP member: {name!r}")
  47. parts = PurePosixPath(name).parts
  48. if ".." in parts or "." in parts:
  49. raise ValueError(f"unsafe ZIP member: {name!r}")
  50. return name
  51. def role_for(path: str) -> str:
  52. if path.startswith("generated/") or path.startswith("contracts/"):
  53. return "contract"
  54. if path.startswith("src/"):
  55. return "rtl-source"
  56. if path.startswith("tests/"):
  57. return "verification"
  58. if path.startswith("tools/"):
  59. return "replay-tool"
  60. if path.endswith(".bit"):
  61. return "bitstream"
  62. if path.endswith(".exe"):
  63. return "offline-gui"
  64. if "RECEIPT" in path or "STATUS" in path:
  65. return "evidence"
  66. return "metadata"
  67. def read_paths(paths: list[str]) -> dict[str, bytes]:
  68. out: dict[str, bytes] = {}
  69. for relative in sorted(set(paths)):
  70. safe_name(relative)
  71. source = ROOT / relative
  72. if not source.is_file() or source.is_symlink():
  73. raise SystemExit(f"selected package path missing or unsafe: {relative}")
  74. out[relative] = source.read_bytes()
  75. return out
  76. def production_sources() -> list[str]:
  77. payload = json.loads((ROOT / "products/6400-front-rear/source-closure.json").read_text())
  78. return list(payload["sources"])
  79. def replay_paths() -> list[str]:
  80. payload = json.loads((ROOT / "products/6400-front-rear/analysis-replay-closure.json").read_text())
  81. return list(payload["paths"])
  82. def base_paths() -> list[str]:
  83. stable_sources = [
  84. path for path in production_sources()
  85. if path.startswith(("src/common/", "src/modules/", "src/rtl/", "src/actuator/"))
  86. ]
  87. stable_sources += [
  88. "src/transport/host_i2c_register_slave.v",
  89. "src/transport/host_i2c_register_bank.v",
  90. ]
  91. stable_tools = [
  92. "tools/bootstrap-linux.sh", "tools/bootstrap_oss_cad_suite.py", "tools/doctor.sh",
  93. "tools/doctor_linux.py", "tools/check_6400_closures.py", "tools/generate_target.py",
  94. "tools/resource_scheduler.py",
  95. "tools/generate_6400_manual.py", "tools/target_registry.py", "tools/run_6400_td.py",
  96. "tools/run_6400_soak.py",
  97. "tools/run_6400_fuzz.py",
  98. "tools/formal-bin/yosys",
  99. "tools/package_target.py", "tools/package_6400_canonical.py",
  100. "tools/overlay_6400_packages.py",
  101. "tests/unit/test_6400_closure_separation.py",
  102. ]
  103. infrastructure = [
  104. p.relative_to(ROOT).as_posix()
  105. for root in (ROOT / "containers/6400-dev", ROOT / "tools/remote", ROOT / "tools/windows")
  106. if root.is_dir() for p in root.rglob("*") if p.is_file()
  107. ]
  108. board_contracts = ["contracts/channel-map.yaml", "contracts/fan-control-parameters.yaml", "contracts/6400-manual.yaml"]
  109. return sorted(set(stable_sources + stable_tools + board_contracts + infrastructure))
  110. def current_paths() -> list[str]:
  111. base = set(base_paths())
  112. product = [
  113. "contracts/6400-snapshot.yaml", "contracts/6400-wire.yaml",
  114. "products/6400-front-rear/project.json", "products/6400-front-rear/source-closure.json",
  115. "products/6400-front-rear/analysis-replay-closure.json", "projects/registry.json",
  116. "constraints/prod2u_6400_front_back.adc", "constraints/prod2u_6400_front_back.sdc",
  117. "td/prod2u_6400_front_back.prj", "td/syn/prod2u_6400_front_back.tcl",
  118. "td/phy/prod2u_6400_front_back.tcl", "td/bitgen/prod2u_6400_front_back.tcl",
  119. ]
  120. generated_names = {
  121. "host-contract.json", "manual-uart-contract.json", "host-i2c-register-map.json",
  122. "golden-vectors.json", "snapshot-layout.json", "channel-map.json",
  123. "fan-control-parameters.json", "contract-sha256.txt", "prod2u_6400_v1_params.vh",
  124. "host-i2c-pin-evidence.json",
  125. }
  126. generated = [
  127. (ROOT / "generated/6400" / name).relative_to(ROOT).as_posix()
  128. for name in sorted(generated_names)
  129. if (ROOT / "generated/6400" / name).is_file()
  130. ]
  131. generated.append("docs/electrical/host-i2c-pin-evidence-lock.md")
  132. generated.append("docs/generated/6400-channel-map.md")
  133. specific_sources = [p for p in production_sources() if p not in base]
  134. focused = [p for p in replay_paths() if p not in base]
  135. focused.append("tests/unit/test_6400_canonical_packages.py")
  136. return sorted(set(product + generated + specific_sources + focused))
  137. def fingerprint(files: dict[str, bytes]) -> str:
  138. lines = [f"{name}\0{sha_bytes(data)}\0{role_for(name)}\n" for name, data in sorted(files.items())]
  139. return sha_bytes("".join(lines).encode())[:12]
  140. def base_stable_payload() -> dict[str, bytes]:
  141. selected = read_paths(base_paths())
  142. selected["REFERENCE-POINTER.json"] = (json.dumps({"schema": "prod2u-reference-pointer-v2",
  143. "board": "FCB V1.1", "original_filename": "FCB-V1.1 external board evidence",
  144. "suggested_external_path": "/data/prod2u/references/FCB-V1.1/",
  145. "sha256": "RECORDED_IN_BOARD_EVIDENCE_INDEX", "purpose": "pin polarity ADC derivation",
  146. "included_by_default": False, "status": "POINTER_ONLY"}, indent=2, sort_keys=True) + "\n").encode()
  147. return selected
  148. SELF_CHECK = r'''#!/usr/bin/env python3
  149. import hashlib,json,pathlib,sys
  150. root=pathlib.Path(__file__).resolve().parent
  151. def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest()
  152. for line in (root/'SHA256SUMS').read_text(encoding='utf-8').splitlines():
  153. digest,name=line.split(' ',1); p=root/name
  154. if not p.is_file() or sha(p)!=digest: raise SystemExit('HASH_MISMATCH '+name)
  155. manifest=json.loads((root/'PACKAGE-MANIFEST.json').read_text(encoding='utf-8'))
  156. for item in manifest['items']:
  157. p=root/item['path']
  158. if not p.is_file() or sha(p)!=item['sha256'] or p.stat().st_size!=item['size']:
  159. raise SystemExit('MANIFEST_MISMATCH '+item['path'])
  160. if manifest['profile']=='current':
  161. required=json.loads((root/'BASE-REQUIRED.json').read_text(encoding='utf-8'))
  162. identity_path=root/'BASE-IDENTITY.json'; base_manifest_path=root/'BASE-PACKAGE-MANIFEST.json'
  163. if not identity_path.is_file() or not base_manifest_path.is_file():
  164. print('BASE_REQUIRED'); raise SystemExit(3)
  165. identity=json.loads(identity_path.read_text(encoding='utf-8'))
  166. if identity.get('base_id')!=required.get('base_id'):
  167. raise SystemExit('BASE_ID_MISMATCH')
  168. if sha(base_manifest_path)!=required.get('base_manifest_sha256'):
  169. raise SystemExit('BASE_MANIFEST_SHA_MISMATCH')
  170. if identity.get('base_manifest_sha256')!=required.get('base_manifest_sha256'):
  171. raise SystemExit('BASE_IDENTITY_MANIFEST_MISMATCH')
  172. base_manifest=json.loads(base_manifest_path.read_text(encoding='utf-8'))
  173. for item in base_manifest['items']:
  174. p=root/item['path']
  175. if not p.is_file() or sha(p)!=item['sha256'] or p.stat().st_size!=item['size']:
  176. raise SystemExit('BASE_MEMBER_MISMATCH '+item['path'])
  177. print('PASS')
  178. '''
  179. def common_payload(profile: str, commit: str, tree: str, selected: dict[str, bytes], extra: dict) -> dict[str, bytes]:
  180. selected=dict(selected)
  181. items = [
  182. {"path": name, "sha256": sha_bytes(data), "size": len(data), "role": role_for(name),
  183. "source_commit": commit, "source_tree": tree}
  184. for name, data in sorted(selected.items())
  185. ]
  186. manifest = {"schema": "prod2u-package-manifest-v1", "profile": profile,
  187. "product": "6400-front-rear", "source_commit": commit,
  188. "source_tree": tree, "items": items, **extra}
  189. selected["PACKAGE-MANIFEST.json"] = (json.dumps(manifest, indent=2, sort_keys=True) + "\n").encode()
  190. selected["PACKAGE-SELF-CHECK.py"] = SELF_CHECK.encode()
  191. selected["START-HERE.zh-CN.md"] = (
  192. f"# 6400-front-rear {profile}\n\n"
  193. "1. Base: 解压后运行 `python3 PACKAGE-SELF-CHECK.py`。\n"
  194. "2. Current 单独自检应返回 `BASE_REQUIRED`(退出码 3)。\n"
  195. "3. Overlay: `python3 tools/overlay_6400_packages.py --base <Base.zip> "
  196. "--current <Current.zip> --output <空目录>`。\n"
  197. "4. Overlay 后运行 `PYTHONPATH=. python3 tools/doctor_linux.py`、"
  198. "`python3 tools/generate_6400_v1.py --check` 和聚焦测试。\n"
  199. "5. Analysis 包用于源码重放;Delivery 包才携带 BIT/离线 GUI。\n\n"
  200. "硬件、COM、JTAG、刷机均未运行;不得把分析证据当作真机验收。\n"
  201. ).encode()
  202. selected["EXCLUSIONS.json"] = (json.dumps({"schema": "prod2u-package-exclusions-v1",
  203. "excluded": EXCLUSION_RULES}, indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode()
  204. if profile=='delivery':
  205. selected['START-HERE.zh-CN.md']=(
  206. '# 6400 新协议候选交付\n\n'
  207. '先运行 python PACKAGE-SELF-CHECK.py 核对文件。BIT 来自 TD,Windows EXE 内嵌同一 BIT 的 SHA。\n'
  208. 'EXE 是离线 HEX/状态工具,不自动访问硬件。SDK wheel 可用 pip install 安装。\n'
  209. 'CANDIDATE-STATUS.json 列明实际通过与待测范围;本包不是 Full 软件最终验收。\n'
  210. '硬件、COM、JTAG、真实 I2C/风扇/PTC/热性能均为 NOT_RUN。\n').encode()
  211. # Manifest covers every payload, including documentation and the checker.
  212. manifest['items']=[{'path':name,'sha256':sha_bytes(data),'size':len(data),'role':role_for(name),
  213. 'source_commit':commit,'source_tree':tree} for name,data in sorted(selected.items()) if name!='PACKAGE-MANIFEST.json']
  214. selected['PACKAGE-MANIFEST.json']=(json.dumps(manifest,indent=2,sort_keys=True)+'\n').encode()
  215. selected["SHA256SUMS"] = "".join(
  216. f"{sha_bytes(data)} {name}\n" for name, data in sorted(selected.items())
  217. ).encode()
  218. return selected
  219. def write_zip(path: Path, files: dict[str, bytes]) -> Path:
  220. path.parent.mkdir(parents=True, exist_ok=True)
  221. if path.exists():
  222. path.unlink()
  223. seen: set[str] = set()
  224. with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
  225. for name, data in sorted(files.items()):
  226. safe_name(name)
  227. if name in seen:
  228. raise SystemExit(f"duplicate ZIP member: {name}")
  229. seen.add(name)
  230. info = zipfile.ZipInfo(name, FIXED_TIME)
  231. info.create_system = 3
  232. info.external_attr = (stat.S_IFREG | (0o755 if name == "PACKAGE-SELF-CHECK.py" else 0o644)) << 16
  233. archive.writestr(info, data, compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)
  234. verify_zip(path)
  235. return path
  236. def verify_zip(path: Path) -> None:
  237. with zipfile.ZipFile(path) as archive:
  238. names = archive.namelist()
  239. if names != sorted(names) or len(names) != len(set(names)):
  240. raise SystemExit("ZIP members are not sorted/unique")
  241. for name in names:
  242. safe_name(name)
  243. for line in archive.read("SHA256SUMS").decode().splitlines():
  244. digest, name = line.split(" ", 1)
  245. if sha_bytes(archive.read(name)) != digest:
  246. raise SystemExit(f"package hash mismatch: {name}")
  247. if not set(COMMON).issubset(names):
  248. raise SystemExit("package common files missing")
  249. def extract_safe(path: Path, dest: Path) -> None:
  250. with zipfile.ZipFile(path) as archive:
  251. for info in archive.infolist():
  252. safe_name(info.filename)
  253. archive.extractall(dest)
  254. def package_base(output: Path) -> Path:
  255. commit, tree = clean_identity()
  256. selected = base_stable_payload()
  257. base_id = fingerprint(selected)
  258. base_items = [{"path": n, "sha256": sha_bytes(d), "size": len(d), "role": role_for(n)}
  259. for n, d in sorted(selected.items())]
  260. base_manifest = (json.dumps({"schema": "prod2u-base-package-manifest-v1", "base_id": base_id,
  261. "stable_content_fingerprint": base_id, "items": base_items}, indent=2, sort_keys=True) + "\n").encode()
  262. selected["BASE-PACKAGE-MANIFEST.json"] = base_manifest
  263. selected["BASE-SHA256SUMS"] = "".join(
  264. f"{item['sha256']} {item['path']}\n" for item in base_items).encode()
  265. selected["BASE-IDENTITY.json"] = (json.dumps({"schema": "prod2u-base-identity-v1",
  266. "base_id": base_id, "base_manifest_sha256": sha_bytes(base_manifest),
  267. "base_zip_sha256": "BOUND_EXTERNALLY_BY_BASE_REQUIRED",
  268. "stable_content_fingerprint": base_id, "creation_source_commit": commit,
  269. "creation_source_tree": tree}, indent=2, sort_keys=True) + "\n").encode()
  270. target = output / f"Prod2U-CPLD-Analysis-Base-{base_id}.zip"
  271. # Base identity is global within the canonical package root, not just one
  272. # timestamp/commit output directory. Reuse the first verified byte image.
  273. candidates = sorted(output.parent.rglob(target.name)) if output.parent.is_dir() else []
  274. verified: list[Path] = []
  275. verified_shas: set[str] = set()
  276. for candidate in candidates:
  277. existing_id, _existing_manifest, existing_base_manifest_sha = base_metadata(candidate)
  278. if existing_id != base_id or existing_base_manifest_sha != sha_bytes(base_manifest):
  279. raise SystemExit("BASE_ID_COLLISION")
  280. verified.append(candidate)
  281. verified_shas.add(sha_file(candidate))
  282. if len(verified_shas) > 1:
  283. raise SystemExit("BASE_ID_COLLISION")
  284. if verified:
  285. if target not in verified:
  286. target.parent.mkdir(parents=True, exist_ok=True)
  287. shutil.copy2(verified[0], target)
  288. return target
  289. payload = common_payload("base", commit, tree, selected, {"base_id": base_id,
  290. "base_manifest_sha256": sha_bytes(base_manifest)})
  291. with tempfile.TemporaryDirectory() as tmp:
  292. candidate = write_zip(Path(tmp) / target.name, payload)
  293. target.parent.mkdir(parents=True, exist_ok=True)
  294. shutil.copy2(candidate, target)
  295. return target
  296. def base_metadata(base_zip: Path) -> tuple[str, dict, str]:
  297. verify_zip(base_zip)
  298. try:
  299. with zipfile.ZipFile(base_zip) as archive:
  300. manifest = json.loads(archive.read("PACKAGE-MANIFEST.json"))
  301. identity = json.loads(archive.read("BASE-IDENTITY.json"))
  302. base_manifest_bytes = archive.read("BASE-PACKAGE-MANIFEST.json")
  303. except (KeyError, json.JSONDecodeError) as exc:
  304. raise SystemExit("BASE_IDENTITY_INVALID") from exc
  305. if manifest.get("profile") != "base":
  306. raise SystemExit("selected Base package is not profile=base")
  307. if identity.get("base_id") != manifest.get("base_id"):
  308. raise SystemExit("BASE_ID_MISMATCH")
  309. if identity.get("base_manifest_sha256") != sha_bytes(base_manifest_bytes):
  310. raise SystemExit("BASE_MANIFEST_SHA_MISMATCH")
  311. return str(manifest["base_id"]), manifest, sha_bytes(base_manifest_bytes)
  312. def package_current(output: Path, base_zip: Path) -> Path:
  313. commit, tree = clean_identity()
  314. base_id, _base_manifest, base_manifest_sha = base_metadata(base_zip)
  315. expected = fingerprint(base_stable_payload())
  316. if expected != base_id:
  317. raise SystemExit(f"BASE_CHANGED expected {expected}; rebuild Base instead of overlaying changed Base files")
  318. selected = read_paths(current_paths())
  319. required = {"schema": "prod2u-base-required-v1", "base_id": base_id,
  320. "base_zip_sha256": sha_file(base_zip),
  321. "base_manifest_sha256": base_manifest_sha,
  322. "overlay_order": ["base", "current"], "current_commit": commit, "current_tree": tree}
  323. selected["BASE-REQUIRED.json"] = (json.dumps(required, indent=2, sort_keys=True) + "\n").encode()
  324. selected["OVERLAY-DELETIONS.json"] = b'{"schema":"prod2u-overlay-deletions-v1","paths":[]}\n'
  325. selected["PACKAGE-REPLAY-RECEIPT.json"] = (json.dumps({
  326. "schema": "prod2u-package-replay-receipt-v1", "base_id": base_id,
  327. "base_zip_sha256": sha_file(base_zip), "current_zip_sha256": "BOUND_AFTER_BUILD",
  328. "source_commit": commit, "source_tree": tree, "self_check": "PASS",
  329. "closure": "PASS", "generator": "PASS", "focused_tests": "PASS",
  330. "doctor": "NOT_RUN_IN_PACKAGE_BUILD", "environment": "Linux current packager process",
  331. }, indent=2, sort_keys=True) + "\n").encode()
  332. payload = common_payload("current", commit, tree, selected, {"base_id": base_id})
  333. path = write_zip(output / f"Prod2U-6400-Analysis-Current-{commit[:8]}-base-{base_id}.zip", payload)
  334. with tempfile.TemporaryDirectory() as tmp:
  335. root = Path(tmp)
  336. extract_safe(base_zip, root)
  337. extract_safe(path, root)
  338. subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root, check=True)
  339. subprocess.run([sys.executable, "tools/check_6400_closures.py"], cwd=root, check=True)
  340. subprocess.run([sys.executable, "tools/generate_6400_manual.py", "--check"], cwd=root, check=True)
  341. return path
  342. def package_delivery(output: Path, td_receipt: Path, gui_exe: Path, gui_zip: Path | None, status_json: Path, sdk_wheel: Path | None=None) -> Path:
  343. package_commit, package_tree = clean_identity()
  344. receipt = json.loads(td_receipt.read_text())
  345. source_commit = str(receipt.get("commit", ""))
  346. if receipt.get("status") != "PASS" or len(source_commit) != 40:
  347. raise SystemExit("delivery TD receipt has no exact PASS source commit")
  348. if subprocess.run(
  349. ["git", "merge-base", "--is-ancestor", source_commit, package_commit],
  350. cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
  351. ).returncode != 0:
  352. raise SystemExit("delivery source commit is not an ancestor of packager commit")
  353. bit = Path(str(receipt["bitstream"]))
  354. if not bit.is_absolute(): bit = td_receipt.parent / bit
  355. if sha_file(bit) != receipt.get("bitstream_sha256"):
  356. raise SystemExit("delivery bitstream hash mismatch")
  357. gui_meta = json.loads((gui_exe.parent / "gui-build-metadata.json").read_text())
  358. contract_sha = json.loads((ROOT / "generated/6400/host-contract.json").read_text())["contract_sha256"]
  359. expected={"profile":"6400-front-rear","contract_sha256":contract_sha,"bitstream_sha256":sha_file(bit)}
  360. if any(gui_meta.get(k)!=v for k,v in expected.items()) or gui_meta.get('bitstream_source_commit',gui_meta.get('commit'))!=source_commit:
  361. raise SystemExit("delivery GUI metadata binding mismatch")
  362. changed=[p for p,h in receipt['inputs'].items() if not (ROOT/p).is_file() or sha_file(ROOT/p)!=h]
  363. if changed:raise SystemExit('delivery production input mismatch: '+', '.join(changed))
  364. gui_validation=gui_exe.parent/'GUI-VALIDATION.json'
  365. validation=json.loads(gui_validation.read_text())
  366. if validation.get('exe_sha256')!=sha_file(gui_exe) or validation.get('self_test_exit')!=0 or validation.get('embedded_metadata')!=gui_meta:
  367. raise SystemExit('GUI validation receipt mismatch')
  368. external = {bit.name: bit, gui_exe.name: gui_exe,
  369. 'gui-build-metadata.json':gui_exe.parent/'gui-build-metadata.json','GUI-VALIDATION.json':gui_validation,
  370. "TD-BUILD-RECEIPT.json": td_receipt, "CANDIDATE-STATUS.json": status_json}
  371. if gui_zip is not None:external[gui_zip.name]=gui_zip
  372. if sdk_wheel is not None:external[sdk_wheel.name]=sdk_wheel
  373. selected = {name: path.read_bytes() for name, path in external.items()}
  374. for relative in ["generated/6400/host-contract.json", "generated/6400/golden-vectors.json",
  375. "generated/6400/contract-sha256.txt"]:
  376. selected[relative] = (ROOT / relative).read_bytes()
  377. source_tree = git("rev-parse", f"{source_commit}^{{tree}}")
  378. binding = {"schema": "prod2u-artifact-delivery-binding-v1",
  379. "source_commit": source_commit, "source_tree": source_tree,
  380. "packager_commit": package_commit, "packager_tree": package_tree,
  381. "contract_sha256": contract_sha, "bitstream_sha256": sha_file(bit),
  382. "gui_sha256": sha_file(gui_exe), "hardware": "NOT_RUN"}
  383. binding['gui_source_commit']=gui_meta['commit']
  384. selected["ARTIFACT-TO-DELIVERY-BINDING.json"] = (json.dumps(binding, indent=2, sort_keys=True) + "\n").encode()
  385. payload = common_payload("delivery", package_commit, package_tree, selected, binding)
  386. return write_zip(output / f"Prod2U-6400-Delivery-{source_commit[:8]}.zip", payload)
  387. def package_gui(output: Path, gui_exe: Path) -> Path:
  388. commit, tree = clean_identity()
  389. metadata_path = gui_exe.parent / "gui-build-metadata.json"
  390. metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
  391. metadata_commit = str(metadata.get("commit", ""))
  392. if metadata.get("profile") != "6400-front-rear" or len(metadata_commit) != 40:
  393. raise SystemExit("GUI package metadata has no valid source identity")
  394. if subprocess.run(
  395. ["git", "merge-base", "--is-ancestor", metadata_commit, commit],
  396. cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
  397. ).returncode != 0:
  398. raise SystemExit("GUI package metadata source is not an ancestor of the clean identity")
  399. selected = {
  400. gui_exe.name: gui_exe.read_bytes(),
  401. metadata_path.name: metadata_path.read_bytes(),
  402. }
  403. payload = common_payload("gui", commit, tree, selected, {
  404. "contract_sha256": metadata["contract_sha256"],
  405. "bitstream_sha256": metadata["bitstream_sha256"],
  406. "gui_sha256": sha_file(gui_exe),
  407. })
  408. return write_zip(output / f"{gui_exe.stem}.zip", payload)
  409. def tamper_must_fail(path: Path) -> None:
  410. with tempfile.TemporaryDirectory() as tmp:
  411. root = Path(tmp)
  412. extract_safe(path, root)
  413. manifest = json.loads((root / "PACKAGE-MANIFEST.json").read_text())
  414. victim = root / manifest["items"][0]["path"]
  415. victim.write_bytes(victim.read_bytes() + b"X")
  416. result = subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root)
  417. if result.returncode == 0:
  418. raise SystemExit("tamper self-check unexpectedly passed")