#!/usr/bin/env python3 """Safely verify and overlay canonical 6400 Base + Current packages.""" from __future__ import annotations import argparse import json import shutil import subprocess import sys import tempfile from pathlib import Path from tools.package_6400_canonical import base_metadata, extract_safe, sha_file, verify_zip def run(base: Path, current: Path, output: Path) -> dict[str, object]: verify_zip(base) verify_zip(current) base_id, _manifest, base_manifest_sha = base_metadata(base) with tempfile.TemporaryDirectory() as tmp: inspect = Path(tmp) extract_safe(current, inspect) required = json.loads((inspect / "BASE-REQUIRED.json").read_text()) if required.get("base_id") != base_id: raise SystemExit("BASE_ID_MISMATCH") if required.get("base_zip_sha256") != sha_file(base): raise SystemExit("BASE_ZIP_SHA_MISMATCH") if required.get("base_manifest_sha256") != base_manifest_sha: raise SystemExit("BASE_MANIFEST_SHA_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, output) with tempfile.TemporaryDirectory() as tmp: current_root = Path(tmp) extract_safe(current, current_root) deletions = json.loads((current_root / "OVERLAY-DELETIONS.json").read_text())["paths"] for relative in deletions: victim = output / relative resolved = victim.resolve() if output.resolve() not in resolved.parents: raise SystemExit("UNSAFE_OVERLAY_DELETION") if victim.is_dir(): shutil.rmtree(victim) elif victim.exists(): victim.unlink() shutil.copytree(current_root, output, dirs_exist_ok=True) checks = [ [sys.executable, "PACKAGE-SELF-CHECK.py"], [sys.executable, "tools/check_6400_closures.py"], [sys.executable, "tools/generate_6400_manual.py", "--check"], ] results = [] for command in checks: completed = subprocess.run(command, cwd=output, text=True, capture_output=True) results.append({"command": command, "exit_code": completed.returncode, "stdout": completed.stdout[-2000:], "stderr": completed.stderr[-2000:]}) if completed.returncode: raise SystemExit(f"OVERLAY_REPLAY_FAILED: {command}") receipt = {"schema": "prod2u-6400-overlay-receipt-v1", "status": "PASS", "base_id": base_id, "base_zip_sha256": sha_file(base), "current_zip_sha256": sha_file(current), "checks": results} (output / "OVERLAY-RECEIPT.json").write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n") return receipt def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--base", type=Path, required=True) parser.add_argument("--current", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() run(args.base.resolve(), args.current.resolve(), args.output.resolve()) return 0 if __name__ == "__main__": raise SystemExit(main())