#!/usr/bin/env python3 """Target-bound source/review/firmware packager with fail-closed release pins.""" from __future__ import annotations import argparse import hashlib import json import os import re import shutil import subprocess import sys import tempfile import zipfile from datetime import datetime, timezone from pathlib import Path _ROOT = Path(__file__).resolve().parents[1] if str(_ROOT) not in sys.path: sys.path.insert(0, str(_ROOT)) from tools.generate_target import generate_named_target from tools.generate_6400_manual import generate as generate_6400_manual from tools.run_6400_td import ( EXPECTED_UNBOUND_PORTS, HARDWARE_PROFILES, input_manifest as td_input_manifest, source_closure as td_source_closure, ) from tools.target_registry import ROOT, load_source_closure, release_blocked, resolve_target from tools import package_6400_canonical CANDIDATE_NOTICE_ZH_CN = "UART + Host-I2C logic-bound TD候选;Pull-up装配和真实硬件验证仍为 NOT RUN" DO_NOT_PROGRAM_LINE = "DO NOT PROGRAM / 不要烧录" PRODUCTION_PROGRAM_LINE = "UART + HOST-I2C LOGIC-BOUND TD PASS / HARDWARE NOT RUN" IDENTIFICATION_PROGRAM_LINE = "IDENTIFICATION ONLY / NOT PRODUCTION / HARDWARE NOT RUN" CONTROL_DEPLOYMENT_STATUS = "TD_QUALIFIED_UART_I2C_LOGIC_BOUND_HARDWARE_NOT_RUN" IDENTIFICATION_DEPLOYMENT_STATUS = ( "IDENTIFICATION_ONLY_RS232_ONLY_HARDWARE_NOT_RUN" ) FORBIDDEN_PROGRAM_INSTRUCTIONS = ( "Erase/Program", "执行 Erase", "执行 Program", "JTAG 下载器", ) def _sha256(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _expected_deployment_status(profile_name: str) -> str: return ( CONTROL_DEPLOYMENT_STATUS if bool(HARDWARE_PROFILES[profile_name]["production"]) else IDENTIFICATION_DEPLOYMENT_STATUS ) def _contract_sha256() -> str: payload = json.loads( (ROOT / "generated/6400/host-contract.json").read_text(encoding="utf-8") ) value = payload.get("contract_sha256") if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value): raise SystemExit("6400 package blocked: invalid generated contract SHA-256") return value def _git(repo: Path, *args: str) -> str: try: return subprocess.check_output(["git", *args], cwd=repo, text=True, stderr=subprocess.DEVNULL).strip() except (OSError, subprocess.CalledProcessError): return os.environ.get("PROD2U_COMMIT", "unknown") def _add(zipf: zipfile.ZipFile, src: Path, dest: str, sums: dict[str, str]) -> None: zipf.write(src, dest) sums[dest] = _sha256(src) def _check_active_6400_generated() -> None: expected = generate_6400_manual() drift = [ str(path.relative_to(ROOT)) for path, content in expected.items() if not path.is_file() or path.read_bytes() != content ] if drift: raise SystemExit("6400 package blocked: active generated contract drift: " + ", ".join(drift)) def _resolve_6400_profile(target_name: str, profile_name: str | None) -> str: if target_name in HARDWARE_PROFILES: if profile_name is not None and profile_name != target_name: raise SystemExit("6400 package blocked: target/profile mismatch") return target_name if target_name != "6400" or profile_name not in HARDWARE_PROFILES: raise SystemExit( "6400 package blocked: explicitly select --profile 6400-front-rear" ) return profile_name def _validated_td_bitstream( profile_name: str, receipt_path: Path | None, package_commit: str ) -> tuple[Path, dict[str, object]]: if receipt_path is None or not receipt_path.is_file(): raise SystemExit("6400 firmware package blocked: explicit --td-receipt is required") receipt = json.loads(receipt_path.read_text(encoding="utf-8")) profile = HARDWARE_PROFILES[profile_name] project_path = ROOT / str(profile["project"]) closure_path = ROOT / str(profile["closure"]) current_inputs = td_input_manifest(profile_name) source_manifest_sha256 = hashlib.sha256( json.dumps(current_inputs, sort_keys=True, separators=(",", ":")).encode() ).hexdigest() expected = { "schema": "prod2u-6400-td-receipt-v1", "status": "PASS", "profile": profile_name, "project": str(profile["project"]), "source_closure": str(profile["closure"]), "production": bool(profile["production"]), "stimulus": bool(profile["stimulus"]), "simulation_only": False, "artifact_basename": str(profile["artifact_basename"]), "timing_pass_25mhz": True, "project_sha256": _sha256(project_path), "source_closure_sha256": _sha256(closure_path), "source_manifest_sha256": source_manifest_sha256, "inputs": current_inputs, "known_unbound_ports": list(EXPECTED_UNBOUND_PORTS), "deployment_status": _expected_deployment_status(profile_name), } mismatches = [ f"{key}: expected {value!r}, got {receipt.get(key)!r}" for key, value in expected.items() if receipt.get(key) != value ] if mismatches: raise SystemExit("6400 firmware package blocked: TD receipt mismatch: " + "; ".join(mismatches)) source_commit = receipt.get("commit") if not isinstance(source_commit, str) or not re.fullmatch( r"[0-9a-f]{40}", source_commit ): raise SystemExit( "6400 firmware package blocked: TD receipt has invalid source commit" ) if not re.fullmatch(r"[0-9a-f]{40}", package_commit): raise SystemExit( "6400 firmware package blocked: exact package commit is unavailable" ) warning_audit = receipt.get("warning_audit") expected_ports = list(EXPECTED_UNBOUND_PORTS) if not isinstance(warning_audit, dict) or any( warning_audit.get(key) != value for key, value in { "status": "PASS", "expected_unbound_ports": expected_ports, "observed_unbound_ports": expected_ports, "unexpected_unbound_ports": [], "missing_expected_unbound_ports": [], }.items() ): raise SystemExit( "6400 firmware package blocked: TD warning audit mismatch" ) bitstream_value = receipt.get("bitstream") if not isinstance(bitstream_value, str) or not bitstream_value: raise SystemExit("6400 firmware package blocked: TD receipt has no bitstream") bitstream = Path(bitstream_value) if not bitstream.is_absolute(): bitstream = receipt_path.parent / bitstream expected_name = f"{profile['artifact_basename']}.bit" if bitstream.name != expected_name or not bitstream.is_file() or bitstream.stat().st_size == 0: raise SystemExit("6400 firmware package blocked: receipt bitstream is missing or misnamed") if receipt.get("bitstream_sha256") != _sha256(bitstream): raise SystemExit("6400 firmware package blocked: receipt bitstream SHA-256 mismatch") return bitstream.resolve(), receipt def build_target_package( target_name: str, kind: str, output_dir: Path, include_reference: bool = False, *, profile_name: str | None = None, td_receipt: Path | None = None, ) -> Path: is_6400 = target_name == "6400" or target_name.startswith("6400-") receipt_payload: dict[str, object] | None = None expanded_closure: dict[str, object] | None = None hardware_validation = "NOT RUN" known_unbound_ports: tuple[str, ...] = () deployment_status: str | None = None source_commit: str | None = None if is_6400: selected_profile = _resolve_6400_profile(target_name, profile_name) profile = HARDWARE_PROFILES[selected_profile] _check_active_6400_generated() project_path = ROOT / str(profile["project"]) closure_path = ROOT / str(profile["closure"]) generated_dir = ROOT / "generated/6400" project = json.loads(project_path.read_text(encoding="utf-8")) sources, _closure_inputs = td_source_closure(selected_profile) top_module = str(project["top"]) project_id = selected_profile target_alias = "6400" package_label = selected_profile blocked, pins = False, () expanded_closure = { "schema": "prod2u-source-closure-expanded-v1", "project_id": selected_profile, "top_module": top_module, "sources": sources, } else: target = resolve_target(target_name) generate_named_target(target.alias) project_path = target.project_config closure_path = target.source_closure generated_dir = target.generated_dir project = json.loads(project_path.read_text(encoding="utf-8")) blocked, pins = release_blocked(target, project) sources = list(load_source_closure(target)) top_module = target.top_module project_id = target.project_id target_alias = target.alias package_label = target.alias selected_profile = target.profile if kind == "firmware" and blocked: raise SystemExit( "release_blocked\n" + "\n".join(f"{name} pin unresolved" for name in pins) ) commit = _git(ROOT, "rev-parse", "HEAD") bitstream_path: Path | None = None if kind == "firmware" and is_6400: if not re.fullmatch(r"[0-9a-f]{40}", commit): raise SystemExit("6400 firmware package blocked: exact Git commit is unavailable") bitstream_path, receipt_payload = _validated_td_bitstream( selected_profile, td_receipt, commit ) ports_value = receipt_payload["known_unbound_ports"] status_value = receipt_payload["deployment_status"] assert isinstance(ports_value, list) assert all(isinstance(port, str) for port in ports_value) assert isinstance(status_value, str) known_unbound_ports = tuple(ports_value) deployment_status = status_value source_commit_value = receipt_payload["commit"] assert isinstance(source_commit_value, str) source_commit = source_commit_value # Hardware NOT RUN is an evidence boundary, not a source/TD packaging # failure. A logic-bound UART + Host-I2C image may be handed to the # user for programming while remaining explicitly unvalidated on real # hardware. Identification is never Production, but may be programmed # for the finite stimulus workflow. blocked = bool(known_unbound_ports) pins = known_unbound_ports run_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") name = f"prod2u-{package_label}-{kind}-{commit[:12]}-{run_id}" output_dir.mkdir(parents=True, exist_ok=True) zip_path = output_dir / f"{name}.zip" manifest = { "schema": "prod2u-target-package-v1", "target_alias": target_alias, "profile": selected_profile, "firmware_role": "production" if is_6400 else "legacy", "project_id": project_id, "top": top_module, "kind": kind, "commit": commit, "run_id": run_id, "project_config_sha256": _sha256(project_path), "source_closure_sha256": _sha256(closure_path), "source_manifest_sha256": ( receipt_payload.get("source_manifest_sha256") if receipt_payload is not None else None ), "bitstream_sha256": _sha256(bitstream_path) if bitstream_path else None, "hardware_validation": hardware_validation, "release_blocked": blocked, "unresolved_pins": list(pins), "include_reference": include_reference, } if is_6400: manifest.update( { "contract_sha256": _contract_sha256(), "production": bool(profile["production"]), "stimulus": bool(profile["stimulus"]), "simulation_only": False, } ) if is_6400 and kind == "firmware": manifest.update( { "candidate_notice_zh_CN": CANDIDATE_NOTICE_ZH_CN, "candidate_only": hardware_validation != "PASS", "td_programmable": not blocked, # The image is safe to hand off for user-controlled programming # after TD passes, but real hardware acceptance remains NOT RUN. "deployable": False, "production_deployable": False, "identification_programmable": ( not blocked and not bool(profile["production"]) ), "hardware_validated": hardware_validation == "PASS", "deployment_status": deployment_status, "source_commit": source_commit, "package_commit": commit, "known_unbound_ports": list(known_unbound_ports), "unresolved_ports": list(known_unbound_ports), } ) with tempfile.TemporaryDirectory() as tmp: stage = Path(tmp) (stage / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n", encoding="utf-8") if is_6400 and kind == "firmware" and blocked: (stage / "CANDIDATE-NOTICE.zh-CN.txt").write_text( DO_NOT_PROGRAM_LINE + "\n" + CANDIDATE_NOTICE_ZH_CN + "\n" + f"未冻结端口:{', '.join(known_unbound_ports)}\n" + f"部署状态:{deployment_status}\n" + f"硬件验证:{hardware_validation}\n", encoding="utf-8", ) shutil.copy2(project_path, stage / "project.json") shutil.copy2(closure_path, stage / "source-closure.json") if expanded_closure is not None: (stage / "source-closure-expanded.json").write_text( json.dumps(expanded_closure, indent=2, sort_keys=True) + "\n", encoding="utf-8", ) if receipt_payload is not None: source_manifest_bytes = json.dumps( receipt_payload["inputs"], sort_keys=True, separators=(",", ":"), ).encode() (stage / "source-manifest.json").write_bytes(source_manifest_bytes) gen_dir = stage / ("generated/6400" if is_6400 else "generated") if generated_dir.is_dir(): shutil.copytree(generated_dir, gen_dir) src_dir = stage / "src" src_dir.mkdir() for rel in sources: dest = stage / rel dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(ROOT / rel, dest) if bitstream_path is not None: bitstream_name = bitstream_path.name shutil.copy2(bitstream_path, stage / bitstream_name) (stage / "BITSTREAM-SHA256.txt").write_text( f"{_sha256(bitstream_path)} {bitstream_name}\n", encoding="ascii", ) role = "生产" instruction_header = ( DO_NOT_PROGRAM_LINE if blocked else ( PRODUCTION_PROGRAM_LINE if is_6400 else IDENTIFICATION_PROGRAM_LINE ) ) (stage / "FLASH-INSTRUCTIONS.zh-CN.txt").write_text( instruction_header + "\n" + CANDIDATE_NOTICE_ZH_CN + "\n\n" + f"6400 {role}固件审核说明\n" "========================\n" "目标器件:EF2L45BG256B(6400 前后独立温控)\n" f"固件文件:{bitstream_name}\n" "请审核 BITSTREAM-SHA256.txt 与 TD-BUILD-RECEIPT.json 后再冻结制品。\n" f"Host 串口仅使用 CON78 RS-232 921600 8N1;每条合法命令先独立 ACK;Profile={selected_profile}。\n" "本包只包含 6400 固件,不能用于 MRDIMM 门控板。\n" + "本固件对保留的 SET_STIMULUS 返回 UNSUPPORTED NACK。\n" + "\n" "注意:本次交付未执行真实 JTAG/硬件烧录,硬件验证状态为 NOT RUN。\n", encoding="utf-8", ) assert receipt_payload is not None (stage / "TD-BUILD-RECEIPT.json").write_text( json.dumps(receipt_payload, indent=2, sort_keys=True) + "\n", encoding="utf-8", ) if include_reference: ref = ROOT / "reference" if ref.is_dir(): shutil.copytree(ref, stage / "reference", dirs_exist_ok=True) sums: dict[str, str] = {} if zip_path.exists(): zip_path.unlink() with zipfile.ZipFile(zip_path, "w", compression=zipfile.ZIP_DEFLATED) as zipf: for path in sorted(stage.rglob("*")): if path.is_file(): _add(zipf, path, path.relative_to(stage).as_posix(), sums) zipf.writestr("SHA256SUMS", "".join(f"{digest} {name}\n" for name, digest in sorted(sums.items()))) _selftest(zip_path) return zip_path def _selftest(zip_path: Path) -> None: with tempfile.TemporaryDirectory() as tmp: dest = Path(tmp) / "unpacked" dest.mkdir() with zipfile.ZipFile(zip_path) as zipf: for info in zipf.infolist(): if info.filename.startswith("/") or ".." in Path(info.filename).parts: raise SystemExit(f"unsafe zip path: {info.filename}") zipf.extractall(dest) manifest = json.loads((dest / "manifest.json").read_text(encoding="utf-8")) if manifest.get("hardware_validation") != "NOT RUN": raise SystemExit("package selftest: hardware_validation must be NOT RUN") sums = (dest / "SHA256SUMS").read_text(encoding="utf-8").splitlines() for line in sums: digest, name = line.split(" ", 1) observed = _sha256(dest / name) if observed != digest: raise SystemExit(f"hash mismatch {name}") if manifest.get("target_alias") == "6400": profile_name = manifest.get("profile") if profile_name not in HARDWARE_PROFILES: raise SystemExit("package selftest: invalid 6400 hardware profile") members = [path.relative_to(dest).as_posix() for path in dest.rglob("*")] if any(name.startswith("src/generated/6400/") for name in members): raise SystemExit("package selftest: historical src/generated/6400 leaked") closure = json.loads( (dest / "source-closure-expanded.json").read_text(encoding="utf-8") ) closure_text = "\n".join(closure["sources"]) if "src/generated/6400" in closure_text or "prod2u_6400_front_back_top" in closure_text: raise SystemExit("package selftest: historical 6400 closure leaked") if manifest.get("target_alias") == "6400" and manifest.get("kind") == "firmware": profile_name = manifest["profile"] profile = HARDWARE_PROFILES[profile_name] expected_name = "prod2u_6400_front_back.bit" bit = dest / expected_name if not bit.is_file() or _sha256(bit) != manifest.get("bitstream_sha256"): raise SystemExit("package selftest: 6400 bitstream identity mismatch") receipt = json.loads( (dest / "TD-BUILD-RECEIPT.json").read_text(encoding="utf-8") ) if receipt.get("profile") != profile_name or receipt.get( "bitstream_sha256" ) != manifest["bitstream_sha256"]: raise SystemExit("package selftest: TD receipt/profile identity mismatch") embedded_contract = json.loads( (dest / "generated/6400/host-contract.json").read_text( encoding="utf-8" ) ) if ( manifest.get("contract_sha256") != embedded_contract.get("contract_sha256") or manifest.get("source_commit") != receipt.get("commit") or manifest.get("package_commit") != manifest.get("commit") or receipt.get("inputs") != td_input_manifest(profile_name) ): raise SystemExit("package selftest: firmware provenance mismatch") expected_input_sha = hashlib.sha256( json.dumps( receipt["inputs"], sort_keys=True, separators=(",", ":") ).encode() ).hexdigest() if ( receipt.get("source_manifest_sha256") != expected_input_sha or receipt.get("project_sha256") != _sha256(dest / "project.json") or receipt.get("source_closure_sha256") != _sha256(dest / "source-closure.json") or manifest.get("source_closure_sha256") != receipt.get("source_closure_sha256") or manifest.get("source_manifest_sha256") != expected_input_sha or not (dest / "source-manifest.json").is_file() or _sha256(dest / "source-manifest.json") != expected_input_sha ): raise SystemExit("package selftest: TD input digest mismatch") receipt_ports = receipt.get("known_unbound_ports") expected_ports = list(EXPECTED_UNBOUND_PORTS) warning_audit = receipt.get("warning_audit") if ( manifest.get("release_blocked") is not False or manifest.get("td_programmable") is not True or manifest.get("candidate_only") is not True or manifest.get("hardware_validated") is not False or manifest.get("deployable") is not False or manifest.get("production_deployable") is not False or manifest.get("identification_programmable") is not (not bool(profile["production"])) or receipt_ports != expected_ports or manifest.get("known_unbound_ports") != receipt_ports or manifest.get("unresolved_ports") != receipt_ports or manifest.get("unresolved_pins") != receipt_ports or receipt.get("deployment_status") != _expected_deployment_status(profile_name) or manifest.get("deployment_status") != receipt.get("deployment_status") or not isinstance(warning_audit, dict) or warning_audit.get("status") != "PASS" or warning_audit.get("observed_unbound_ports") != expected_ports ): raise SystemExit("package selftest: unsafe deployment gate mismatch") if (dest / "CANDIDATE-NOTICE.zh-CN.txt").exists(): raise SystemExit("package selftest: stale release-block notice present") if ( manifest.get("production") is not bool(profile["production"]) or manifest.get("stimulus") is not bool(profile["stimulus"]) or (not bool(profile["production"]) and manifest.get("deployable")) ): raise SystemExit("package selftest: firmware profile semantics mismatch") instructions = (dest / "FLASH-INSTRUCTIONS.zh-CN.txt").read_text( encoding="utf-8" ) expected_header = ( PRODUCTION_PROGRAM_LINE if bool(profile["production"]) else IDENTIFICATION_PROGRAM_LINE ) if ( not instructions.startswith(expected_header) or "921600 8N1" not in instructions or "独立 ACK" not in instructions or any(token in instructions for token in FORBIDDEN_PROGRAM_INSTRUCTIONS) ): raise SystemExit("package selftest: Host UART/ACK contract missing") def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser() parser.add_argument("--target", required=True) parser.add_argument("--kind", choices=("source", "review", "firmware", "analysis-base", "analysis-current", "gui", "delivery"), default="source") parser.add_argument( "--profile", choices=("6400-front-rear",), ) parser.add_argument("--td-receipt", type=Path) parser.add_argument("--base-zip", type=Path) parser.add_argument("--gui-exe", type=Path) parser.add_argument("--gui-zip", type=Path) parser.add_argument("--status-json", type=Path) parser.add_argument("--output-dir", type=Path, default=ROOT / "dist") parser.add_argument("--include-reference", action="store_true") args = parser.parse_args(argv) if args.kind == "analysis-base": path = package_6400_canonical.package_base(args.output_dir) elif args.kind == "analysis-current": if args.base_zip is None: parser.error("--base-zip is required for analysis-current") path = package_6400_canonical.package_current(args.output_dir, args.base_zip) elif args.kind == "delivery": required = (args.td_receipt, args.gui_exe, args.gui_zip, args.status_json) if any(value is None for value in required): parser.error("delivery requires --td-receipt --gui-exe --gui-zip --status-json") path = package_6400_canonical.package_delivery( args.output_dir, args.td_receipt, args.gui_exe, args.gui_zip, args.status_json ) elif args.kind == "gui": if args.gui_exe is None: parser.error("gui requires --gui-exe") path = package_6400_canonical.package_gui(args.output_dir, args.gui_exe) else: path = build_target_package( args.target, args.kind, args.output_dir, args.include_reference, profile_name=args.profile, td_receipt=args.td_receipt, ) print(json.dumps({"status": "pass", "package": str(path), "sha256": _sha256(path)}, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())