"""Build a local replacement for QA-FAST-001@2026-12-01.1 from its verified release bundle.""" import argparse import hashlib import io import json import re import zipfile from datetime import datetime, timezone from pathlib import Path TEMPLATE = "QA-FAST-001" OLD_VERSION = "2026-12-01.1" OLD_BUNDLE_SHA = "2e276b3d336f0e049739348fd5dc7150c40cb1d5d139a7f0e9c035805f9a9db3" PAGES = { "detail": [("S01", "D01"), ("S02", "D02")], "main_images": [("M01", "M01")], "sku_images": [("K01", "K01")], } def fingerprint(data): return {"size": len(data), "sha256": hashlib.sha256(data).hexdigest()} def json_bytes(value): return (json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode("utf-8") def require(condition, message): if not condition: raise ValueError(message) def repair_component(manifest, files, payload, component, pages): binding = manifest["bindings"][component] mapping_path, inventory_path = binding["mapping"], binding["inventory"] require(files[mapping_path]["type"] == "mapping" and files[inventory_path]["type"] == "inventory", component) mapping, inventory = (json.loads(payload[path]) for path in (mapping_path, inventory_path)) require(all(x["template_id"] == TEMPLATE and x["component"] == component for x in (mapping, inventory)), f"{component}: template or component mismatch") require(mapping["mapping_version"] == "20261201.1" and "mapping_version" not in inventory, f"{component}: unexpected mapping versions") require([(screen["screen_id"], screen["asset_id"]) for screen in mapping["screens"]] == pages, f"{component}: unexpected pages") sources = mapping["ps_assets"] require(sources == inventory["ps_assets"] and [source["asset_id"] for source in sources] == [item[1] for item in pages], f"{component}: original references disagree") originals = {asset["path"]: asset for asset in manifest["assets"] if asset["type"] == "original" and asset["component"] == component} require(set(originals) == {source["ps_asset_path"] for source in sources}, f"{component}: originals missing") for source, (page, asset_id) in zip(sources, pages): path = source["ps_asset_path"] if len(pages) == 1: require(binding["original"] == path, f"{component}: original binding mismatch") else: require(binding["pages"][page] == {"original": path, "assetId": asset_id}, f"{page}: original binding mismatch") require((originals[path]["sha256"], originals[path]["size"]) == (source["ps_sha256"], source["ps_size_bytes"]), f"{page}: original hash or size mismatch") fields = [field for field in mapping["fields"] if field["screen_id"] == page] require(len(fields) == 1 and fields[0]["type"] == "图片", f"{page}: expected one image slot") field = fields[0] location = field["ps_location"] require(field["asset_id"] == location["asset_id"] == asset_id and sum( row["asset_id"] == asset_id and row["id"] == location["layer_id"] and row["path"] == location["path"] for row in inventory["rows"] ) == 1, f"{page}: image layer binding mismatch") for document in (mapping, inventory): require("source" not in document, f"{component}: unexpected source metadata") document["source"] = {"assets": document["ps_assets"]} inventory["mapping_version"] = mapping["mapping_version"] for path, document in ((mapping_path, mapping), (inventory_path, inventory)): payload[path] = json_bytes(document) files[path].update(fingerprint(payload[path])) def repair(manifest, bundle, new_version): require((manifest["schemaVersion"], manifest["templateId"], manifest["version"], manifest["visibility"]) == (1, TEMPLATE, OLD_VERSION, "super_admin_only"), "Unexpected input release") require(new_version != OLD_VERSION and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]{0,79}", new_version), "Choose a new release version") require(manifest["bundle"] == fingerprint(bundle) and manifest["bundle"]["sha256"] == OLD_BUNDLE_SHA, "Input is not the verified QA release bundle") require(manifest["bindings"].keys() == PAGES.keys(), "Expected detail, main_images and sku_images") files = {item["path"]: item for item in manifest["files"]} with zipfile.ZipFile(io.BytesIO(bundle)) as archive: require(len(archive.namelist()) == len(files) and set(archive.namelist()) == set(files), "Bundle file list mismatch") payload = {name: archive.read(name) for name in files} for name, data in payload.items(): require(all(files[name][field] == value for field, value in fingerprint(data).items()), f"{name}: file hash or size mismatch") for component, pages in PAGES.items(): repair_component(manifest, files, payload, component, pages) intake_path = Path(__file__).resolve().parents[1] / "lib" / "desktop-client" / "test-preset-intake.json" config_path = manifest["productionConfig"] config = json.loads(payload[config_path]) require("intake" not in config and manifest.get("intake") is None, "Unexpected existing intake schema") manifest["intake"] = config["intake"] = json.loads(intake_path.read_bytes()) payload[config_path] = json_bytes(config) files[config_path].update(fingerprint(payload[config_path])) output = io.BytesIO() with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive: for name, data in payload.items(): archive.writestr(name, data) repaired_bundle = output.getvalue() manifest.pop("publishedAt", None) manifest.pop("bundlePath", None) manifest.update(version=new_version, knowledgeVersion=f"{TEMPLATE}@{new_version}", builtAt=datetime.now(timezone.utc).isoformat(), bundle=fingerprint(repaired_bundle)) return repaired_bundle def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--manifest", type=Path, required=True) parser.add_argument("--bundle", type=Path, required=True) parser.add_argument("--version", required=True, help="Unused knowledge release version, e.g. 2026-12-01.2") parser.add_argument("--output", type=Path, required=True, help="New local directory for manifest.json and bundle.zip") args = parser.parse_args() try: manifest = json.loads(args.manifest.read_bytes()) bundle = repair(manifest, args.bundle.read_bytes(), args.version) args.output.mkdir() (args.output / "bundle.zip").write_bytes(bundle) (args.output / "manifest.json").write_bytes(json_bytes(manifest)) except (OSError, ValueError, KeyError, zipfile.BadZipFile) as error: parser.exit(1, f"{error}\n") print(f"{manifest['knowledgeVersion']} | detail: S01,S02 | main_images: M01 | sku_images: K01") if __name__ == "__main__": main()