package_hth_review.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. #!/usr/bin/env python3
  2. """Draft packager: zip host/ (no .git, venv, caches) to /tmp/hth-platform-review-*.zip.
  3. Parent may run this later. Works without the `zip` / `rsync` binaries.
  4. """
  5. from __future__ import annotations
  6. import hashlib
  7. import json
  8. import os
  9. import subprocess
  10. import zipfile
  11. from datetime import datetime, timezone
  12. from pathlib import Path
  13. SKIP_DIR_NAMES = {
  14. ".git",
  15. ".venv-sdk",
  16. ".venv",
  17. "__pycache__",
  18. ".pytest_cache",
  19. ".mypy_cache",
  20. ".ruff_cache",
  21. "bin",
  22. "dist",
  23. "build",
  24. "artifacts",
  25. }
  26. SKIP_SUFFIXES = {".sock", ".pyc", ".pyo"}
  27. SKIP_NAME_SUBSTR = {".egg-info"}
  28. def zip_file_mode(path: Path) -> int:
  29. name = path.name
  30. if path.suffix == ".sh" or name in {"hthd", "hthctl", "hth-capture", "install.sh", "uninstall.sh"}:
  31. return 0o755
  32. if path.suffix == ".py":
  33. try:
  34. if path.read_bytes()[:2] == b"#!":
  35. return 0o755
  36. except OSError:
  37. pass
  38. if path.suffix in {".yaml", ".yml"} and ("example" in name or name in {"hthd.yaml"}):
  39. return 0o640
  40. return 0o644
  41. _ZIP_DATE = (2026, 1, 1, 0, 0, 0)
  42. def write_zip_file(zf: zipfile.ZipFile, name: str, data: bytes, mode: int = 0o644) -> None:
  43. info = zipfile.ZipInfo(name.replace("\\", "/"))
  44. info.create_system = 3
  45. info.date_time = _ZIP_DATE
  46. info.external_attr = (mode & 0o777) << 16
  47. info.compress_type = zipfile.ZIP_DEFLATED
  48. zf.writestr(info, data)
  49. def should_skip(path: Path, host_root: Path) -> bool:
  50. rel = path.relative_to(host_root)
  51. for part in rel.parts:
  52. if part in SKIP_DIR_NAMES:
  53. return True
  54. if any(token in part for token in SKIP_NAME_SUBSTR):
  55. return True
  56. if path.suffix in SKIP_SUFFIXES:
  57. return True
  58. return False
  59. def _tools_text() -> str:
  60. lines = []
  61. for args in (
  62. ["go", "version"],
  63. ["protoc", "--version"],
  64. ["python3", "--version"],
  65. ["git", "--version"],
  66. ):
  67. try:
  68. out = subprocess.check_output(args, stderr=subprocess.STDOUT, text=True)
  69. lines.append(out.strip())
  70. except (subprocess.CalledProcessError, FileNotFoundError) as exc:
  71. lines.append(f"{args[0]}: {exc}")
  72. return "\n".join(lines) + "\n"
  73. def snapshot_evidence(repo: Path, host_root: Path) -> dict[str, bytes]:
  74. mapping = {
  75. "evidence/host-contract.json": repo / "src" / "generated" / "host-contract.json",
  76. "evidence/golden-vectors.json": repo / "src" / "generated" / "golden-vectors.json",
  77. "evidence/prod2u-door-temp-protocol.zh-CN.md": repo / "docs" / "prod2u-door-temp-protocol.zh-CN.md",
  78. "evidence/project.json": repo / "projects" / "prod2u-door-temp" / "project.json",
  79. "evidence/profile.json": host_root / "profiles" / "prod2u-door-temp" / "profile.json",
  80. "evidence/hth.proto": host_root / "api" / "proto" / "hth" / "api" / "v1" / "hth.proto",
  81. }
  82. out: dict[str, bytes] = {}
  83. sha_lines = []
  84. for name, path in mapping.items():
  85. if not path.is_file():
  86. continue
  87. data = path.read_bytes()
  88. out[name] = data
  89. sha_lines.append(f"{hashlib.sha256(data).hexdigest()} {name}")
  90. out["evidence/SHA256SUMS"] = ("\n".join(sha_lines) + "\n").encode("utf-8")
  91. return out
  92. def git_info(repo: Path) -> tuple[str, str, str]:
  93. def run(args: list[str]) -> str:
  94. try:
  95. out = subprocess.check_output(args, cwd=repo, stderr=subprocess.DEVNULL, text=True)
  96. return out.strip()
  97. except (subprocess.CalledProcessError, FileNotFoundError):
  98. return ""
  99. if not (repo / ".git").exists() and run(["git", "rev-parse", "--is-inside-work-tree"]) != "true":
  100. return "unknown", "unknown", "n/a (not a git checkout or git unavailable)"
  101. head = run(["git", "rev-parse", "HEAD"]) or "unknown"
  102. short = run(["git", "rev-parse", "--short", "HEAD"]) or "unknown"
  103. stat_txt = run(["git", "diff", "--stat"]) or "clean or unavailable"
  104. return head, short, stat_txt[-2000:]
  105. def main() -> int:
  106. import time
  107. global _ZIP_DATE
  108. host_root = Path(__file__).resolve().parents[1]
  109. repo_root = host_root.parent
  110. stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  111. head, short, diffstat = git_info(repo_root)
  112. run_id = os.environ.get("HTH_RUN_ID") or stamp
  113. epoch = os.environ.get("SOURCE_DATE_EPOCH")
  114. if not epoch:
  115. try:
  116. epoch = subprocess.check_output(
  117. ["git", "log", "-1", "--format=%ct"], cwd=repo_root, text=True
  118. ).strip()
  119. except (subprocess.CalledProcessError, FileNotFoundError):
  120. epoch = "1764000000"
  121. _ZIP_DATE = time.gmtime(int(epoch))[:6]
  122. out = Path(f"/tmp/hth-platform-safety-closure-r5-{short}-{run_id}.zip")
  123. root_name = "hth-platform-r5"
  124. files: list[Path] = []
  125. for dirpath, dirnames, filenames in os.walk(host_root):
  126. pdir = Path(dirpath)
  127. 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)]
  128. for name in filenames:
  129. path = pdir / name
  130. if should_skip(path, host_root):
  131. continue
  132. files.append(path)
  133. files.sort()
  134. files = [p for p in files if "reviews/superseded" not in str(p).replace("\\", "/")]
  135. readme = f"""# hth platform safety closure r5
  136. Generated: {stamp} UTC
  137. Git HEAD: {head}
  138. Short: {short}
  139. Run ID: {run_id}
  140. ## Honesty
  141. Software simulation & integration acceptance: see run/run-manifest.json (Gate Evaluator, not hand-edited)
  142. Hardware validation: NOT RUN
  143. Real actuator validation: NOT RUN
  144. Release candidate readiness: NO unless 24h soak and controlled hardware PASS
  145. Production readiness: NO
  146. SAFE means the Host fully dispatched a Safe Frame and latched control mode.
  147. It does not mean the device acknowledged execution. Current UART has no ACK.
  148. ## Layout
  149. - `host/` daemon, proto, Python SDK, docs, deploy, reviews
  150. - `run/` this-run logs only
  151. - `reviews/` five current authority reports
  152. - `MANIFEST.json` / `MANIFEST` / `SHA256SUMS`
  153. ## Self-verify
  154. From the unzipped `{root_name}/` directory:
  155. ```
  156. python3 host/tools/verify_review_package.py . --mode offline
  157. python3 host/tools/verify_review_package.py . --mode release
  158. ```
  159. """
  160. entries: list[tuple[str, bytes, int, str]] = []
  161. extras: dict[str, tuple[bytes, int, str]] = {
  162. f"{root_name}/GIT_HEAD": ((head + "\n").encode("utf-8"), 0o644, "meta"),
  163. f"{root_name}/GIT_DIFFSTAT.txt": ((diffstat + "\n").encode("utf-8"), 0o644, "meta"),
  164. f"{root_name}/TOOLS.txt": (_tools_text().encode("utf-8"), 0o644, "meta"),
  165. f"{root_name}/README_FOR_REVIEW.md": (readme.encode("utf-8"), 0o644, "meta"),
  166. }
  167. ident = {
  168. "package": "hth-platform-safety-closure-r5",
  169. "git_commit": head,
  170. "git_short": short,
  171. "run_id": run_id,
  172. "source_date_epoch": int(epoch),
  173. }
  174. extras[f"{root_name}/PACKAGE_IDENTITY.json"] = (json.dumps(ident, indent=2).encode("utf-8") + b"\n", 0o644, "meta")
  175. for name, data in snapshot_evidence(repo_root, host_root).items():
  176. extras[f"{root_name}/{name}"] = (data, 0o644, "evidence")
  177. aliases = {
  178. "evidence/host-contract.json": "src/generated/host-contract.json",
  179. "evidence/golden-vectors.json": "src/generated/golden-vectors.json",
  180. "evidence/project.json": "projects/prod2u-door-temp/project.json",
  181. "evidence/prod2u-door-temp-protocol.zh-CN.md": "docs/prod2u-door-temp-protocol.zh-CN.md",
  182. }
  183. if name in aliases:
  184. extras[f"{root_name}/{aliases[name]}"] = (data, 0o644, "evidence")
  185. run_dir = os.environ.get("HTH_RUN_DIR", "").strip()
  186. if run_dir:
  187. rd = Path(run_dir)
  188. if rd.is_dir():
  189. for p in sorted(rd.iterdir()):
  190. if not p.is_file() or p.stat().st_size >= 32 * 1024 * 1024:
  191. continue
  192. name_u = p.name.upper()
  193. if "SUPERSEDED" in name_u or "NOT_FINAL" in name_u:
  194. continue
  195. extras[f"{root_name}/run/{p.name}"] = (p.read_bytes(), 0o644, "run")
  196. am = rd / "ACCEPTANCE_MATRIX.md"
  197. if am.is_file():
  198. extras[f"{root_name}/ACCEPTANCE_MATRIX.md"] = (am.read_bytes(), 0o644, "run")
  199. for review in (
  200. "01-scope-architecture.md",
  201. "02-protocol-action-truth.md",
  202. "03-safe-lifecycle-concurrency.md",
  203. "04-sdk-replay-deployment.md",
  204. "05-evidence-packaging-release.md",
  205. ):
  206. p = host_root / "reviews" / review
  207. if p.is_file():
  208. extras[f"{root_name}/reviews/{review}"] = (p.read_bytes(), 0o644, "review")
  209. for tool in (
  210. "verify_review_package.py",
  211. "l0_contract_check.py",
  212. "evaluate_gates.py",
  213. "gen_run_manifest.py",
  214. "write_toolchain_manifest.py",
  215. "protocol_oracle.py",
  216. ):
  217. p = host_root / "tools" / tool
  218. if p.is_file():
  219. extras[f"{root_name}/verify/{tool}"] = (p.read_bytes(), zip_file_mode(p), "verify")
  220. with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
  221. manifest_lines = []
  222. sha_lines = []
  223. man_json = []
  224. members: list[tuple[str, bytes, int, str]] = []
  225. for path in files:
  226. rel = Path(root_name) / "host" / path.relative_to(host_root)
  227. members.append((str(rel).replace("\\", "/"), path.read_bytes(), zip_file_mode(path), "host"))
  228. for name, (data, mode, klass) in extras.items():
  229. members.append((name.replace("\\", "/"), data, mode, klass))
  230. members.sort(key=lambda m: m[0])
  231. for name, data, mode, klass in members:
  232. write_zip_file(zf, name, data, mode)
  233. key = name[len(root_name) + 1 :]
  234. manifest_lines.append(key)
  235. digest = hashlib.sha256(data).hexdigest()
  236. sha_lines.append(f"{digest} {key}")
  237. man_json.append({"path": key, "size": len(data), "mode": f"{mode:04o}", "sha256": digest, "source_class": klass})
  238. write_zip_file(zf, f"{root_name}/MANIFEST", ("\n".join(manifest_lines) + "\n").encode("utf-8"), 0o644)
  239. write_zip_file(zf, f"{root_name}/SHA256SUMS", ("\n".join(sha_lines) + "\n").encode("utf-8"), 0o644)
  240. write_zip_file(zf, f"{root_name}/MANIFEST.json", json.dumps(man_json, indent=2).encode("utf-8") + b"\n", 0o644)
  241. digest = hashlib.sha256(out.read_bytes()).hexdigest()
  242. print(f"zip={out}")
  243. print(f"bytes={out.stat().st_size}")
  244. print(f"sha256={digest}")
  245. print(f"top={root_name}/")
  246. return 0
  247. if __name__ == "__main__":
  248. raise SystemExit(main())