#!/usr/bin/env python3 """Draft packager: zip host/ (no .git, venv, caches) to /tmp/hth-platform-review-*.zip. Parent may run this later. Works without the `zip` / `rsync` binaries. """ from __future__ import annotations import hashlib import json import os import subprocess import zipfile from datetime import datetime, timezone from pathlib import Path SKIP_DIR_NAMES = { ".git", ".venv-sdk", ".venv", "__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", "bin", "dist", "build", "artifacts", } SKIP_SUFFIXES = {".sock", ".pyc", ".pyo"} SKIP_NAME_SUBSTR = {".egg-info"} def zip_file_mode(path: Path) -> int: name = path.name if path.suffix == ".sh" or name in {"hthd", "hthctl", "hth-capture", "install.sh", "uninstall.sh"}: return 0o755 if path.suffix == ".py": try: if path.read_bytes()[:2] == b"#!": return 0o755 except OSError: pass if path.suffix in {".yaml", ".yml"} and ("example" in name or name in {"hthd.yaml"}): return 0o640 return 0o644 _ZIP_DATE = (2026, 1, 1, 0, 0, 0) def write_zip_file(zf: zipfile.ZipFile, name: str, data: bytes, mode: int = 0o644) -> None: info = zipfile.ZipInfo(name.replace("\\", "/")) info.create_system = 3 info.date_time = _ZIP_DATE info.external_attr = (mode & 0o777) << 16 info.compress_type = zipfile.ZIP_DEFLATED zf.writestr(info, data) def should_skip(path: Path, host_root: Path) -> bool: rel = path.relative_to(host_root) for part in rel.parts: if part in SKIP_DIR_NAMES: return True if any(token in part for token in SKIP_NAME_SUBSTR): return True if path.suffix in SKIP_SUFFIXES: return True return False def _tools_text() -> str: lines = [] for args in ( ["go", "version"], ["protoc", "--version"], ["python3", "--version"], ["git", "--version"], ): try: out = subprocess.check_output(args, stderr=subprocess.STDOUT, text=True) lines.append(out.strip()) except (subprocess.CalledProcessError, FileNotFoundError) as exc: lines.append(f"{args[0]}: {exc}") return "\n".join(lines) + "\n" def snapshot_evidence(repo: Path, host_root: Path) -> dict[str, bytes]: mapping = { "evidence/host-contract.json": repo / "src" / "generated" / "host-contract.json", "evidence/golden-vectors.json": repo / "src" / "generated" / "golden-vectors.json", "evidence/prod2u-door-temp-protocol.zh-CN.md": repo / "docs" / "prod2u-door-temp-protocol.zh-CN.md", "evidence/project.json": repo / "projects" / "prod2u-door-temp" / "project.json", "evidence/profile.json": host_root / "profiles" / "prod2u-door-temp" / "profile.json", "evidence/hth.proto": host_root / "api" / "proto" / "hth" / "api" / "v1" / "hth.proto", } out: dict[str, bytes] = {} sha_lines = [] for name, path in mapping.items(): if not path.is_file(): continue data = path.read_bytes() out[name] = data sha_lines.append(f"{hashlib.sha256(data).hexdigest()} {name}") out["evidence/SHA256SUMS"] = ("\n".join(sha_lines) + "\n").encode("utf-8") return out def git_info(repo: Path) -> tuple[str, str, str]: def run(args: list[str]) -> str: try: out = subprocess.check_output(args, cwd=repo, stderr=subprocess.DEVNULL, text=True) return out.strip() except (subprocess.CalledProcessError, FileNotFoundError): return "" if not (repo / ".git").exists() and run(["git", "rev-parse", "--is-inside-work-tree"]) != "true": return "unknown", "unknown", "n/a (not a git checkout or git unavailable)" head = run(["git", "rev-parse", "HEAD"]) or "unknown" short = run(["git", "rev-parse", "--short", "HEAD"]) or "unknown" stat_txt = run(["git", "diff", "--stat"]) or "clean or unavailable" return head, short, stat_txt[-2000:] def main() -> int: import time global _ZIP_DATE host_root = Path(__file__).resolve().parents[1] repo_root = host_root.parent stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") head, short, diffstat = git_info(repo_root) run_id = os.environ.get("HTH_RUN_ID") or stamp epoch = os.environ.get("SOURCE_DATE_EPOCH") if not epoch: try: epoch = subprocess.check_output( ["git", "log", "-1", "--format=%ct"], cwd=repo_root, text=True ).strip() except (subprocess.CalledProcessError, FileNotFoundError): epoch = "1764000000" _ZIP_DATE = time.gmtime(int(epoch))[:6] out = Path(f"/tmp/hth-platform-safety-closure-r5-{short}-{run_id}.zip") root_name = "hth-platform-r5" files: list[Path] = [] for dirpath, dirnames, filenames in os.walk(host_root): pdir = Path(dirpath) dirnames[:] = [d for d in dirnames if d not in SKIP_DIR_NAMES and not any(t in d for t in SKIP_NAME_SUBSTR)] for name in filenames: path = pdir / name if should_skip(path, host_root): continue files.append(path) files.sort() files = [p for p in files if "reviews/superseded" not in str(p).replace("\\", "/")] readme = f"""# hth platform safety closure r5 Generated: {stamp} UTC Git HEAD: {head} Short: {short} Run ID: {run_id} ## Honesty Software simulation & integration acceptance: see run/run-manifest.json (Gate Evaluator, not hand-edited) Hardware validation: NOT RUN Real actuator validation: NOT RUN Release candidate readiness: NO unless 24h soak and controlled hardware PASS Production readiness: NO SAFE means the Host fully dispatched a Safe Frame and latched control mode. It does not mean the device acknowledged execution. Current UART has no ACK. ## Layout - `host/` daemon, proto, Python SDK, docs, deploy, reviews - `run/` this-run logs only - `reviews/` five current authority reports - `MANIFEST.json` / `MANIFEST` / `SHA256SUMS` ## Self-verify From the unzipped `{root_name}/` directory: ``` python3 host/tools/verify_review_package.py . --mode offline python3 host/tools/verify_review_package.py . --mode release ``` """ entries: list[tuple[str, bytes, int, str]] = [] extras: dict[str, tuple[bytes, int, str]] = { f"{root_name}/GIT_HEAD": ((head + "\n").encode("utf-8"), 0o644, "meta"), f"{root_name}/GIT_DIFFSTAT.txt": ((diffstat + "\n").encode("utf-8"), 0o644, "meta"), f"{root_name}/TOOLS.txt": (_tools_text().encode("utf-8"), 0o644, "meta"), f"{root_name}/README_FOR_REVIEW.md": (readme.encode("utf-8"), 0o644, "meta"), } ident = { "package": "hth-platform-safety-closure-r5", "git_commit": head, "git_short": short, "run_id": run_id, "source_date_epoch": int(epoch), } extras[f"{root_name}/PACKAGE_IDENTITY.json"] = (json.dumps(ident, indent=2).encode("utf-8") + b"\n", 0o644, "meta") for name, data in snapshot_evidence(repo_root, host_root).items(): extras[f"{root_name}/{name}"] = (data, 0o644, "evidence") aliases = { "evidence/host-contract.json": "src/generated/host-contract.json", "evidence/golden-vectors.json": "src/generated/golden-vectors.json", "evidence/project.json": "projects/prod2u-door-temp/project.json", "evidence/prod2u-door-temp-protocol.zh-CN.md": "docs/prod2u-door-temp-protocol.zh-CN.md", } if name in aliases: extras[f"{root_name}/{aliases[name]}"] = (data, 0o644, "evidence") run_dir = os.environ.get("HTH_RUN_DIR", "").strip() if run_dir: rd = Path(run_dir) if rd.is_dir(): for p in sorted(rd.iterdir()): if not p.is_file() or p.stat().st_size >= 32 * 1024 * 1024: continue name_u = p.name.upper() if "SUPERSEDED" in name_u or "NOT_FINAL" in name_u: continue extras[f"{root_name}/run/{p.name}"] = (p.read_bytes(), 0o644, "run") am = rd / "ACCEPTANCE_MATRIX.md" if am.is_file(): extras[f"{root_name}/ACCEPTANCE_MATRIX.md"] = (am.read_bytes(), 0o644, "run") for review in ( "01-scope-architecture.md", "02-protocol-action-truth.md", "03-safe-lifecycle-concurrency.md", "04-sdk-replay-deployment.md", "05-evidence-packaging-release.md", ): p = host_root / "reviews" / review if p.is_file(): extras[f"{root_name}/reviews/{review}"] = (p.read_bytes(), 0o644, "review") for tool in ( "verify_review_package.py", "l0_contract_check.py", "evaluate_gates.py", "gen_run_manifest.py", "write_toolchain_manifest.py", "protocol_oracle.py", ): p = host_root / "tools" / tool if p.is_file(): extras[f"{root_name}/verify/{tool}"] = (p.read_bytes(), zip_file_mode(p), "verify") with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf: manifest_lines = [] sha_lines = [] man_json = [] members: list[tuple[str, bytes, int, str]] = [] for path in files: rel = Path(root_name) / "host" / path.relative_to(host_root) members.append((str(rel).replace("\\", "/"), path.read_bytes(), zip_file_mode(path), "host")) for name, (data, mode, klass) in extras.items(): members.append((name.replace("\\", "/"), data, mode, klass)) members.sort(key=lambda m: m[0]) for name, data, mode, klass in members: write_zip_file(zf, name, data, mode) key = name[len(root_name) + 1 :] manifest_lines.append(key) digest = hashlib.sha256(data).hexdigest() sha_lines.append(f"{digest} {key}") man_json.append({"path": key, "size": len(data), "mode": f"{mode:04o}", "sha256": digest, "source_class": klass}) write_zip_file(zf, f"{root_name}/MANIFEST", ("\n".join(manifest_lines) + "\n").encode("utf-8"), 0o644) write_zip_file(zf, f"{root_name}/SHA256SUMS", ("\n".join(sha_lines) + "\n").encode("utf-8"), 0o644) write_zip_file(zf, f"{root_name}/MANIFEST.json", json.dumps(man_json, indent=2).encode("utf-8") + b"\n", 0o644) digest = hashlib.sha256(out.read_bytes()).hexdigest() print(f"zip={out}") print(f"bytes={out.stat().st_size}") print(f"sha256={digest}") print(f"top={root_name}/") return 0 if __name__ == "__main__": raise SystemExit(main())