#!/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] sys.dont_write_bytecode=True 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: from tools.package_archive import write_archive return write_archive(path,files) def _dual_paths() -> list[str]: """Current CPLD replay closure; missing dependencies fail before ZIP creation.""" from tools.source_package_closure import current_cpld_paths return current_cpld_paths(ROOT) def _dual_current(output: Path, base_zip: Path) -> Path: from tools import package_archive as archive from tools.source_identity import source_identity from tools.source_package_closure import current_cpld_paths import subprocess base=archive.read_archive(base_zip);base_id,base_manifest_sha=archive.base_identity(base) origin=source_identity(ROOT) if origin['clean'] is False:raise ValueError('Current requires a clean source snapshot') base_sources={n:d for n,d in base['files'].items() if n not in archive.META} extras=[n for n in base_sources if (ROOT/n).is_file() and not n.startswith('src/legacy/')] wanted=current_cpld_paths(ROOT,extras) desired={n:(ROOT/n).read_bytes() for n in wanted} modes={n:archive.mode_for(n,d) for n,d in desired.items()} repos=[{'name':'cpld-temperature-control','commit':origin['commit'],'tree':origin['tree'],'path':'.'}] exclusions=[] for name in ('hth-platform','engineering-manifests'): repo=ROOT.parent/name if origin['source_kind']=='git' else ROOT/name if not repo.is_dir():raise ValueError('required workspace repository missing: '+str(repo)) if origin['source_kind']=='git': def git(*args):return subprocess.check_output(['git',*args],cwd=repo,text=True).strip() if git('status','--porcelain'):raise ValueError('workspace repository is dirty: '+name) identity={'name':name,'commit':git('rev-parse','HEAD'),'tree':git('rev-parse','HEAD^{tree}'),'path':name} paths=subprocess.check_output(['git','ls-files','-z'],cwd=repo).decode().split('\0') paths=[x for x in paths if x] else: workspace=json.loads((ROOT/'WORKSPACE-SNAPSHOT.json').read_text()) matches=[x for x in workspace['repos'] if x['name']==name] if len(matches)!=1:raise ValueError('exported repository identity missing: '+name) identity=matches[0] combined=json.loads((ROOT/'COMBINED-SOURCE-MANIFEST.json').read_text()) paths=[x['path'][len(name)+1:] for x in combined['items'] if x['path'].startswith(name+'/')] repos.append(identity) for relative in paths: if relative.startswith('legacy-hth/') or relative=='AGENTS.md': exclusions.append(name+'/'+relative);continue path=repo/relative if not path.is_file() or path.is_symlink():raise ValueError('workspace source missing or unsafe: '+str(path)) target=name+'/'+archive.safe_name(relative);desired[target]=path.read_bytes();modes[target]=archive.mode_for(target,desired[target]) if origin['source_kind']=='exported': exclusions=json.loads((ROOT/'EXCLUSIONS.json').read_text(encoding='utf-8'))['excluded_paths'] exclusions=sorted(set(exclusions)) source_items=[{'path':n,'size':len(d),'sha256':archive.digest(d),'mode':modes[n]} for n,d in sorted(desired.items())] identity={'repos':repos,'base_id':base_id,'base_zip_sha256':base['sha256'],'base_manifest_sha256':base_manifest_sha, 'source_items':source_items,'excluded_paths':exclusions,'format':'dual-current-v2'} snapshot=archive.digest(json.dumps(identity,sort_keys=True,separators=(',',':')).encode())[:16] changed={n:d for n,d in desired.items() if n not in base_sources or base_sources[n]!=d or base['modes'][n]!=modes[n]} replacements=[{'path':n,'base_sha256':archive.digest(base_sources[n]),'current_sha256':archive.digest(d)} for n,d in sorted(changed.items()) if n in base_sources] additions=sorted(set(changed)-set(base_sources)) deletions=[{'path':n,'base_sha256':archive.digest(d)} for n,d in sorted(base_sources.items()) if n not in desired] payload=dict(changed) payload['BASE-REQUIRED.json']=archive.encode({'schema':'prod2u-base-required-v1','base_id':base_id, 'base_manifest_sha256':base_manifest_sha,'base_zip_sha256':base['sha256']}) payload['WORKSPACE-SNAPSHOT.json']=archive.encode({'schema':'prod2u-workspace-snapshot-v1','snapshot_id':snapshot,'repos':repos,'base_id':base_id}) payload['OVERLAY-REPLACEMENTS.json']=archive.encode({'schema':'prod2u-overlay-replacements-v1','replacements':replacements}) payload['OVERLAY-ADDITIONS.json']=archive.encode({'schema':'prod2u-overlay-additions-v1','additions':additions}) payload['OVERLAY-DELETIONS.json']=archive.encode({'schema':'prod2u-overlay-deletions-v1','deletions':deletions}) payload['COMBINED-SOURCE-MANIFEST.json']=archive.encode({'schema':'prod2u-combined-source-v1','items':source_items}) payload['EXCLUSIONS.json']=archive.encode({'scope':'current source replay','excluded_paths':exclusions, 'excluded_categories':['Git objects','toolchain binaries/licenses','build outputs','runtime caches','retired HTH implementation'], 'authority_note':'stale per-tool/per-repository agent instructions are not build dependencies'}) payload['START-HERE.zh-CN.md']=('# 双产品源码增量包\n\nCurrent 单独仅能验证归档完整性,自检退出码3表示需要指定 Base。\n' '使用 tools/package_prod2u.py overlay 叠加后运行根目录 PACKAGE-SELF-CHECK.py。\n' 'CPLD 文件位于根目录;HTH 和 engineering-manifests 位于同名子目录。\n' 'python3 tools/fw_cli.py generate all --check;python3 tools/fw_cli.py test all --run-root <外部新目录>。\n' 'HTH 可从 hth-platform/pyproject.toml 安装并运行其中的源码测试。\n' '本包为源码重放,不代表 Full 软件或真实硬件验收。\n').encode() payload['PACKAGE-SELF-CHECK.py']=Path(archive.__file__).read_bytes() payload_modes={n:modes.get(n,archive.mode_for(n,d)) for n,d in payload.items()} manifest={'schema':'prod2u-dual-current-manifest-v2','profile':'current','products':['6400-front-rear','mrdimm-chamber'], 'source_commit':origin['commit'],'source_tree':origin['tree'],'snapshot_id':snapshot,'base_id':base_id,'repos':repos} files,final_modes=archive.finalize(payload,manifest,payload_modes) target=output/f'Prod2U-CPLD-Analysis-Current-{snapshot}-base-{base_id}.zip' archive.write_archive(target,files,final_modes);archive.read_archive(target);return target def _dual_overlay(base_zip: Path, current_zip: Path, output: Path) -> Path: from tools.package_archive import overlay return overlay(base_zip,current_zip,output) def verify(path: Path) -> dict: from tools.package_archive import read_archive data=read_archive(path) return {'status':'PASS','scope':'archive integrity only','package':str(path.resolve()),'sha256':data['sha256']} 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 in ("prod2u-dual-current-manifest-v1","prod2u-dual-current-manifest-v2"): 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) p.add_argument('--sdk-wheel',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.status_json)): ap.error("6400 delivery requires --td-receipt --gui-exe --status-json") from tools 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,a.sdk_wheel) 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())