#!/usr/bin/env python3 """Historical Base/Current/Delivery package dispatcher. Kept for legacy compact/replay compatibility. Current v2.1 releases use tools/package_unified_analysis.py with explicit current product receipts. """ 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 in ('6400-front-rear', '6400-v2') else 'contracts/mrdimm-wire.yaml' requirements='docs/prod2u-6400-front-back-protocol.zh-CN.md' if product in ('6400-front-rear', '6400-v2') 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'] for name in ('README.zh-CN.md', 'README.md', 'go.mod', 'golden-vectors.json', 'manual-uart-contract.json', 'send_uart_hex_debug.sh'): if (sdk / name).is_file(): sdk_paths.append(name) for directory in ('src', 'python', 'cmd', 'internal', 'pkg', 'examples', 'tools'): if (sdk / directory).is_dir(): 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() metrics = receipt.get('metrics', {}) for rep in metrics.get('area_reports', []): p = Path(rep) if p.is_file(): add('reports/' + p.name, p) timing_rep = metrics.get('timing_report') if timing_rep and Path(timing_rep).is_file(): add('reports/' + Path(timing_rep).name, Path(timing_rep)) for st_info in receipt.get('stages', {}).values(): log_p = Path(st_info.get('log', '')) if log_p.is_file(): add('reports/' + log_p.name, log_p) from tools import exclusion_packager universe = exclusion_packager.scan_candidate_universe(ROOT) included_candidates = {} for rel_path, item in universe.items(): if rel_path in files or ('contracts/' + rel_path) in files or ('SDK/' + rel_path) in files: included_candidates[rel_path] = item rules = exclusion_packager.get_6400_v2_exclusion_rules('delivery') exclusions = [] for rel_path, item in sorted(universe.items()): if rel_path in included_candidates: continue matched = False for pred, type_str, reason_str in rules: if pred(rel_path, item): exclusions.append({ 'path': rel_path, 'type': type_str, 'reason': reason_str, 'size': item['size'], }) matched = True break if not matched: exclusions.append({ 'path': rel_path, 'type': 'source-internal', 'reason': 'Development source/artifact excluded from production delivery package', 'size': item['size'], }) assert len(included_candidates) + len(exclusions) == len(universe) assert set(included_candidates.keys()).isdisjoint({x['path'] for x in exclusions}) files['EXCLUSIONS.json'] = archive.encode({ 'schema': 'prod2u-package-exclusions-v2', 'scope': f'{product} delivery package', 'total_candidates': len(universe), 'included_count': len(included_candidates), 'excluded_count': len(exclusions), 'exclusions': exclusions, }) 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-V2.0' if product=='6400-v2' else ('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 workspace_recovery(output_dir: Path) -> Path: from tools import package_archive as archive from tools.source_identity import source_identity output = Path(output_dir) output.mkdir(parents=True, exist_ok=True) origin, repos, sdk = release_workspace() files = {} modes = {} def add(name: str, data: bytes, mode: int = 0o644): archive.safe_name(name) if name in files: raise ValueError(f"duplicate recovery member: {name}") files[name] = data modes[name] = mode for repo_info in repos: repo_name = repo_info['name'] repo_path = ROOT if repo_name == 'cpld-temperature-control' else ROOT.parent / repo_name tracked = subprocess.check_output(['git', 'ls-files', '-z'], cwd=repo_path).decode().split('\0') tracked = [x for x in tracked if x] for rel in tracked: p = repo_path / rel if p.is_file() and not p.is_symlink(): target = f"repos/{repo_name}/{rel}" content = p.read_bytes() m = stat.S_IMODE(p.stat().st_mode) if m not in (0o644, 0o755): m = 0o755 if content.startswith(b'#!') else 0o644 add(target, content, m) bundles_meta = {} with tempfile.TemporaryDirectory() as tmpdir: for repo_info in repos: repo_name = repo_info['name'] repo_path = ROOT if repo_name == 'cpld-temperature-control' else ROOT.parent / repo_name bundle_file = Path(tmpdir) / f"{repo_name}.bundle" subprocess.check_call(['git', 'bundle', 'create', str(bundle_file), '--all'], cwd=repo_path) bundle_bytes = bundle_file.read_bytes() add(f"bundles/{repo_name}.bundle", bundle_bytes, 0o644) bundles_meta[repo_name] = { 'bundle': f"bundles/{repo_name}.bundle", 'sha256': archive.digest(bundle_bytes), 'size': len(bundle_bytes), 'commit': repo_info['commit'], 'tree': repo_info['tree'] } runs_dir = Path("/data/prod2u/cpld-runs") r6400_receipt = runs_dir / "6400-front-rear-td-20260921T041456Z-fa83b719/td-receipt.json" r6400_bit = runs_dir / "6400-front-rear-td-20260921T041456Z-fa83b719/bitgen/prod2u_6400_front_back.bit" rmrdimm_receipt = runs_dir / "mrdimm-chamber-td-20260921T045235Z-e564a0be/td-receipt.json" rmrdimm_bit = runs_dir / "mrdimm-chamber-td-20260921T045235Z-e564a0be/bitgen/prod2u_mrdimm.bit" if r6400_receipt.is_file(): add("receipts/6400-td-receipt.json", r6400_receipt.read_bytes()) if r6400_bit.is_file(): add("bitstreams/prod2u_6400_front_back.bit", r6400_bit.read_bytes()) if rmrdimm_receipt.is_file(): add("receipts/mrdimm-td-receipt.json", rmrdimm_receipt.read_bytes()) if rmrdimm_bit.is_file(): add("bitstreams/prod2u_mrdimm.bit", rmrdimm_bit.read_bytes()) proto_spec = ROOT / "docs/prod2u-dual-product-protocol.zh-CN.md" if proto_spec.is_file(): add("docs/prod2u-dual-product-protocol.zh-CN.md", proto_spec.read_bytes()) restore_script = ( "#!/usr/bin/env python3\n" "'''Disaster recovery restore and offline verification script.'''\n" "import argparse, json, subprocess, sys\n" "from pathlib import Path\n" "\n" "ROOT = Path(__file__).resolve().parent\n" "\n" "def main():\n" " parser = argparse.ArgumentParser(description='Restore Prod2U repositories from bundles')\n" " parser.add_argument('--dest', type=Path, default=ROOT / 'restored_workspace')\n" " args = parser.parse_args()\n" " dest = args.dest\n" " dest.mkdir(parents=True, exist_ok=True)\n" " manifest = json.loads((ROOT / 'RECOVERY-MANIFEST.json').read_text(encoding='utf-8'))\n" " print(f'Restoring Prod2U Workspace from Recovery archive (ID: {manifest.get(\"content_id\")})...')\n" " for repo in manifest.get('repositories', []):\n" " name = repo['name']\n" " bundle = ROOT / repo['bundle']\n" " repo_dest = dest / name\n" " print(f'Restoring {name} from {bundle} to {repo_dest}...')\n" " if not repo_dest.exists():\n" " subprocess.check_call(['git', 'clone', str(bundle), str(repo_dest)])\n" " subprocess.check_call(['git', '-C', str(repo_dest), 'bundle', 'verify', str(bundle)])\n" " commit = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=repo_dest, text=True).strip()\n" " tree = subprocess.check_output(['git', 'rev-parse', 'HEAD^{tree}'], cwd=repo_dest, text=True).strip()\n" " print(f' {name} restored: commit={commit}, tree={tree}')\n" " if commit != repo['commit']:\n" " subprocess.check_call(['git', 'checkout', repo['commit']], cwd=repo_dest)\n" " print('\\nVerifying generator check in restored cpld-temperature-control...')\n" " subprocess.check_call([sys.executable, 'tools/fw_cli.py', 'generate', 'all', '--check'], cwd=dest / 'cpld-temperature-control')\n" " print('RECOVERY_VERIFY PASS')\n" " return 0\n" "\n" "if __name__ == '__main__':\n" " raise SystemExit(main())\n" ).encode('utf-8') add("RESTORE-SELF-TEST.py", restore_script, 0o755) content_basis = "".join(r['commit'] + r['tree'] for r in repos) content_id = archive.digest(content_basis.encode())[:12] rec_manifest = { 'schema': 'prod2u-workspace-recovery-v1', 'content_id': content_id, 'repositories': [ { 'name': r['name'], 'commit': r['commit'], 'tree': r['tree'], 'bundle': f"bundles/{r['name']}.bundle", 'bundle_sha256': bundles_meta[r['name']]['sha256'], 'source_dir': f"repos/{r['name']}" } for r in repos ], 'bitstreams': { '6400-front-rear': { 'sha256': '32fe7d5c237af85b5c6c5082e27be5f7cf56b3f6605c0d5e2777abcf88e20697', 'file': 'bitstreams/prod2u_6400_front_back.bit', 'receipt': 'receipts/6400-td-receipt.json' }, 'mrdimm-chamber': { 'sha256': '4b21ebd10a6e42b837a056b35240995b621b1cba061dad68cc8305079ea6d573', 'file': 'bitstreams/prod2u_mrdimm.bit', 'receipt': 'receipts/mrdimm-td-receipt.json' } }, 'toolchain_note': '源码可独立恢复,厂商工具另包。Anlogic TD 2026.1 SP2 (Build 6.2.2.200067) 经 /usr/local/bin/td2026 运行。' } files['RECOVERY-MANIFEST.json'] = archive.encode(rec_manifest) modes['RECOVERY-MANIFEST.json'] = 0o644 payload, final_modes = archive.finalize(files, { 'schema': 'prod2u-recovery-manifest-v1', 'profile': 'recovery', 'content_id': content_id, 'repos': repos }, modes) target = output / f"Prod2U-Workspace-Recovery-{content_id}.zip" archive.write_archive(target, payload, final_modes) archive.read_archive(target) return target 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","6400-v2"),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) p=sp.add_parser("recovery"); p.add_argument("--output-dir",type=Path,default=ROOT/"dist"/"recovery") 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","6400-v2":"6400-v2"}[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 if a.action=="recovery": result=workspace_recovery(a.output_dir) print(json.dumps({**verify(result),"action":"recovery"},indent=2));return 0 return 2 if __name__=="__main__": raise SystemExit(main())