package_target.py 25 KB

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