| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206 |
- #!/usr/bin/env python3
- """Single canonical Base/Current/Delivery package dispatcher.
- Product-specific legacy packagers remain implementation details; this entrypoint
- is the only supported command surface and performs fail-closed ZIP verification.
- """
- from __future__ import annotations
- import argparse, hashlib, json, shutil, stat, sys, tempfile, zipfile
- from pathlib import Path, PurePosixPath
- ROOT = Path(__file__).resolve().parents[1]
- if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT))
- def sha(p: Path) -> str: return hashlib.sha256(p.read_bytes()).hexdigest()
- FIXED_TIME = (1980, 1, 1, 0, 0, 0)
- def _safe(name: str) -> str:
- p = PurePosixPath(name)
- if not name or name.startswith("/") or ".." in p.parts or "\\" in name:
- raise ValueError(f"unsafe package path: {name}")
- return name
- def _zip(path: Path, files: dict[str, bytes]) -> Path:
- path.parent.mkdir(parents=True, exist_ok=True)
- with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as z:
- for name in sorted(files):
- _safe(name)
- info = zipfile.ZipInfo(name, FIXED_TIME); info.create_system = 3
- info.external_attr = (stat.S_IFREG | 0o644) << 16
- z.writestr(info, files[name], compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)
- return path
- def _dual_paths() -> list[str]:
- """Current-only closure for both products, excluding build/cache/secrets."""
- wanted = {
- "projects/registry.json", "projects/prod2u-door-temp/project.json",
- "projects/prod2u-door-temp/requirements.zh-CN.md",
- "products/6400-front-rear/project.json", "products/6400-front-rear/source-closure.json",
- "products/6400-front-rear/analysis-replay-closure.json",
- "docs/prod2u-6400-front-back-protocol.zh-CN.md",
- "contracts/6400-manual.yaml", "contracts/6400-wire.yaml", "contracts/6400-snapshot.yaml",
- "constraints/prod2u_6400_front_back.adc", "constraints/prod2u_6400_front_back.sdc",
- "constraints/prod2u_p4_normal_v3.adc", "constraints/prod2u_p4_normal_v3.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",
- "td/prod2u_p4_normal_v3.prj", "td/syn/prod2u_p4_normal_v3.tcl",
- "td/phy/prod2u_p4_normal_v3.tcl", "td/bitgen/prod2u_p4_normal_v3.tcl",
- "tools/generate_target.py", "tools/generate_project.py", "tools/generate_6400_manual.py",
- "tools/target_registry.py", "tools/fw_cli.py", "tools/package_prod2u.py",
- "tools/mrdimm_hex_gui.py", "tools/build_mrdimm_hex_gui.py", "tools/6400_hex_gui.py",
- "tools/build_6400_hex_gui.py", "tools/overlay_6400_packages.py",
- "ACTIVE_GOAL_LOCK.yaml", "EXECUTION_PLAN.md", "PHASE_STATE.json",
- "TEST_IMPACT_MAP.yaml", "DECISION_TRACE.md", "RECOVERY_LOG.md", "EVIDENCE_INDEX.json",
- "evidence/solver-map.yaml",
- }
- for closure in (ROOT/"config/source_closure.json", ROOT/"products/6400-front-rear/source-closure.json"):
- data = json.loads(closure.read_text(encoding="utf-8"))
- wanted.add(closure.relative_to(ROOT).as_posix())
- wanted.update(str(x).replace("\\", "/") for x in data.get("sources", []))
- for root in (ROOT/"src/generated", ROOT/"generated/6400"):
- if root.is_dir():
- wanted.update(p.relative_to(ROOT).as_posix() for p in root.rglob("*") if p.is_file())
- return sorted(p for p in wanted if (ROOT/p).is_file() and not any(x in p.lower() for x in ("__pycache__", ".pyc", ".pytest_cache", "secret", "token", "password")))
- def _dual_current(output: Path, base_zip: Path) -> Path:
- from tools.package_6400_canonical import base_metadata
- base_id, _manifest, base_manifest_sha = base_metadata(base_zip)
- files = {p: (ROOT/p).read_bytes() for p in _dual_paths()}
- commits = __import__("subprocess").check_output(["git", "rev-parse", "HEAD"], cwd=ROOT, text=True).strip()
- contract_shas = []
- for p in (ROOT/"src/generated/host-contract.json", ROOT/"generated/6400/host-contract.json"):
- if p.is_file(): contract_shas.append(sha(p))
- snapshot = hashlib.sha256((commits + "".join(sorted(contract_shas)) + base_id).encode()).hexdigest()[:16]
- required = {"schema":"prod2u-base-required-v1","base_id":base_id,"base_manifest_sha256":base_manifest_sha,"base_zip_sha256":sha(base_zip)}
- files["BASE-REQUIRED.json"] = (json.dumps(required, indent=2, sort_keys=True)+"\n").encode()
- items = [{"path":p,"sha256":hashlib.sha256(data).hexdigest(),"size":len(data)} for p,data in sorted(files.items())]
- manifest = {"schema":"prod2u-dual-current-manifest-v1","profile":"current","products":["6400-front-rear","mrdimm-chamber"],"source_commit":commits,"snapshot_id":snapshot,"base_id":base_id,"items":items}
- files["PACKAGE-MANIFEST.json"]=(json.dumps(manifest,indent=2,sort_keys=True)+"\n").encode()
- files["PACKAGE-SELF-CHECK.py"]=("import hashlib,json,pathlib\nroot=pathlib.Path(__file__).parent\nm=json.loads((root/'PACKAGE-MANIFEST.json').read_text())\nfor i in m['items']:\n p=root/i['path']; assert p.is_file() and hashlib.sha256(p.read_bytes()).hexdigest()==i['sha256']\nprint('PASS')\n").encode()
- files["START-HERE.zh-CN.md"]=("# Prod2U 双产品 Current\n\n包含 6400 V1.1 与 MRDIMM V1.2 Source Closure;需匹配 Base ZIP 后 Overlay。硬件与 Fresh TD 状态以候选记录为准。\n").encode()
- files["EXCLUSIONS.json"]=(json.dumps({"excluded":[".git","venv","node_modules","__pycache__","BIT/GUI binaries","tokens/secrets/licenses","raw board files","large logs"]},indent=2,ensure_ascii=False)+"\n").encode()
- files["SHA256SUMS"]="".join(f"{hashlib.sha256(data).hexdigest()} {name}\n" for name,data in sorted(files.items())).encode()
- return _zip(output/(f"Prod2U-CPLD-Analysis-Current-{snapshot}-base-{base_id}.zip"), files)
- def _dual_overlay(base_zip: Path, current_zip: Path, output: Path) -> Path:
- """Replay a dual Current over its matching Base without path escapes."""
- from tools.package_6400_canonical import extract_safe, base_metadata
- from tools.package_6400_canonical import sha_file as _sha_file
- base_id, _manifest, _base_manifest_sha = base_metadata(base_zip)
- with zipfile.ZipFile(current_zip) as z:
- manifest = json.loads(z.read("PACKAGE-MANIFEST.json"))
- if manifest.get("schema") != "prod2u-dual-current-manifest-v1" or manifest.get("base_id") != base_id:
- raise SystemExit("BASE_ID_MISMATCH")
- if output.exists() and any(output.iterdir()): raise SystemExit("output directory must be empty")
- output.mkdir(parents=True, exist_ok=True)
- extract_safe(base_zip, output)
- with zipfile.ZipFile(current_zip) as z:
- for info in z.infolist():
- name = _safe(info.filename)
- dest = output / name
- dest.parent.mkdir(parents=True, exist_ok=True)
- dest.write_bytes(z.read(info))
- selfcheck = __import__("subprocess").run([sys.executable, "PACKAGE-SELF-CHECK.py"], cwd=output, text=True, capture_output=True)
- if selfcheck.returncode != 0: raise SystemExit("DUAL_OVERLAY_SELF_CHECK_FAILED")
- required = (output/"projects/prod2u-door-temp/project.json", output/"products/6400-front-rear/project.json")
- if not all(p.is_file() for p in required): raise SystemExit("DUAL_OVERLAY_CLOSURE_INCOMPLETE")
- receipt = {"schema":"prod2u-dual-overlay-receipt-v1","status":"PASS","base_id":base_id,"base_zip_sha256":_sha_file(base_zip),"current_zip_sha256":_sha_file(current_zip),"self_check":selfcheck.stdout.strip()}
- (output/"OVERLAY-RECEIPT.json").write_text(json.dumps(receipt, indent=2, sort_keys=True)+"\n", encoding="utf-8")
- return output
- def verify(path: Path) -> dict:
- raw_archive = path.read_bytes()
- with zipfile.ZipFile(path) as z:
- names = z.namelist()
- if names != sorted(names) or len(names) != len(set(names)): raise SystemExit("invalid ZIP ordering or duplicate members")
- if any(n.startswith("/") or ".." in Path(n).parts for n in names): raise SystemExit("unsafe ZIP member")
- with tempfile.TemporaryDirectory() as t:
- d=Path(t); z.extractall(d)
- sums=d/"SHA256SUMS"
- if sums.is_file():
- for line in sums.read_text(encoding="utf-8").splitlines():
- digest,name=line.split(" ",1)
- if not (d/name).is_file() or sha(d/name)!=digest: raise SystemExit("HASH_MISMATCH "+name)
- try: schema = json.loads((d/"PACKAGE-MANIFEST.json").read_text(encoding="utf-8")).get("schema")
- except Exception: schema = None
- if schema == "prod2u-dual-current-manifest-v1":
- canonical = _zip(d/".canonical.zip", {n: (d/n).read_bytes() for n in names})
- if canonical.read_bytes() != raw_archive: raise SystemExit("NON_CANONICAL_OR_TAMPERED_ARCHIVE")
- return {"status":"PASS","package":str(path.resolve()),"sha256":sha(path)}
- def dispatch_legacy(args: argparse.Namespace) -> Path:
- from tools import package_6400_canonical as c
- if args.action == "base": return c.package_base(args.output_dir)
- if args.action == "current": return _dual_current(args.output_dir, args.base_zip)
- if args.action == "overlay":
- with zipfile.ZipFile(args.current_zip) as z:
- try: current_schema = json.loads(z.read("PACKAGE-MANIFEST.json")).get("schema")
- except Exception: current_schema = None
- if current_schema == "prod2u-dual-current-manifest-v1":
- return _dual_overlay(args.base_zip, args.current_zip, args.output_dir)
- from tools.overlay_6400_packages import run
- run(args.base_zip, args.current_zip, args.output_dir)
- return args.output_dir
- raise SystemExit("unsupported legacy action")
- def main(argv=None) -> int:
- ap=argparse.ArgumentParser(description=__doc__); sp=ap.add_subparsers(dest="action",required=True)
- for name in ("base","current","all"):
- p=sp.add_parser(name); p.add_argument("--output-dir",type=Path,default=ROOT/"dist")
- if name=="current": p.add_argument("--base-zip",type=Path,required=True)
- p=sp.add_parser("verify"); p.add_argument("package",type=Path)
- p=sp.add_parser("overlay"); p.add_argument("--base-zip",type=Path,required=True); p.add_argument("--current-zip",type=Path,required=True); p.add_argument("--output-dir",type=Path,required=True)
- p=sp.add_parser("delivery"); p.add_argument("--product",choices=("6400-v1.1","mrdimm-v1.2"),required=True); p.add_argument("--output-dir",type=Path,default=ROOT/"dist"); p.add_argument("--td-receipt",type=Path); p.add_argument("--gui-exe",type=Path); p.add_argument("--gui-zip",type=Path); p.add_argument("--status-json",type=Path)
- a=ap.parse_args(argv)
- if a.action=="verify": print(json.dumps(verify(a.package),indent=2)); return 0
- if a.action == "all":
- base = dispatch_legacy(argparse.Namespace(action="base", output_dir=a.output_dir))
- current = dispatch_legacy(argparse.Namespace(action="current", output_dir=a.output_dir, base_zip=base))
- print(json.dumps({"status":"PASS","base":verify(base),"current":verify(current)}, indent=2))
- return 0
- if a.action in ("base","current","overlay"):
- result=dispatch_legacy(a)
- if a.action == "overlay":
- receipt = result / "OVERLAY-RECEIPT.json"
- payload = json.loads(receipt.read_text(encoding="utf-8")) if receipt.is_file() else {"status":"PASS"}
- print(json.dumps({**payload, "action": a.action, "output_dir": str(result.resolve())}, indent=2))
- else:
- print(json.dumps({**verify(result),"action":a.action},indent=2))
- return 0
- if a.action=="delivery":
- if a.product=="6400-v1.1":
- if not all((a.td_receipt,a.gui_exe,a.gui_zip,a.status_json)): ap.error("6400 delivery requires --td-receipt --gui-exe --gui-zip --status-json")
- from tools.package_target import package_6400_canonical
- result=package_6400_canonical.package_delivery(a.output_dir,a.td_receipt,a.gui_exe,a.gui_zip,a.status_json)
- else:
- required=(a.td_receipt,a.gui_exe,a.gui_zip)
- if not all(required): ap.error("mrdimm delivery requires --td-receipt --gui-exe --gui-zip")
- a.output_dir.mkdir(parents=True,exist_ok=True); commit="unknown"; receipt=json.loads(a.td_receipt.read_text(encoding="utf-8")); commit=str(receipt.get("commit",commit))
- # TD receipts retain the Linux artifact path. Resolve the copied
- # bitstream beside the receipt (the Windows fetch step preserves
- # this basename) so Delivery always contains the actual BIT.
- bit = None
- bit_meta = receipt.get("measurement_artifacts", {}).get("bitstream", {})
- bit_name = Path(str(bit_meta.get("path", ""))).name
- candidates = [a.td_receipt.parent / bit_name] if bit_name else []
- candidates += sorted(a.td_receipt.parent.glob("*.bit"))
- for candidate in candidates:
- if candidate.is_file(): bit = candidate; break
- if bit is None: ap.error("MRDIMM delivery requires fetched TD bitstream beside receipt")
- status = str(receipt.get("status", "unknown")).upper()
- candidate_status = {"status": "PASS" if status == "PASS" else "PARTIAL", "td_status": status, "timing_gate": receipt.get("timing_gate", {}), "structural_gate": receipt.get("structural_gate", {})}
- files = {
- "prod2u-mrdimm-v1.2.bit": bit.read_bytes(),
- "TD-RECEIPT.json": a.td_receipt.read_bytes(),
- a.gui_exe.name: a.gui_exe.read_bytes(),
- a.gui_zip.name: a.gui_zip.read_bytes(),
- "Wire-Contract.md": (ROOT/"projects/prod2u-door-temp/requirements.zh-CN.md").read_bytes(),
- "Snapshot-Contract.json": (ROOT/"src/generated/host-contract.json").read_bytes(),
- "CANDIDATE-STATUS.json": json.dumps(candidate_status,indent=2,sort_keys=True).encode()+b"\n",
- }
- manifest={"schema":"prod2u-delivery-v1","product":"mrdimm-chamber","board":"FCB V1.2","commit":commit,"status":"PASS" if status == "PASS" else "PARTIAL","hardware":"NOT RUN","members":sorted(files)}
- files["RELEASE-IDENTITY.json"] = (json.dumps(manifest,indent=2,sort_keys=True)+"\n").encode()
- files["SHA256SUMS"] = "".join(f"{hashlib.sha256(data).hexdigest()} {name}\n" for name,data in sorted(files.items())).encode()
- result=a.output_dir/f"Prod2U-MRDIMM-V1.2-Delivery-{commit[:8]}.zip"; _zip(result, files)
- print(json.dumps({**verify(result),"action":"delivery","product":a.product},indent=2)); return 0
- return 2
- if __name__=="__main__": raise SystemExit(main())
|