package_target.py 25 KB

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