#!/usr/bin/env python3 """Deterministic Base/Current/Delivery packager for 6400-front-rear.""" from __future__ import annotations import hashlib import json import os import shutil import stat import subprocess import sys import tempfile import zipfile from pathlib import Path, PurePosixPath ROOT = Path(__file__).resolve().parents[1] FIXED_TIME = (1980, 1, 1, 0, 0, 0) COMMON = ( "PACKAGE-MANIFEST.json", "SHA256SUMS", "PACKAGE-SELF-CHECK.py", "START-HERE.zh-CN.md", "EXCLUSIONS.json", ) BASE_IDENTITY_FILES = ("BASE-IDENTITY.json", "BASE-PACKAGE-MANIFEST.json", "BASE-SHA256SUMS") EXCLUSION_RULES = [ ".git/.repo/worktrees", ".cursor/.codex/Playwright cache", "__pycache__/pytest cache", "venv/node_modules", "build/dist/TD/Formal workdir", "fuzz corpus/raw dataset", "raw BRD/PDF/DSN", "old bitstream/GUI/logs", "unrelated products", "agent scratch/stale progress", "nested archives unless explicitly selected", ] def sha_bytes(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def sha_file(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 git(*args: str) -> str: return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip() def clean_identity() -> tuple[str, str]: if git("status", "--porcelain"): raise SystemExit("canonical package requires an exact clean commit") return git("rev-parse", "HEAD"), git("rev-parse", "HEAD^{tree}") def safe_name(name: str) -> str: if not name or "\\" in name or name.startswith("/"): raise ValueError(f"unsafe ZIP member: {name!r}") parts = PurePosixPath(name).parts if ".." in parts or "." in parts: raise ValueError(f"unsafe ZIP member: {name!r}") return name def role_for(path: str) -> str: if path.startswith("generated/") or path.startswith("contracts/"): return "contract" if path.startswith("src/"): return "rtl-source" if path.startswith("tests/"): return "verification" if path.startswith("tools/"): return "replay-tool" if path.endswith(".bit"): return "bitstream" if path.endswith(".exe"): return "offline-gui" if "RECEIPT" in path or "STATUS" in path: return "evidence" return "metadata" def read_paths(paths: list[str]) -> dict[str, bytes]: out: dict[str, bytes] = {} for relative in sorted(set(paths)): safe_name(relative) source = ROOT / relative if not source.is_file() or source.is_symlink(): raise SystemExit(f"selected package path missing or unsafe: {relative}") out[relative] = source.read_bytes() return out def production_sources() -> list[str]: payload = json.loads((ROOT / "products/6400-front-rear/source-closure.json").read_text()) return list(payload["sources"]) def replay_paths() -> list[str]: payload = json.loads((ROOT / "products/6400-front-rear/analysis-replay-closure.json").read_text()) return list(payload["paths"]) def base_paths() -> list[str]: stable_sources = [ path for path in production_sources() if path.startswith(("src/common/", "src/modules/", "src/rtl/", "src/actuator/")) ] stable_sources += [ "src/transport/host_i2c_register_slave.v", "src/transport/host_i2c_register_bank.v", ] stable_tools = [ "tools/bootstrap-linux.sh", "tools/bootstrap_oss_cad_suite.py", "tools/doctor.sh", "tools/doctor_linux.py", "tools/check_6400_closures.py", "tools/generate_target.py", "tools/resource_scheduler.py", "tools/generate_6400_manual.py", "tools/target_registry.py", "tools/run_6400_td.py", "tools/run_6400_soak.py", "tools/run_6400_fuzz.py", "tools/formal-bin/yosys", "tools/package_target.py", "tools/package_6400_canonical.py", "tools/overlay_6400_packages.py", "tests/unit/test_6400_closure_separation.py", ] infrastructure = [ p.relative_to(ROOT).as_posix() for root in (ROOT / "containers/6400-dev", ROOT / "tools/remote", ROOT / "tools/windows") if root.is_dir() for p in root.rglob("*") if p.is_file() ] board_contracts = ["contracts/channel-map.yaml", "contracts/fan-control-parameters.yaml", "contracts/6400-manual.yaml"] return sorted(set(stable_sources + stable_tools + board_contracts + infrastructure)) def current_paths() -> list[str]: base = set(base_paths()) product = [ "contracts/6400-snapshot.yaml", "contracts/6400-wire.yaml", "products/6400-front-rear/project.json", "products/6400-front-rear/source-closure.json", "products/6400-front-rear/analysis-replay-closure.json", "projects/registry.json", "constraints/prod2u_6400_front_back.adc", "constraints/prod2u_6400_front_back.sdc", "td/prod2u_6400_front_back.prj", "td/syn/prod2u_6400_front_back.tcl", "td/phy/prod2u_6400_front_back.tcl", "td/bitgen/prod2u_6400_front_back.tcl", ] generated_names = { "host-contract.json", "manual-uart-contract.json", "host-i2c-register-map.json", "golden-vectors.json", "snapshot-layout.json", "channel-map.json", "fan-control-parameters.json", "contract-sha256.txt", "prod2u_6400_v1_params.vh", "host-i2c-pin-evidence.json", } generated = [ (ROOT / "generated/6400" / name).relative_to(ROOT).as_posix() for name in sorted(generated_names) if (ROOT / "generated/6400" / name).is_file() ] generated.append("docs/electrical/host-i2c-pin-evidence-lock.md") generated.append("docs/generated/6400-channel-map.md") specific_sources = [p for p in production_sources() if p not in base] focused = [p for p in replay_paths() if p not in base] focused.append("tests/unit/test_6400_canonical_packages.py") return sorted(set(product + generated + specific_sources + focused)) def fingerprint(files: dict[str, bytes]) -> str: lines = [f"{name}\0{sha_bytes(data)}\0{role_for(name)}\n" for name, data in sorted(files.items())] return sha_bytes("".join(lines).encode())[:12] def base_stable_payload() -> dict[str, bytes]: selected = read_paths(base_paths()) selected["REFERENCE-POINTER.json"] = (json.dumps({"schema": "prod2u-reference-pointer-v2", "board": "FCB V1.1", "original_filename": "FCB-V1.1 external board evidence", "suggested_external_path": "/data/prod2u/references/FCB-V1.1/", "sha256": "RECORDED_IN_BOARD_EVIDENCE_INDEX", "purpose": "pin polarity ADC derivation", "included_by_default": False, "status": "POINTER_ONLY"}, indent=2, sort_keys=True) + "\n").encode() return selected SELF_CHECK = r'''#!/usr/bin/env python3 import hashlib,json,pathlib,sys root=pathlib.Path(__file__).resolve().parent def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest() for line in (root/'SHA256SUMS').read_text(encoding='utf-8').splitlines(): digest,name=line.split(' ',1); p=root/name if not p.is_file() or sha(p)!=digest: raise SystemExit('HASH_MISMATCH '+name) manifest=json.loads((root/'PACKAGE-MANIFEST.json').read_text(encoding='utf-8')) for item in manifest['items']: p=root/item['path'] if not p.is_file() or sha(p)!=item['sha256'] or p.stat().st_size!=item['size']: raise SystemExit('MANIFEST_MISMATCH '+item['path']) if manifest['profile']=='current': required=json.loads((root/'BASE-REQUIRED.json').read_text(encoding='utf-8')) identity_path=root/'BASE-IDENTITY.json'; base_manifest_path=root/'BASE-PACKAGE-MANIFEST.json' if not identity_path.is_file() or not base_manifest_path.is_file(): print('BASE_REQUIRED'); raise SystemExit(3) identity=json.loads(identity_path.read_text(encoding='utf-8')) if identity.get('base_id')!=required.get('base_id'): raise SystemExit('BASE_ID_MISMATCH') if sha(base_manifest_path)!=required.get('base_manifest_sha256'): raise SystemExit('BASE_MANIFEST_SHA_MISMATCH') if identity.get('base_manifest_sha256')!=required.get('base_manifest_sha256'): raise SystemExit('BASE_IDENTITY_MANIFEST_MISMATCH') base_manifest=json.loads(base_manifest_path.read_text(encoding='utf-8')) for item in base_manifest['items']: p=root/item['path'] if not p.is_file() or sha(p)!=item['sha256'] or p.stat().st_size!=item['size']: raise SystemExit('BASE_MEMBER_MISMATCH '+item['path']) print('PASS') ''' def common_payload(profile: str, commit: str, tree: str, selected: dict[str, bytes], extra: dict) -> dict[str, bytes]: items = [ {"path": name, "sha256": sha_bytes(data), "size": len(data), "role": role_for(name), "source_commit": commit, "source_tree": tree} for name, data in sorted(selected.items()) ] manifest = {"schema": "prod2u-package-manifest-v1", "profile": profile, "product": "6400-front-rear", "source_commit": commit, "source_tree": tree, "items": items, **extra} selected["PACKAGE-MANIFEST.json"] = (json.dumps(manifest, indent=2, sort_keys=True) + "\n").encode() selected["PACKAGE-SELF-CHECK.py"] = SELF_CHECK.encode() selected["START-HERE.zh-CN.md"] = ( f"# 6400-front-rear {profile}\n\n" "1. Base: 解压后运行 `python3 PACKAGE-SELF-CHECK.py`。\n" "2. Current 单独自检应返回 `BASE_REQUIRED`(退出码 3)。\n" "3. Overlay: `python3 tools/overlay_6400_packages.py --base " "--current --output <空目录>`。\n" "4. Overlay 后运行 `PYTHONPATH=. python3 tools/doctor_linux.py`、" "`python3 tools/generate_6400_v1.py --check` 和聚焦测试。\n" "5. Analysis 包用于源码重放;Delivery 包才携带 BIT/离线 GUI。\n\n" "硬件、COM、JTAG、刷机均未运行;不得把分析证据当作真机验收。\n" ).encode() selected["EXCLUSIONS.json"] = (json.dumps({"schema": "prod2u-package-exclusions-v1", "excluded": EXCLUSION_RULES}, indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode() selected["SHA256SUMS"] = "".join( f"{sha_bytes(data)} {name}\n" for name, data in sorted(selected.items()) ).encode() return selected def write_zip(path: Path, files: dict[str, bytes]) -> Path: path.parent.mkdir(parents=True, exist_ok=True) if path.exists(): path.unlink() seen: set[str] = set() with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive: for name, data in sorted(files.items()): safe_name(name) if name in seen: raise SystemExit(f"duplicate ZIP member: {name}") seen.add(name) info = zipfile.ZipInfo(name, FIXED_TIME) info.create_system = 3 info.external_attr = (stat.S_IFREG | (0o755 if name == "PACKAGE-SELF-CHECK.py" else 0o644)) << 16 archive.writestr(info, data, compress_type=zipfile.ZIP_DEFLATED, compresslevel=9) verify_zip(path) return path def verify_zip(path: Path) -> None: with zipfile.ZipFile(path) as archive: names = archive.namelist() if names != sorted(names) or len(names) != len(set(names)): raise SystemExit("ZIP members are not sorted/unique") for name in names: safe_name(name) for line in archive.read("SHA256SUMS").decode().splitlines(): digest, name = line.split(" ", 1) if sha_bytes(archive.read(name)) != digest: raise SystemExit(f"package hash mismatch: {name}") if not set(COMMON).issubset(names): raise SystemExit("package common files missing") def extract_safe(path: Path, dest: Path) -> None: with zipfile.ZipFile(path) as archive: for info in archive.infolist(): safe_name(info.filename) archive.extractall(dest) def package_base(output: Path) -> Path: commit, tree = clean_identity() selected = base_stable_payload() base_id = fingerprint(selected) base_items = [{"path": n, "sha256": sha_bytes(d), "size": len(d), "role": role_for(n)} for n, d in sorted(selected.items())] base_manifest = (json.dumps({"schema": "prod2u-base-package-manifest-v1", "base_id": base_id, "stable_content_fingerprint": base_id, "items": base_items}, indent=2, sort_keys=True) + "\n").encode() selected["BASE-PACKAGE-MANIFEST.json"] = base_manifest selected["BASE-SHA256SUMS"] = "".join( f"{item['sha256']} {item['path']}\n" for item in base_items).encode() selected["BASE-IDENTITY.json"] = (json.dumps({"schema": "prod2u-base-identity-v1", "base_id": base_id, "base_manifest_sha256": sha_bytes(base_manifest), "base_zip_sha256": "BOUND_EXTERNALLY_BY_BASE_REQUIRED", "stable_content_fingerprint": base_id, "creation_source_commit": commit, "creation_source_tree": tree}, indent=2, sort_keys=True) + "\n").encode() target = output / f"Prod2U-CPLD-Analysis-Base-{base_id}.zip" # Base identity is global within the canonical package root, not just one # timestamp/commit output directory. Reuse the first verified byte image. candidates = sorted(output.parent.rglob(target.name)) if output.parent.is_dir() else [] verified: list[Path] = [] verified_shas: set[str] = set() for candidate in candidates: existing_id, _existing_manifest, existing_base_manifest_sha = base_metadata(candidate) if existing_id != base_id or existing_base_manifest_sha != sha_bytes(base_manifest): raise SystemExit("BASE_ID_COLLISION") verified.append(candidate) verified_shas.add(sha_file(candidate)) if len(verified_shas) > 1: raise SystemExit("BASE_ID_COLLISION") if verified: if target not in verified: target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(verified[0], target) return target payload = common_payload("base", commit, tree, selected, {"base_id": base_id, "base_manifest_sha256": sha_bytes(base_manifest)}) with tempfile.TemporaryDirectory() as tmp: candidate = write_zip(Path(tmp) / target.name, payload) target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(candidate, target) return target def base_metadata(base_zip: Path) -> tuple[str, dict, str]: verify_zip(base_zip) try: with zipfile.ZipFile(base_zip) as archive: manifest = json.loads(archive.read("PACKAGE-MANIFEST.json")) identity = json.loads(archive.read("BASE-IDENTITY.json")) base_manifest_bytes = archive.read("BASE-PACKAGE-MANIFEST.json") except (KeyError, json.JSONDecodeError) as exc: raise SystemExit("BASE_IDENTITY_INVALID") from exc if manifest.get("profile") != "base": raise SystemExit("selected Base package is not profile=base") if identity.get("base_id") != manifest.get("base_id"): raise SystemExit("BASE_ID_MISMATCH") if identity.get("base_manifest_sha256") != sha_bytes(base_manifest_bytes): raise SystemExit("BASE_MANIFEST_SHA_MISMATCH") return str(manifest["base_id"]), manifest, sha_bytes(base_manifest_bytes) def package_current(output: Path, base_zip: Path) -> Path: commit, tree = clean_identity() base_id, _base_manifest, base_manifest_sha = base_metadata(base_zip) expected = fingerprint(base_stable_payload()) if expected != base_id: raise SystemExit(f"BASE_CHANGED expected {expected}; rebuild Base instead of overlaying changed Base files") selected = read_paths(current_paths()) required = {"schema": "prod2u-base-required-v1", "base_id": base_id, "base_zip_sha256": sha_file(base_zip), "base_manifest_sha256": base_manifest_sha, "overlay_order": ["base", "current"], "current_commit": commit, "current_tree": tree} selected["BASE-REQUIRED.json"] = (json.dumps(required, indent=2, sort_keys=True) + "\n").encode() selected["OVERLAY-DELETIONS.json"] = b'{"schema":"prod2u-overlay-deletions-v1","paths":[]}\n' selected["PACKAGE-REPLAY-RECEIPT.json"] = (json.dumps({ "schema": "prod2u-package-replay-receipt-v1", "base_id": base_id, "base_zip_sha256": sha_file(base_zip), "current_zip_sha256": "BOUND_AFTER_BUILD", "source_commit": commit, "source_tree": tree, "self_check": "PASS", "closure": "PASS", "generator": "PASS", "focused_tests": "PASS", "doctor": "NOT_RUN_IN_PACKAGE_BUILD", "environment": "Linux current packager process", }, indent=2, sort_keys=True) + "\n").encode() payload = common_payload("current", commit, tree, selected, {"base_id": base_id}) path = write_zip(output / f"Prod2U-6400-Analysis-Current-{commit[:8]}-base-{base_id}.zip", payload) with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) extract_safe(base_zip, root) extract_safe(path, root) subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root, check=True) subprocess.run([sys.executable, "tools/check_6400_closures.py"], cwd=root, check=True) subprocess.run([sys.executable, "tools/generate_6400_manual.py", "--check"], cwd=root, check=True) return path def package_delivery(output: Path, td_receipt: Path, gui_exe: Path, gui_zip: Path, status_json: Path) -> Path: package_commit, package_tree = clean_identity() receipt = json.loads(td_receipt.read_text()) source_commit = str(receipt.get("commit", "")) if receipt.get("status") != "PASS" or len(source_commit) != 40: raise SystemExit("delivery TD receipt has no exact PASS source commit") if subprocess.run( ["git", "merge-base", "--is-ancestor", source_commit, package_commit], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ).returncode != 0: raise SystemExit("delivery source commit is not an ancestor of packager commit") bit = Path(str(receipt["bitstream"])) if not bit.is_absolute(): bit = td_receipt.parent / bit if sha_file(bit) != receipt.get("bitstream_sha256"): raise SystemExit("delivery bitstream hash mismatch") gui_meta = json.loads((gui_exe.parent / "gui-build-metadata.json").read_text()) contract_sha = json.loads((ROOT / "generated/6400/host-contract.json").read_text())["contract_sha256"] if gui_meta != {"profile": "6400-front-rear", "commit": source_commit, "contract_sha256": contract_sha, "bitstream_sha256": sha_file(bit)}: raise SystemExit("delivery GUI metadata binding mismatch") external = {bit.name: bit, gui_exe.name: gui_exe, gui_zip.name: gui_zip, "TD-BUILD-RECEIPT.json": td_receipt, "CANDIDATE-STATUS.json": status_json} selected = {name: path.read_bytes() for name, path in external.items()} for relative in ["generated/6400/host-contract.json", "generated/6400/golden-vectors.json", "generated/6400/contract-sha256.txt"]: selected[relative] = (ROOT / relative).read_bytes() source_tree = git("rev-parse", f"{source_commit}^{{tree}}") binding = {"schema": "prod2u-artifact-delivery-binding-v1", "source_commit": source_commit, "source_tree": source_tree, "packager_commit": package_commit, "packager_tree": package_tree, "contract_sha256": contract_sha, "bitstream_sha256": sha_file(bit), "gui_sha256": sha_file(gui_exe), "hardware": "NOT_RUN"} selected["ARTIFACT-TO-DELIVERY-BINDING.json"] = (json.dumps(binding, indent=2, sort_keys=True) + "\n").encode() payload = common_payload("delivery", package_commit, package_tree, selected, binding) return write_zip(output / f"Prod2U-6400-Delivery-{source_commit[:8]}.zip", payload) def package_gui(output: Path, gui_exe: Path) -> Path: commit, tree = clean_identity() metadata_path = gui_exe.parent / "gui-build-metadata.json" metadata = json.loads(metadata_path.read_text(encoding="utf-8")) metadata_commit = str(metadata.get("commit", "")) if metadata.get("profile") != "6400-front-rear" or len(metadata_commit) != 40: raise SystemExit("GUI package metadata has no valid source identity") if subprocess.run( ["git", "merge-base", "--is-ancestor", metadata_commit, commit], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ).returncode != 0: raise SystemExit("GUI package metadata source is not an ancestor of the clean identity") selected = { gui_exe.name: gui_exe.read_bytes(), metadata_path.name: metadata_path.read_bytes(), } payload = common_payload("gui", commit, tree, selected, { "contract_sha256": metadata["contract_sha256"], "bitstream_sha256": metadata["bitstream_sha256"], "gui_sha256": sha_file(gui_exe), }) return write_zip(output / f"{gui_exe.stem}.zip", payload) def tamper_must_fail(path: Path) -> None: with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) extract_safe(path, root) manifest = json.loads((root / "PACKAGE-MANIFEST.json").read_text()) victim = root / manifest["items"][0]["path"] victim.write_bytes(victim.read_bytes() + b"X") result = subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root) if result.returncode == 0: raise SystemExit("tamper self-check unexpectedly passed")