#!/usr/bin/env python3 """Package current sources, qualified firmware, native GUI and actual debug evidence. No dated default BITs, invented hardware results, or implicit delivery/cleanup. All inputs are explicit and hashes are checked before any firmware is included. """ from __future__ import annotations import argparse from datetime import datetime, timezone import hashlib import json from pathlib import Path import subprocess import sys import tempfile ROOT = Path(__file__).resolve().parents[1] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) from tools.package_archive import encode, finalize, read_archive, write_archive PRODUCTS = {"6400-v2", "mrdimm-chamber"} DEFAULT_PROTOCOL_DOC = Path("docs/CPLD_通讯协议v2.0.md") def digest(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def git(repo: Path, *args: str) -> bytes: return subprocess.check_output(["git", *args], cwd=repo) def snapshot(repo: Path, label: str) -> tuple[dict, dict]: """Include every tracked working file and a recoverable committed history.""" files = {} missing = [] for name in git(repo, "ls-files", "-z").decode().split("\0"): if not name: continue path = repo / name if path.is_file(): files[f"sources/{label}/{name}"] = path.read_bytes() else: missing.append(name) identity = { "path": str(repo), "commit": git(repo, "rev-parse", "HEAD").decode().strip(), "branch": git(repo, "branch", "--show-current").decode().strip(), "tree": git(repo, "rev-parse", "HEAD^{tree}").decode().strip(), "working_status": git(repo, "status", "--porcelain").decode(), "missing_tracked_files": missing, } files[f"changes/{label}-working.diff"] = git(repo, "diff", "HEAD", "--binary") files[f"changes/{label}-status.txt"] = identity["working_status"].encode() with tempfile.TemporaryDirectory() as temporary: bundle = Path(temporary) / "source.bundle" git(repo, "bundle", "create", str(bundle), "HEAD") files[f"history/{label}.bundle"] = bundle.read_bytes() return files, identity def verified_td(run: Path) -> tuple[dict, Path]: receipt = json.loads((run / "td-receipt.json").read_text()) if (receipt.get("profile") not in PRODUCTS or receipt.get("status") != "PASS" or receipt.get("production") is not True or receipt.get("simulation_only") is not False or not receipt.get("timing_pass_25mhz") or receipt.get("warning_audit", {}).get("status") != "PASS"): raise ValueError("unqualified TD run: " + str(run)) inputs = receipt.get("inputs", {}) if not inputs or any(digest((ROOT / name).read_bytes()) != sha for name, sha in inputs.items()): raise ValueError("TD source differs from current files: " + str(run)) actual_manifest = digest(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()) if receipt.get("source_manifest_sha256") != actual_manifest: raise ValueError("invalid TD input manifest: " + str(run)) bit = Path(receipt["bitstream"]) if not bit.is_absolute(): bit = run / bit if digest(bit.read_bytes()) != receipt.get("bitstream_sha256"): raise ValueError("BIT differs from TD receipt: " + str(bit)) return receipt, bit def collect_evidence(root: Path, prefix: str) -> dict[str, bytes]: files = {} # Retain logs, receipts, timing/area reports, fixture sources and raw captures. # Tool databases, waveforms and runnable compiler intermediates are reproducible. omit = {".db", ".vvp", ".vcd", ".fst", ".exe", ".bit", ".tar", ".pyc"} for path in sorted(root.rglob("*")): if path.is_file() and path.suffix.lower() not in omit: if any(part in {"__pycache__", "pytest-temp", "pytest-cache"} for part in path.relative_to(root).parts): continue files[prefix + "/" + path.relative_to(root).as_posix()] = path.read_bytes() return files def package(path: Path, files: dict, identity: dict) -> dict: files = {**files, "PACKAGE-SELF-CHECK.py": (ROOT / "tools/package_archive.py").read_bytes()} payload, modes = finalize(files, {"schema": "prod2u-analysis-manifest-v3", **identity}) write_archive(path, payload, modes) checked = read_archive(path) return {"file": path.name, "sha256": checked["sha256"], "size_bytes": path.stat().st_size, "members": len(checked["files"]), "archive_integrity": "PASS"} def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--td-run", action="append", type=Path, default=[]) parser.add_argument("--td-blocker-receipt", type=Path, default=None, help="Explicit TD blocker JSON when vendor TD bitgen is blocked (no .bit bundled)") parser.add_argument("--gui-dir", type=Path, required=True) parser.add_argument("--review-dir", type=Path, required=True) parser.add_argument("--related-repo", action="append", default=[], metavar="NAME=PATH") parser.add_argument("--hardware-file", action="append", type=Path, default=[]) parser.add_argument("--protocol-doc", type=Path, default=None, help="Maintained protocol document to bundle at release root and inside archives (defaults to docs/CPLD_通讯协议v2.0.md if present)") parser.add_argument("--hardware-status", type=Path, required=True, help="actual connection/programming/test result JSON, including NOT_RUN when unavailable") args = parser.parse_args(argv) if not args.td_run and args.td_blocker_receipt is None: parser.error("requires --td-run or explicit --td-blocker-receipt") out = args.output_dir.resolve() out.mkdir(parents=True, exist_ok=True) version = (ROOT / "VERSION").read_text().strip() sources, identity = snapshot(ROOT, "cpld") repos = {"cpld": identity} for value in args.related_repo: label, separator, path = value.partition("=") if not separator or not label or "/" in label or "\\" in label or label in repos: parser.error("invalid or duplicate NAME=PATH: " + value) extra, extra_identity = snapshot(Path(path).resolve(), label) sources.update(extra) repos[label] = extra_identity stamp = datetime.now(timezone.utc).isoformat() td_blocker = None if args.td_blocker_receipt is not None: td_blocker = json.loads(args.td_blocker_receipt.read_text(encoding="utf-8")) if not str(td_blocker.get("status", "")).startswith("BLOCKED_"): raise ValueError("td_blocker_receipt status must start with BLOCKED_") run = {"release_version": version, "commit": identity["commit"], "branch": identity["branch"], "created_utc": stamp, "repositories": repos, "firmware": [], "td_blocker": td_blocker, "gui": {}, "hardware": json.loads(args.hardware_status.read_text()), "verification_scope": "See individual receipts; archive integrity is not hardware validation"} products, debug = {}, collect_evidence(args.review_dir, "debug/review") seen = set() for path in args.td_run: path = path.resolve() receipt, bit = verified_td(path) product = receipt["profile"] baud = receipt["build_parameters"]["host_baud"] if (product, baud) in seen: parser.error("duplicate product and baud TD run") seen.add((product, baud)) name = f"products/{product}/{baud}" products[name + "/firmware.bit"] = bit.read_bytes() mask = bit.with_suffix(".bmk") if mask.is_file(): products[name + "/firmware.bmk"] = mask.read_bytes() products[name + "/td-receipt.json"] = (path / "td-receipt.json").read_bytes() debug.update(collect_evidence(path, "debug/td/" + product + "/" + str(baud))) run["firmware"].append({"product": product, "host_baud": baud, "bitstream_sha256": receipt["bitstream_sha256"], "td_run": str(path), "metrics": receipt.get("metrics", {}), "source_commit": receipt["commit"]}) if td_blocker is None and not all((p, 921600) in seen for p in PRODUCTS): parser.error("both current products require a qualified default 921600 run") if td_blocker is not None: products["TD-LICENSE-BLOCKER.json"] = encode(td_blocker) gui = json.loads((args.gui_dir / "BUILD-SUMMARY.json").read_text()) if set(gui.get("products", {})) != PRODUCTS: parser.error("native GUI summary must contain both current products") for product, result in gui["products"].items(): exe = args.gui_dir / result["exe"] metadata = result["metadata"] if (result.get("status") != "PASS" or result.get("self_test_exit") != 0 or digest(exe.read_bytes()) != result["sha256"] or metadata.get("release_version") != version): raise ValueError("unqualified native GUI: " + product) if td_blocker is None: matches = [r for r in run["firmware"] if r["product"] == product and r["host_baud"] == metadata["host_baud"]] if not matches or metadata["bitstream_sha256"] != matches[0]["bitstream_sha256"]: raise ValueError("GUI and firmware identity mismatch: " + product) else: if metadata.get("bitstream_sha256") is not None: raise ValueError("blocked-TD GUI must not carry a fabricated bitstream_sha256: " + product) products[f"products/{product}/{exe.name}"] = exe.read_bytes() run["gui"][product] = {"exe": exe.name, "sha256": result["sha256"], "metadata": metadata, "self_test": "PASS", "visual_gui_validation": gui.get("visual_gui_validation", "NOT_RUN")} debug.update(collect_evidence(args.gui_dir, "debug/native-gui")) hardware = {} for path in args.hardware_file: path = path.resolve() try: key = "sources/cpld/" + path.relative_to(ROOT.resolve()).as_posix() except ValueError: key = "hardware/originals/" + path.name data = path.read_bytes() if ((key in hardware and hardware[key] != data) or (key in sources and sources[key] != data)): raise ValueError("conflicting hardware file: " + key) hardware[key] = data start = (ROOT / f"docs/releases/v{version}.md").read_bytes() protocol_doc_path = args.protocol_doc.resolve() if args.protocol_doc is not None else (ROOT / DEFAULT_PROTOCOL_DOC) protocol_doc_bytes = None if protocol_doc_path.is_file(): protocol_doc_bytes = protocol_doc_path.read_bytes() try: proto_rel = protocol_doc_path.relative_to(ROOT.resolve()).as_posix() except ValueError: proto_rel = protocol_doc_path.name run["protocol_doc"] = { "file": protocol_doc_path.name, "source_path": proto_rel, "sha256": digest(protocol_doc_bytes), "size_bytes": len(protocol_doc_bytes), } elif args.protocol_doc is not None: parser.error("missing --protocol-doc: " + str(protocol_doc_path)) common = {"START-HERE.zh-CN.md": start, "RUN.json": encode(run), "EXCLUSIONS.json": encode({"excluded": ["working untracked user files except explicit --hardware-file inputs", "tool databases and vvp/vcd/fst intermediates", "ignored caches", "Git local config (including remote credentials)"], "source_scope": "All Git-tracked working files; explicit hardware originals included with repository-relative paths preserved; committed history in history/*.bundle"})} if protocol_doc_bytes is not None: common[protocol_doc_path.name] = protocol_doc_bytes tag = f"v{version}-{identity['commit'][:8]}" results = [ package(out / f"Prod2U-Source-{tag}.zip", {**sources, **hardware, **common}, {"kind": "source", "version": version}), package(out / f"Prod2U-Debug-Logs-{tag}.zip", {**debug, **common}, {"kind": "debug", "version": version}), package(out / f"Prod2U-Analysis-{tag}.zip", {**sources, **products, **debug, **hardware, **common}, {"kind": "analysis", "version": version}), ] # Convenient unpacked product folders and exact local delivery checksums. for name, data in products.items(): target = out / name target.parent.mkdir(parents=True, exist_ok=True) target.write_bytes(data) (out / "START-HERE.zh-CN.md").write_bytes(start) if protocol_doc_bytes is not None: (out / protocol_doc_path.name).write_bytes(protocol_doc_bytes) (out / "RUN.json").write_bytes(encode(run)) (out / "PACKAGE-RESULTS.json").write_bytes(encode(results)) inventory = [{"path": p.relative_to(out).as_posix(), "sha256": digest(p.read_bytes()), "size_bytes": p.stat().st_size} for p in sorted(out.rglob("*")) if p.is_file() and p.name != "DELIVERY-SHA256.json"] (out / "DELIVERY-SHA256.json").write_bytes(encode(inventory)) print(json.dumps(results, ensure_ascii=False, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())