#!/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, re, shutil, stat, subprocess, 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 release_workspace(): from tools.source_identity import source_identity from tools.package_archive import check_overlay origin=source_identity(ROOT) if origin['clean'] is False:raise ValueError('delivery requires clean source') names=('cpld-temperature-control','hth-platform','engineering-manifests') if origin['source_kind']=='exported': check_overlay(ROOT) listed=json.loads((ROOT/'WORKSPACE-SNAPSHOT.json').read_text(encoding='utf-8'))['repos'] repos=[] for name in names: matches=[row for row in listed if row['name']==name] if len(matches)!=1:raise ValueError('workspace repository identity missing: '+name) repos.append(matches[0]) sdk=ROOT/'hth-platform' else: repos=[] for name in names: path=ROOT if name=='cpld-temperature-control' else ROOT.parent/name identity=source_identity(path) if not identity['clean']:raise ValueError('delivery workspace repository is dirty: '+name) repos.append({'name':name,'commit':identity['commit'],'tree':identity['tree'], 'path':'.' if name=='cpld-temperature-control' else name}) sdk=ROOT.parent/'hth-platform' for row in repos: if any(not re.fullmatch('[0-9a-f]{40}',str(row.get(k,''))) for k in ('commit','tree')): raise ValueError('invalid repository commit/tree: '+row['name']) return origin,repos,sdk def delivery_bit(receipt_path,receipt,explicit=None): expected=receipt.get('bitstream_sha256','') if not re.fullmatch('[0-9a-f]{64}',expected):raise ValueError('TD BIT identity missing') if explicit: candidates=[Path(explicit)] else: recorded=str(receipt.get('bitstream','')) name=PurePosixPath(recorded.replace('\\','/')).name candidates=[Path(recorded),receipt_path.parent/name,receipt_path.parent/'bitgen'/name] if name else [] for path in candidates: if path.is_file() and sha(path)==expected:return path.resolve() raise ValueError('actual BIT missing or different from TD receipt') def product_delivery(product,output,td_receipt,gui_exe,gui_zip=None,status_json=None,sdk_wheel=None,bitstream=None): from tools import package_archive as archive from tools import build_product_gui as gui td_receipt,gui_exe,output=Path(td_receipt),Path(gui_exe),Path(output) receipt=json.loads(td_receipt.read_text(encoding='utf-8')) if receipt.get('profile')!=product or receipt.get('status')!='PASS': raise ValueError('delivery requires a PASS TD receipt for this product') bit=delivery_bit(td_receipt,receipt,bitstream) expected=gui.prepare_identity(product,bit,td_receipt) metadata_path=gui_exe.parent/'gui-build-metadata.json' metadata=json.loads(metadata_path.read_text(encoding='utf-8')) keys=('product','profile','board','contract_sha256','bitstream_sha256','bitstream_source_commit', 'bitstream_source_tree','source_manifest_sha256','td_receipt_sha256') if any(metadata.get(key)!=expected[key] for key in keys): raise ValueError('GUI product/BIT/source/TD identity mismatch') if any(not re.fullmatch('[0-9a-f]{40}',str(metadata.get(key,''))) for key in ('commit','source_tree')): raise ValueError('GUI source commit/tree missing') inspected=gui.inspect_executable(gui_exe,metadata,gui.gui_assets(product,metadata_path)) validation_path=gui_exe.parent/'GUI-VALIDATION.json' validation=json.loads(validation_path.read_text(encoding='utf-8')) if (validation.get('exe_sha256')!=sha(gui_exe) or validation.get('self_test_exit')!=0 or any(validation.get(key)!=value for key,value in inspected.items())): raise ValueError('GUI actual bytes/embedded assets/Windows validation mismatch') if gui_zip: packed=archive.read_archive(gui_zip)['files'] if packed.get(gui_exe.name)!=gui_exe.read_bytes() or packed.get('gui-build-metadata.json')!=metadata_path.read_bytes(): raise ValueError('optional GUI archive does not contain the selected EXE and metadata') origin,repos,sdk=release_workspace() if origin['source_kind']=='git': tree=subprocess.check_output(['git','rev-parse',metadata['commit']+'^{tree}'],cwd=ROOT,text=True).strip() if tree!=metadata['source_tree']:raise ValueError('GUI Git tree mismatch') files={} def add(name,path): archive.safe_name(name) if name in files:raise ValueError('duplicate delivery member: '+name) files[name]=Path(path).read_bytes() add(bit.name,bit);add(gui_exe.name,gui_exe) add('TD-BUILD-RECEIPT.json',td_receipt);add('gui-build-metadata.json',metadata_path) add('GUI-VALIDATION.json',validation_path) if gui_zip:add(Path(gui_zip).name,gui_zip) generated=ROOT/'generated'/gui.PRODUCTS[product]['generated'] for path in sorted(generated.iterdir()): if path.suffix in ('.json','.md','.txt'):add('contracts/'+path.name,path) wire='contracts/6400-wire.yaml' if product=='6400-front-rear' else 'contracts/mrdimm-wire.yaml' requirements='docs/prod2u-6400-front-back-protocol.zh-CN.md' if product=='6400-front-rear' else 'projects/mrdimm-chamber/requirements.zh-CN.md' add('contracts/wire.yaml',ROOT/wire);add('contracts/requirements.zh-CN.md',ROOT/requirements) sdk_paths=['pyproject.toml','README.zh-CN.md'] # Include the source/examples invoked by the SDK guide, including existing # Go consumers. Keep repository-level verification orchestration outside it. for name in ('go.mod','golden-vectors.json','manual-uart-contract.json','host-i2c-register-map.json','send_uart_hex_debug.sh'): if (sdk/name).is_file():sdk_paths.append(name) for directory in ('python','cmd','internal','pkg','examples','tools'): for path in sorted((sdk/directory).rglob('*')): relative=path.relative_to(sdk).as_posix() if (path.is_file() and path.suffix in ('.py','.go','.c','.sh','.json') and '__pycache__' not in path.parts and relative!='tools/verify_consumers.py'): sdk_paths.append(relative) for name in sdk_paths:add('SDK/'+name,sdk/name) if sdk_wheel: with zipfile.ZipFile(sdk_wheel) as wheel: names=wheel.namelist() for name in names:archive.safe_name(name) if len({name.casefold() for name in names})!=len(names):raise ValueError('SDK wheel has duplicate members') for name in sdk_paths: installed=(name in ('python/hth_protocol.py','python/hth6400.py','python/prod2u_status.py') or name.startswith('python/prod2u_sdk/')) member=name.removeprefix('python/') if installed and (member not in names or wheel.read(member)!=(sdk/name).read_bytes()): raise ValueError('SDK wheel differs from current source: '+name) add(Path(sdk_wheel).name,sdk_wheel) if status_json:add('CANDIDATE-STATUS.json',status_json) else:files['CANDIDATE-STATUS.json']=archive.encode({'status':'QUICK_CANDIDATE_FULL_PENDING', 'td':'PASS','gui_windows_selftest':'PASS','scope':'verified BIT/GUI binding; Full acceptance is separate','hardware':'NOT_RUN'}) candidate=json.loads(files['CANDIDATE-STATUS.json']) identity={'schema':'prod2u-release-identity-v2','product':product,'board':gui.PRODUCTS[product]['board'], 'repos':repos,'packager_commit':origin['commit'],'packager_tree':origin['tree'], 'bitstream_source_commit':receipt['commit'],'bitstream_source_tree':receipt['tree'], 'source_manifest_sha256':expected['source_manifest_sha256'],'contract_sha256':expected['contract_sha256'], 'bitstream_sha256':sha(bit),'gui_sha256':sha(gui_exe),'gui_source_commit':metadata['commit'], 'gui_source_tree':metadata['source_tree'],'td_receipt_sha256':sha(td_receipt), 'gui_validation_sha256':sha(validation_path),'sdk_wheel_sha256':sha(sdk_wheel) if sdk_wheel else None, 'toolchain':receipt.get('tool'),'td_run_id':receipt.get('run_id'), 'candidate_status':candidate,'hardware':'NOT_RUN'} files['RELEASE-IDENTITY.json']=archive.encode(identity) files['PACKAGE-SELF-CHECK.py']=Path(archive.__file__).read_bytes() files['START-HERE.zh-CN.md']=( '# '+product+' '+identity['board']+' 交付候选\n\n' '运行 python PACKAGE-SELF-CHECK.py 核对完整性。BIT、实际 Windows GUI、合同和源码身份见 RELEASE-IDENTITY.json。\n' 'GUI 是离线工具,不自动访问硬件。SDK/README.zh-CN.md 说明安装和使用;可安装随附 wheel 或 SDK 源码。\n' 'CANDIDATE-STATUS.json 保留实际验证范围;字节完整性不是 Full 软件或真实硬件验收。\n' 'Hardware/COM/JTAG/真实I2C/BMC/风扇/PTC/电机验证均为 NOT_RUN。\n').encode() files['EXCLUSIONS.json']=archive.encode({'excluded':['licenses','credentials','raw board files','large logs','toolchain installers'], 'scope':'product artifacts, current contracts and installable SDK source'}) payload,modes=archive.finalize(files,{'schema':'prod2u-delivery-manifest-v2','profile':'delivery', 'product':product,'source_commit':origin['commit'],'source_tree':origin['tree'],'hardware':'NOT_RUN'}) label='6400' if product=='6400-front-rear' else 'MRDIMM-V1.2' path=output/f'Prod2U-{label}-Delivery-{receipt["commit"][:8]}.zip' archive.write_archive(path,payload,modes);archive.read_archive(path) return 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 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) p.add_argument('--bitstream',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 not all((a.td_receipt,a.gui_exe)):ap.error("delivery requires --td-receipt and --gui-exe") product={"6400-v1.1":"6400-front-rear","mrdimm-v1.2":"mrdimm-chamber"}[a.product] result=product_delivery(product,a.output_dir,a.td_receipt,a.gui_exe,a.gui_zip,a.status_json,a.sdk_wheel,a.bitstream) print(json.dumps({**verify(result),"action":"delivery","product":a.product},indent=2));return 0 return 2 if __name__=="__main__": raise SystemExit(main())