package_target.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. #!/usr/bin/env python3
  2. """Target-bound source/review/firmware packager with fail-closed release pins."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. import os
  8. import re
  9. import shutil
  10. import subprocess
  11. import sys
  12. import tempfile
  13. import zipfile
  14. from datetime import datetime, timezone
  15. from pathlib import Path
  16. _ROOT = Path(__file__).resolve().parents[1]
  17. if str(_ROOT) not in sys.path:
  18. sys.path.insert(0, str(_ROOT))
  19. from tools.generate_target import generate_named_target
  20. from tools.generate_6400_v1 import generate as generate_6400_v1
  21. from tools.run_6400_td import (
  22. EXPECTED_UNBOUND_PORTS,
  23. HARDWARE_PROFILES,
  24. input_manifest as td_input_manifest,
  25. source_closure as td_source_closure,
  26. )
  27. from tools.target_registry import ROOT, load_source_closure, release_blocked, resolve_target
  28. from tools import package_6400_canonical
  29. CANDIDATE_NOTICE_ZH_CN = "RS-232-only TD候选;真实硬件验证仍为 NOT RUN"
  30. DO_NOT_PROGRAM_LINE = "DO NOT PROGRAM / 不要烧录"
  31. PRODUCTION_PROGRAM_LINE = "RS-232-ONLY PRODUCTION TD PASS / HARDWARE NOT RUN"
  32. IDENTIFICATION_PROGRAM_LINE = "IDENTIFICATION ONLY / NOT PRODUCTION / HARDWARE NOT RUN"
  33. CONTROL_DEPLOYMENT_STATUS = (
  34. "TD_QUALIFIED_RS232_ONLY_HARDWARE_NOT_RUN"
  35. )
  36. IDENTIFICATION_DEPLOYMENT_STATUS = (
  37. "IDENTIFICATION_ONLY_RS232_ONLY_HARDWARE_NOT_RUN"
  38. )
  39. FORBIDDEN_PROGRAM_INSTRUCTIONS = (
  40. "Erase/Program",
  41. "执行 Erase",
  42. "执行 Program",
  43. "JTAG 下载器",
  44. )
  45. def _sha256(path: Path) -> str:
  46. digest = hashlib.sha256()
  47. with path.open("rb") as handle:
  48. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  49. digest.update(chunk)
  50. return digest.hexdigest()
  51. def _expected_deployment_status(profile_name: str) -> str:
  52. return (
  53. CONTROL_DEPLOYMENT_STATUS
  54. if bool(HARDWARE_PROFILES[profile_name]["production"])
  55. else IDENTIFICATION_DEPLOYMENT_STATUS
  56. )
  57. def _contract_sha256() -> str:
  58. payload = json.loads(
  59. (ROOT / "generated/6400/host-contract.json").read_text(encoding="utf-8")
  60. )
  61. value = payload.get("contract_sha256")
  62. if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):
  63. raise SystemExit("6400 package blocked: invalid generated contract SHA-256")
  64. return value
  65. def _git(repo: Path, *args: str) -> str:
  66. try:
  67. return subprocess.check_output(["git", *args], cwd=repo, text=True, stderr=subprocess.DEVNULL).strip()
  68. except (OSError, subprocess.CalledProcessError):
  69. return os.environ.get("PROD2U_COMMIT", "unknown")
  70. def _add(zipf: zipfile.ZipFile, src: Path, dest: str, sums: dict[str, str]) -> None:
  71. zipf.write(src, dest)
  72. sums[dest] = _sha256(src)
  73. def _check_active_6400_generated() -> None:
  74. expected = generate_6400_v1(ROOT / "generated/6400")
  75. drift = [
  76. str(path.relative_to(ROOT))
  77. for path, content in expected.items()
  78. if not path.is_file() or path.read_bytes() != content
  79. ]
  80. if drift:
  81. raise SystemExit("6400 package blocked: active generated contract drift: " + ", ".join(drift))
  82. def _resolve_6400_profile(target_name: str, profile_name: str | None) -> str:
  83. if target_name in HARDWARE_PROFILES:
  84. if profile_name is not None and profile_name != target_name:
  85. raise SystemExit("6400 package blocked: target/profile mismatch")
  86. return target_name
  87. if target_name != "6400" or profile_name not in HARDWARE_PROFILES:
  88. raise SystemExit(
  89. "6400 package blocked: explicitly select --profile 6400-front-rear"
  90. )
  91. return profile_name
  92. def _validated_td_bitstream(
  93. profile_name: str, receipt_path: Path | None, package_commit: str
  94. ) -> tuple[Path, dict[str, object]]:
  95. if receipt_path is None or not receipt_path.is_file():
  96. raise SystemExit("6400 firmware package blocked: explicit --td-receipt is required")
  97. receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
  98. profile = HARDWARE_PROFILES[profile_name]
  99. project_path = ROOT / str(profile["project"])
  100. closure_path = ROOT / str(profile["closure"])
  101. current_inputs = td_input_manifest(profile_name)
  102. source_manifest_sha256 = hashlib.sha256(
  103. json.dumps(current_inputs, sort_keys=True, separators=(",", ":")).encode()
  104. ).hexdigest()
  105. expected = {
  106. "schema": "prod2u-6400-td-receipt-v1",
  107. "status": "PASS",
  108. "profile": profile_name,
  109. "project": str(profile["project"]),
  110. "source_closure": str(profile["closure"]),
  111. "production": bool(profile["production"]),
  112. "stimulus": bool(profile["stimulus"]),
  113. "simulation_only": False,
  114. "artifact_basename": str(profile["artifact_basename"]),
  115. "timing_pass_25mhz": True,
  116. "project_sha256": _sha256(project_path),
  117. "source_closure_sha256": _sha256(closure_path),
  118. "source_manifest_sha256": source_manifest_sha256,
  119. "inputs": current_inputs,
  120. "known_unbound_ports": list(EXPECTED_UNBOUND_PORTS),
  121. "deployment_status": _expected_deployment_status(profile_name),
  122. }
  123. mismatches = [
  124. f"{key}: expected {value!r}, got {receipt.get(key)!r}"
  125. for key, value in expected.items()
  126. if receipt.get(key) != value
  127. ]
  128. if mismatches:
  129. raise SystemExit("6400 firmware package blocked: TD receipt mismatch: " + "; ".join(mismatches))
  130. source_commit = receipt.get("commit")
  131. if not isinstance(source_commit, str) or not re.fullmatch(
  132. r"[0-9a-f]{40}", source_commit
  133. ):
  134. raise SystemExit(
  135. "6400 firmware package blocked: TD receipt has invalid source commit"
  136. )
  137. if not re.fullmatch(r"[0-9a-f]{40}", package_commit):
  138. raise SystemExit(
  139. "6400 firmware package blocked: exact package commit is unavailable"
  140. )
  141. warning_audit = receipt.get("warning_audit")
  142. expected_ports = list(EXPECTED_UNBOUND_PORTS)
  143. if not isinstance(warning_audit, dict) or any(
  144. warning_audit.get(key) != value
  145. for key, value in {
  146. "status": "PASS",
  147. "expected_unbound_ports": expected_ports,
  148. "observed_unbound_ports": expected_ports,
  149. "unexpected_unbound_ports": [],
  150. "missing_expected_unbound_ports": [],
  151. }.items()
  152. ):
  153. raise SystemExit(
  154. "6400 firmware package blocked: TD warning audit mismatch"
  155. )
  156. bitstream_value = receipt.get("bitstream")
  157. if not isinstance(bitstream_value, str) or not bitstream_value:
  158. raise SystemExit("6400 firmware package blocked: TD receipt has no bitstream")
  159. bitstream = Path(bitstream_value)
  160. if not bitstream.is_absolute():
  161. bitstream = receipt_path.parent / bitstream
  162. expected_name = f"{profile['artifact_basename']}.bit"
  163. if bitstream.name != expected_name or not bitstream.is_file() or bitstream.stat().st_size == 0:
  164. raise SystemExit("6400 firmware package blocked: receipt bitstream is missing or misnamed")
  165. if receipt.get("bitstream_sha256") != _sha256(bitstream):
  166. raise SystemExit("6400 firmware package blocked: receipt bitstream SHA-256 mismatch")
  167. return bitstream.resolve(), receipt
  168. def build_target_package(
  169. target_name: str,
  170. kind: str,
  171. output_dir: Path,
  172. include_reference: bool = False,
  173. *,
  174. profile_name: str | None = None,
  175. td_receipt: Path | None = None,
  176. ) -> Path:
  177. is_6400 = target_name == "6400" or target_name.startswith("6400-")
  178. receipt_payload: dict[str, object] | None = None
  179. expanded_closure: dict[str, object] | None = None
  180. hardware_validation = "NOT RUN"
  181. known_unbound_ports: tuple[str, ...] = ()
  182. deployment_status: str | None = None
  183. source_commit: str | None = None
  184. if is_6400:
  185. selected_profile = _resolve_6400_profile(target_name, profile_name)
  186. profile = HARDWARE_PROFILES[selected_profile]
  187. _check_active_6400_generated()
  188. project_path = ROOT / str(profile["project"])
  189. closure_path = ROOT / str(profile["closure"])
  190. generated_dir = ROOT / "generated/6400"
  191. project = json.loads(project_path.read_text(encoding="utf-8"))
  192. sources, _closure_inputs = td_source_closure(selected_profile)
  193. top_module = str(project["top"])
  194. project_id = selected_profile
  195. target_alias = "6400"
  196. package_label = selected_profile
  197. blocked, pins = False, ()
  198. expanded_closure = {
  199. "schema": "prod2u-source-closure-expanded-v1",
  200. "project_id": selected_profile,
  201. "top_module": top_module,
  202. "sources": sources,
  203. }
  204. else:
  205. target = resolve_target(target_name)
  206. generate_named_target(target.alias)
  207. project_path = target.project_config
  208. closure_path = target.source_closure
  209. generated_dir = target.generated_dir
  210. project = json.loads(project_path.read_text(encoding="utf-8"))
  211. blocked, pins = release_blocked(target, project)
  212. sources = list(load_source_closure(target))
  213. top_module = target.top_module
  214. project_id = target.project_id
  215. target_alias = target.alias
  216. package_label = target.alias
  217. selected_profile = target.profile
  218. if kind == "firmware" and blocked:
  219. raise SystemExit(
  220. "release_blocked\n" + "\n".join(f"{name} pin unresolved" for name in pins)
  221. )
  222. commit = _git(ROOT, "rev-parse", "HEAD")
  223. bitstream_path: Path | None = None
  224. if kind == "firmware" and is_6400:
  225. if not re.fullmatch(r"[0-9a-f]{40}", commit):
  226. raise SystemExit("6400 firmware package blocked: exact Git commit is unavailable")
  227. bitstream_path, receipt_payload = _validated_td_bitstream(
  228. selected_profile, td_receipt, commit
  229. )
  230. ports_value = receipt_payload["known_unbound_ports"]
  231. status_value = receipt_payload["deployment_status"]
  232. assert isinstance(ports_value, list)
  233. assert all(isinstance(port, str) for port in ports_value)
  234. assert isinstance(status_value, str)
  235. known_unbound_ports = tuple(ports_value)
  236. deployment_status = status_value
  237. source_commit_value = receipt_payload["commit"]
  238. assert isinstance(source_commit_value, str)
  239. source_commit = source_commit_value
  240. # Hardware NOT RUN is an evidence boundary, not a source/TD packaging
  241. # failure. A zero-unbound-port RS-232-only image may be handed to the
  242. # user for programming while remaining explicitly unvalidated on real
  243. # hardware. Identification is never Production, but may be programmed
  244. # for the finite stimulus workflow.
  245. blocked = bool(known_unbound_ports)
  246. pins = known_unbound_ports
  247. run_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  248. name = f"prod2u-{package_label}-{kind}-{commit[:12]}-{run_id}"
  249. output_dir.mkdir(parents=True, exist_ok=True)
  250. zip_path = output_dir / f"{name}.zip"
  251. manifest = {
  252. "schema": "prod2u-target-package-v1",
  253. "target_alias": target_alias,
  254. "profile": selected_profile,
  255. "firmware_role": "production" if is_6400 else "legacy",
  256. "project_id": project_id,
  257. "top": top_module,
  258. "kind": kind,
  259. "commit": commit,
  260. "run_id": run_id,
  261. "project_config_sha256": _sha256(project_path),
  262. "source_closure_sha256": _sha256(closure_path),
  263. "source_manifest_sha256": (
  264. receipt_payload.get("source_manifest_sha256")
  265. if receipt_payload is not None
  266. else None
  267. ),
  268. "bitstream_sha256": _sha256(bitstream_path) if bitstream_path else None,
  269. "hardware_validation": hardware_validation,
  270. "release_blocked": blocked,
  271. "unresolved_pins": list(pins),
  272. "include_reference": include_reference,
  273. }
  274. if is_6400:
  275. manifest.update(
  276. {
  277. "contract_sha256": _contract_sha256(),
  278. "production": bool(profile["production"]),
  279. "stimulus": bool(profile["stimulus"]),
  280. "simulation_only": False,
  281. }
  282. )
  283. if is_6400 and kind == "firmware":
  284. manifest.update(
  285. {
  286. "candidate_notice_zh_CN": CANDIDATE_NOTICE_ZH_CN,
  287. "candidate_only": hardware_validation != "PASS",
  288. "td_programmable": not blocked,
  289. # The image is safe to hand off for user-controlled programming
  290. # after TD passes, but real hardware acceptance remains NOT RUN.
  291. "deployable": False,
  292. "production_deployable": False,
  293. "identification_programmable": (
  294. not blocked and not bool(profile["production"])
  295. ),
  296. "hardware_validated": hardware_validation == "PASS",
  297. "deployment_status": deployment_status,
  298. "source_commit": source_commit,
  299. "package_commit": commit,
  300. "known_unbound_ports": list(known_unbound_ports),
  301. "unresolved_ports": list(known_unbound_ports),
  302. }
  303. )
  304. with tempfile.TemporaryDirectory() as tmp:
  305. stage = Path(tmp)
  306. (stage / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
  307. if is_6400 and kind == "firmware" and blocked:
  308. (stage / "CANDIDATE-NOTICE.zh-CN.txt").write_text(
  309. DO_NOT_PROGRAM_LINE + "\n"
  310. + CANDIDATE_NOTICE_ZH_CN + "\n"
  311. + f"未冻结端口:{', '.join(known_unbound_ports)}\n"
  312. + f"部署状态:{deployment_status}\n"
  313. + f"硬件验证:{hardware_validation}\n",
  314. encoding="utf-8",
  315. )
  316. shutil.copy2(project_path, stage / "project.json")
  317. shutil.copy2(closure_path, stage / "source-closure.json")
  318. if expanded_closure is not None:
  319. (stage / "source-closure-expanded.json").write_text(
  320. json.dumps(expanded_closure, indent=2, sort_keys=True) + "\n",
  321. encoding="utf-8",
  322. )
  323. if receipt_payload is not None:
  324. source_manifest_bytes = json.dumps(
  325. receipt_payload["inputs"],
  326. sort_keys=True,
  327. separators=(",", ":"),
  328. ).encode()
  329. (stage / "source-manifest.json").write_bytes(source_manifest_bytes)
  330. gen_dir = stage / ("generated/6400" if is_6400 else "generated")
  331. if generated_dir.is_dir():
  332. shutil.copytree(generated_dir, gen_dir)
  333. src_dir = stage / "src"
  334. src_dir.mkdir()
  335. for rel in sources:
  336. dest = stage / rel
  337. dest.parent.mkdir(parents=True, exist_ok=True)
  338. shutil.copy2(ROOT / rel, dest)
  339. if bitstream_path is not None:
  340. bitstream_name = bitstream_path.name
  341. shutil.copy2(bitstream_path, stage / bitstream_name)
  342. (stage / "BITSTREAM-SHA256.txt").write_text(
  343. f"{_sha256(bitstream_path)} {bitstream_name}\n",
  344. encoding="ascii",
  345. )
  346. role = "生产"
  347. instruction_header = (
  348. DO_NOT_PROGRAM_LINE
  349. if blocked
  350. else (
  351. PRODUCTION_PROGRAM_LINE
  352. if is_6400
  353. else IDENTIFICATION_PROGRAM_LINE
  354. )
  355. )
  356. (stage / "FLASH-INSTRUCTIONS.zh-CN.txt").write_text(
  357. instruction_header + "\n"
  358. + CANDIDATE_NOTICE_ZH_CN + "\n\n"
  359. + f"6400 {role}固件审核说明\n"
  360. "========================\n"
  361. "目标器件:EF2L45BG256B(6400 前后独立温控)\n"
  362. f"固件文件:{bitstream_name}\n"
  363. "请审核 BITSTREAM-SHA256.txt 与 TD-BUILD-RECEIPT.json 后再冻结制品。\n"
  364. f"Host 串口仅使用 CON78 RS-232 921600 8N1;每条合法命令先独立 ACK;Profile={selected_profile}。\n"
  365. "本包只包含 6400 固件,不能用于 MRDIMM 门控板。\n"
  366. + "本固件对保留的 SET_STIMULUS 返回 UNSUPPORTED NACK。\n"
  367. + "\n"
  368. "注意:本次交付未执行真实 JTAG/硬件烧录,硬件验证状态为 NOT RUN。\n",
  369. encoding="utf-8",
  370. )
  371. assert receipt_payload is not None
  372. (stage / "TD-BUILD-RECEIPT.json").write_text(
  373. json.dumps(receipt_payload, indent=2, sort_keys=True) + "\n",
  374. encoding="utf-8",
  375. )
  376. if include_reference:
  377. ref = ROOT / "reference"
  378. if ref.is_dir():
  379. shutil.copytree(ref, stage / "reference", dirs_exist_ok=True)
  380. sums: dict[str, str] = {}
  381. if zip_path.exists():
  382. zip_path.unlink()
  383. with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zipf:
  384. for path in sorted(stage.rglob("*")):
  385. if path.is_file():
  386. _add(zipf, path, path.relative_to(stage).as_posix(), sums)
  387. zipf.writestr("SHA256SUMS", "".join(f"{digest} {name}\n" for name, digest in sorted(sums.items())))
  388. _selftest(zip_path)
  389. return zip_path
  390. def _selftest(zip_path: Path) -> None:
  391. with tempfile.TemporaryDirectory() as tmp:
  392. dest = Path(tmp) / "unpacked"
  393. dest.mkdir()
  394. with zipfile.ZipFile(zip_path) as zipf:
  395. for info in zipf.infolist():
  396. if info.filename.startswith("/") or ".." in Path(info.filename).parts:
  397. raise SystemExit(f"unsafe zip path: {info.filename}")
  398. zipf.extractall(dest)
  399. manifest = json.loads((dest / "manifest.json").read_text(encoding="utf-8"))
  400. if manifest.get("hardware_validation") != "NOT RUN":
  401. raise SystemExit("package selftest: hardware_validation must be NOT RUN")
  402. sums = (dest / "SHA256SUMS").read_text(encoding="utf-8").splitlines()
  403. for line in sums:
  404. digest, name = line.split(" ", 1)
  405. observed = _sha256(dest / name)
  406. if observed != digest:
  407. raise SystemExit(f"hash mismatch {name}")
  408. if manifest.get("target_alias") == "6400":
  409. profile_name = manifest.get("profile")
  410. if profile_name not in HARDWARE_PROFILES:
  411. raise SystemExit("package selftest: invalid 6400 hardware profile")
  412. members = [path.relative_to(dest).as_posix() for path in dest.rglob("*")]
  413. if any(name.startswith("src/generated/6400/") for name in members):
  414. raise SystemExit("package selftest: historical src/generated/6400 leaked")
  415. closure = json.loads(
  416. (dest / "source-closure-expanded.json").read_text(encoding="utf-8")
  417. )
  418. closure_text = "\n".join(closure["sources"])
  419. if "src/generated/6400" in closure_text or "prod2u_6400_front_back_top" in closure_text:
  420. raise SystemExit("package selftest: historical 6400 closure leaked")
  421. if manifest.get("target_alias") == "6400" and manifest.get("kind") == "firmware":
  422. profile_name = manifest["profile"]
  423. profile = HARDWARE_PROFILES[profile_name]
  424. expected_name = "prod2u_6400_front_back.bit"
  425. bit = dest / expected_name
  426. if not bit.is_file() or _sha256(bit) != manifest.get("bitstream_sha256"):
  427. raise SystemExit("package selftest: 6400 bitstream identity mismatch")
  428. receipt = json.loads(
  429. (dest / "TD-BUILD-RECEIPT.json").read_text(encoding="utf-8")
  430. )
  431. if receipt.get("profile") != profile_name or receipt.get(
  432. "bitstream_sha256"
  433. ) != manifest["bitstream_sha256"]:
  434. raise SystemExit("package selftest: TD receipt/profile identity mismatch")
  435. embedded_contract = json.loads(
  436. (dest / "generated/6400/host-contract.json").read_text(
  437. encoding="utf-8"
  438. )
  439. )
  440. if (
  441. manifest.get("contract_sha256")
  442. != embedded_contract.get("contract_sha256")
  443. or manifest.get("source_commit") != receipt.get("commit")
  444. or manifest.get("package_commit") != manifest.get("commit")
  445. or receipt.get("inputs") != td_input_manifest(profile_name)
  446. ):
  447. raise SystemExit("package selftest: firmware provenance mismatch")
  448. expected_input_sha = hashlib.sha256(
  449. json.dumps(
  450. receipt["inputs"], sort_keys=True, separators=(",", ":")
  451. ).encode()
  452. ).hexdigest()
  453. if (
  454. receipt.get("source_manifest_sha256") != expected_input_sha
  455. or receipt.get("project_sha256") != _sha256(dest / "project.json")
  456. or receipt.get("source_closure_sha256")
  457. != _sha256(dest / "source-closure.json")
  458. or manifest.get("source_closure_sha256")
  459. != receipt.get("source_closure_sha256")
  460. or manifest.get("source_manifest_sha256") != expected_input_sha
  461. or not (dest / "source-manifest.json").is_file()
  462. or _sha256(dest / "source-manifest.json") != expected_input_sha
  463. ):
  464. raise SystemExit("package selftest: TD input digest mismatch")
  465. receipt_ports = receipt.get("known_unbound_ports")
  466. expected_ports = list(EXPECTED_UNBOUND_PORTS)
  467. warning_audit = receipt.get("warning_audit")
  468. if (
  469. manifest.get("release_blocked") is not False
  470. or manifest.get("td_programmable") is not True
  471. or manifest.get("candidate_only") is not True
  472. or manifest.get("hardware_validated") is not False
  473. or manifest.get("deployable") is not False
  474. or manifest.get("production_deployable") is not False
  475. or manifest.get("identification_programmable")
  476. is not (not bool(profile["production"]))
  477. or receipt_ports != expected_ports
  478. or manifest.get("known_unbound_ports") != receipt_ports
  479. or manifest.get("unresolved_ports") != receipt_ports
  480. or manifest.get("unresolved_pins") != receipt_ports
  481. or receipt.get("deployment_status")
  482. != _expected_deployment_status(profile_name)
  483. or manifest.get("deployment_status")
  484. != receipt.get("deployment_status")
  485. or not isinstance(warning_audit, dict)
  486. or warning_audit.get("status") != "PASS"
  487. or warning_audit.get("observed_unbound_ports") != expected_ports
  488. ):
  489. raise SystemExit("package selftest: unsafe deployment gate mismatch")
  490. if (dest / "CANDIDATE-NOTICE.zh-CN.txt").exists():
  491. raise SystemExit("package selftest: stale release-block notice present")
  492. if (
  493. manifest.get("production") is not bool(profile["production"])
  494. or manifest.get("stimulus") is not bool(profile["stimulus"])
  495. or (not bool(profile["production"]) and manifest.get("deployable"))
  496. ):
  497. raise SystemExit("package selftest: firmware profile semantics mismatch")
  498. instructions = (dest / "FLASH-INSTRUCTIONS.zh-CN.txt").read_text(
  499. encoding="utf-8"
  500. )
  501. expected_header = (
  502. PRODUCTION_PROGRAM_LINE
  503. if bool(profile["production"])
  504. else IDENTIFICATION_PROGRAM_LINE
  505. )
  506. if (
  507. not instructions.startswith(expected_header)
  508. or "921600 8N1" not in instructions
  509. or "独立 ACK" not in instructions
  510. or any(token in instructions for token in FORBIDDEN_PROGRAM_INSTRUCTIONS)
  511. ):
  512. raise SystemExit("package selftest: Host UART/ACK contract missing")
  513. def main(argv: list[str] | None = None) -> int:
  514. parser = argparse.ArgumentParser()
  515. parser.add_argument("--target", required=True)
  516. parser.add_argument("--kind", choices=("source", "review", "firmware", "analysis-base", "analysis-current", "gui", "delivery"), default="source")
  517. parser.add_argument(
  518. "--profile",
  519. choices=("6400-front-rear",),
  520. )
  521. parser.add_argument("--td-receipt", type=Path)
  522. parser.add_argument("--base-zip", type=Path)
  523. parser.add_argument("--gui-exe", type=Path)
  524. parser.add_argument("--gui-zip", type=Path)
  525. parser.add_argument("--status-json", type=Path)
  526. parser.add_argument("--output-dir", type=Path, default=ROOT / "dist")
  527. parser.add_argument("--include-reference", action="store_true")
  528. args = parser.parse_args(argv)
  529. if args.kind == "analysis-base":
  530. path = package_6400_canonical.package_base(args.output_dir)
  531. elif args.kind == "analysis-current":
  532. if args.base_zip is None:
  533. parser.error("--base-zip is required for analysis-current")
  534. path = package_6400_canonical.package_current(args.output_dir, args.base_zip)
  535. elif args.kind == "delivery":
  536. required = (args.td_receipt, args.gui_exe, args.gui_zip, args.status_json)
  537. if any(value is None for value in required):
  538. parser.error("delivery requires --td-receipt --gui-exe --gui-zip --status-json")
  539. path = package_6400_canonical.package_delivery(
  540. args.output_dir, args.td_receipt, args.gui_exe, args.gui_zip, args.status_json
  541. )
  542. elif args.kind == "gui":
  543. if args.gui_exe is None:
  544. parser.error("gui requires --gui-exe")
  545. path = package_6400_canonical.package_gui(args.output_dir, args.gui_exe)
  546. else:
  547. path = build_target_package(
  548. args.target,
  549. args.kind,
  550. args.output_dir,
  551. args.include_reference,
  552. profile_name=args.profile,
  553. td_receipt=args.td_receipt,
  554. )
  555. print(json.dumps({"status": "pass", "package": str(path), "sha256": _sha256(path)}, indent=2))
  556. return 0
  557. if __name__ == "__main__":
  558. raise SystemExit(main())