package_hth_review.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. #!/usr/bin/env python3
  2. """Package the standalone HTH repository under a compatibility ``host/`` prefix.
  3. 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 rel.parts and rel.parts[0] == "reviews":
  57. return True
  58. if path.name in {"ACCEPTANCE_MATRIX.md", "_r6_quick_test.sh"}:
  59. return True
  60. if path.suffix in SKIP_SUFFIXES:
  61. return True
  62. return False
  63. def _tools_text() -> str:
  64. lines = []
  65. for args in (
  66. ["go", "version"],
  67. ["protoc", "--version"],
  68. ["python3", "--version"],
  69. ["git", "--version"],
  70. ):
  71. try:
  72. out = subprocess.check_output(args, stderr=subprocess.STDOUT, text=True)
  73. lines.append(out.strip())
  74. except (subprocess.CalledProcessError, FileNotFoundError) as exc:
  75. lines.append(f"{args[0]}: {exc}")
  76. return "\n".join(lines) + "\n"
  77. def snapshot_evidence(host_root: Path) -> dict[str, bytes]:
  78. mapping = {
  79. "evidence/host-contract.json": host_root / "contracts" / "evidence" / "host-contract.json",
  80. "evidence/golden-vectors.json": host_root / "contracts" / "evidence" / "golden-vectors.json",
  81. "evidence/legacy-RTL_REF.txt": host_root / "contracts" / "evidence" / "RTL_REF.txt",
  82. "evidence/legacy-SHA256SUMS": host_root / "contracts" / "evidence" / "SHA256SUMS",
  83. "evidence/6400-host-contract.json": host_root / "contracts" / "6400" / "host-contract.json",
  84. "evidence/6400-SHA256SUMS": host_root / "contracts" / "6400" / "SHA256SUMS",
  85. "evidence/profile.json": host_root / "profiles" / "prod2u-door-temp" / "profile.json",
  86. "evidence/hth.proto": host_root / "api" / "proto" / "hth" / "api" / "v1" / "hth.proto",
  87. }
  88. out: dict[str, bytes] = {}
  89. sha_lines = []
  90. for name, path in mapping.items():
  91. if not path.is_file():
  92. continue
  93. data = path.read_bytes()
  94. out[name] = data
  95. sha_lines.append(f"{hashlib.sha256(data).hexdigest()} {name}")
  96. out["evidence/SHA256SUMS"] = ("\n".join(sha_lines) + "\n").encode("utf-8")
  97. return out
  98. def git_info(repo: Path) -> tuple[str, str, str]:
  99. env_head = os.environ.get("HTH_GIT_COMMIT", "").strip()
  100. env_short = os.environ.get("HTH_GIT_SHORT", "").strip()
  101. def run(args: list[str]) -> str:
  102. try:
  103. out = subprocess.check_output(args, cwd=repo, stderr=subprocess.DEVNULL, text=True)
  104. return out.strip()
  105. except (subprocess.CalledProcessError, FileNotFoundError):
  106. return ""
  107. if env_head:
  108. short = env_short or env_head[:12]
  109. return env_head, short, os.environ.get("HTH_GIT_DIFFSTAT", "clean (commit bound via HTH_GIT_COMMIT)")
  110. if not (repo / ".git").exists() and run(["git", "rev-parse", "--is-inside-work-tree"]) != "true":
  111. return "unknown", "unknown", "n/a (not a git checkout or git unavailable)"
  112. head = run(["git", "rev-parse", "HEAD"]) or "unknown"
  113. short = run(["git", "rev-parse", "--short", "HEAD"]) or "unknown"
  114. stat_txt = run(["git", "diff", "--stat"]) or "clean or unavailable"
  115. return head, short, stat_txt[-2000:]
  116. def main() -> int:
  117. import time
  118. global _ZIP_DATE
  119. host_root = Path(__file__).resolve().parents[1]
  120. repo_root = host_root
  121. stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  122. head, short, diffstat = git_info(repo_root)
  123. run_id = os.environ.get("HTH_RUN_ID") or stamp
  124. epoch = os.environ.get("SOURCE_DATE_EPOCH")
  125. if not epoch:
  126. try:
  127. epoch = subprocess.check_output(
  128. ["git", "log", "-1", "--format=%ct"], cwd=repo_root, text=True
  129. ).strip()
  130. except (subprocess.CalledProcessError, FileNotFoundError):
  131. epoch = "1764000000"
  132. _ZIP_DATE = time.gmtime(int(epoch))[:6]
  133. out_dir = Path(os.environ.get("HTH_PACKAGE_DIR") or "/tmp")
  134. out_dir.mkdir(parents=True, exist_ok=True)
  135. out = out_dir / f"hth-engineering-review-{short}-{run_id}.zip"
  136. root_name = "hth-platform-r6"
  137. files: list[Path] = []
  138. for dirpath, dirnames, filenames in os.walk(host_root):
  139. pdir = Path(dirpath)
  140. 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)]
  141. for name in filenames:
  142. path = pdir / name
  143. if should_skip(path, host_root):
  144. continue
  145. files.append(path)
  146. files.sort()
  147. files = [p for p in files if "reviews/superseded" not in str(p).replace("\\", "/")]
  148. readme = f"""# hth platform safety closure r6
  149. Generated: {stamp} UTC
  150. Git HEAD: {head}
  151. Short: {short}
  152. Run ID: {run_id}
  153. ## Honesty
  154. Software simulation & integration acceptance: see run/run-manifest.json (Gate Evaluator, not hand-edited)
  155. Hardware validation: NOT RUN
  156. Real actuator validation: NOT RUN
  157. Release candidate readiness: NO unless 24h soak and controlled hardware PASS
  158. Production readiness: NO
  159. SAFE means the Host fully dispatched a Safe Frame and latched control mode.
  160. It does not mean the device acknowledged execution. Current UART has no ACK.
  161. ## Layout
  162. - `host/` standalone HTH daemon, proto, Python SDK, docs, deploy, reviews
  163. - `run/` this-run logs only
  164. - `reviews/` five current authority reports
  165. - `MANIFEST.json` / `MANIFEST` / `SHA256SUMS`
  166. ## Self-verify
  167. From the unzipped `{root_name}/` directory:
  168. ```
  169. python3 host/tools/verify_review_package.py . --mode offline
  170. python3 host/tools/verify_review_package.py . --mode release
  171. ```
  172. """
  173. entries: list[tuple[str, bytes, int, str]] = []
  174. extras: dict[str, tuple[bytes, int, str]] = {
  175. f"{root_name}/GIT_HEAD": ((head + "\n").encode("utf-8"), 0o644, "meta"),
  176. f"{root_name}/GIT_DIFFSTAT.txt": ((diffstat + "\n").encode("utf-8"), 0o644, "meta"),
  177. f"{root_name}/TOOLS.txt": (_tools_text().encode("utf-8"), 0o644, "meta"),
  178. f"{root_name}/README_FOR_REVIEW.md": (readme.encode("utf-8"), 0o644, "meta"),
  179. }
  180. ident = {
  181. "package": "hth-platform-safety-closure-r6",
  182. "git_commit": head,
  183. "git_short": short,
  184. "run_id": run_id,
  185. "source_date_epoch": int(epoch),
  186. }
  187. extras[f"{root_name}/PACKAGE_IDENTITY.json"] = (json.dumps(ident, indent=2).encode("utf-8") + b"\n", 0o644, "meta")
  188. for name, data in snapshot_evidence(host_root).items():
  189. extras[f"{root_name}/{name}"] = (data, 0o644, "evidence")
  190. run_dir = os.environ.get("HTH_RUN_DIR", "").strip()
  191. if run_dir:
  192. rd = Path(run_dir)
  193. if rd.is_dir():
  194. for p in sorted(rd.iterdir()):
  195. if not p.is_file() or p.stat().st_size >= 32 * 1024 * 1024:
  196. continue
  197. name_u = p.name.upper()
  198. if "SUPERSEDED" in name_u or "NOT_FINAL" in name_u:
  199. continue
  200. extras[f"{root_name}/run/{p.name}"] = (p.read_bytes(), 0o644, "run")
  201. am = rd / "ACCEPTANCE_MATRIX.md"
  202. if am.is_file():
  203. extras[f"{root_name}/ACCEPTANCE_MATRIX.md"] = (am.read_bytes(), 0o644, "run")
  204. for review in (
  205. "01-scope-architecture.md",
  206. "02-watchdog-protocol-truth.md",
  207. "03-actor-action-lifecycle.md",
  208. "04-sdk-replay-deployment.md",
  209. "05-evidence-artifact-release.md",
  210. "algorithm-01-external-simplicity.md",
  211. "algorithm-02-facade-honesty.md",
  212. "algorithm-03-internal-automation.md",
  213. "algorithm-04-mock-replay.md",
  214. "algorithm-05-packages.md",
  215. ):
  216. p = host_root / "reviews" / review
  217. rd_rev = None
  218. if run_dir:
  219. cand = Path(run_dir) / "reviews" / review
  220. if cand.is_file():
  221. rd_rev = cand
  222. src = rd_rev if rd_rev is not None else p
  223. if src.is_file():
  224. extras[f"{root_name}/reviews/{review}"] = (src.read_bytes(), 0o644, "review")
  225. for tool in (
  226. "verify_review_package.py",
  227. "l0_contract_check.py",
  228. "evaluate_gates.py",
  229. "gen_run_manifest.py",
  230. "write_toolchain_manifest.py",
  231. "protocol_oracle.py",
  232. ):
  233. p = host_root / "tools" / tool
  234. if p.is_file():
  235. extras[f"{root_name}/verify/{tool}"] = (p.read_bytes(), zip_file_mode(p), "verify")
  236. with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
  237. manifest_lines = []
  238. sha_lines = []
  239. man_json = []
  240. members: list[tuple[str, bytes, int, str]] = []
  241. for path in files:
  242. rel = Path(root_name) / "host" / path.relative_to(host_root)
  243. members.append((str(rel).replace("\\", "/"), path.read_bytes(), zip_file_mode(path), "host"))
  244. for name, (data, mode, klass) in extras.items():
  245. members.append((name.replace("\\", "/"), data, mode, klass))
  246. members.sort(key=lambda m: m[0])
  247. for name, data, mode, klass in members:
  248. write_zip_file(zf, name, data, mode)
  249. key = name[len(root_name) + 1 :]
  250. manifest_lines.append(key)
  251. digest = hashlib.sha256(data).hexdigest()
  252. sha_lines.append(f"{digest} {key}")
  253. man_json.append({"path": key, "size": len(data), "mode": f"{mode:04o}", "sha256": digest, "source_class": klass})
  254. write_zip_file(zf, f"{root_name}/MANIFEST", ("\n".join(manifest_lines) + "\n").encode("utf-8"), 0o644)
  255. write_zip_file(zf, f"{root_name}/SHA256SUMS", ("\n".join(sha_lines) + "\n").encode("utf-8"), 0o644)
  256. write_zip_file(zf, f"{root_name}/MANIFEST.json", json.dumps(man_json, indent=2).encode("utf-8") + b"\n", 0o644)
  257. digest = hashlib.sha256(out.read_bytes()).hexdigest()
  258. sha_path = Path(str(out) + ".sha256")
  259. sha_path.write_text(f"{digest} {out.name}\n", encoding="utf-8")
  260. tree = ""
  261. try:
  262. tree = subprocess.check_output(["git", "rev-parse", "HEAD^{tree}"], cwd=repo_root, text=True).strip()
  263. except (subprocess.CalledProcessError, FileNotFoundError):
  264. tree = "unknown"
  265. att = {
  266. "filename": out.name,
  267. "bytes": out.stat().st_size,
  268. "sha256": digest,
  269. "git_commit": head,
  270. "git_tree": tree,
  271. "run_id": run_id,
  272. "source_date_epoch": int(epoch),
  273. "packager": "host/tools/package_hth_review.py",
  274. "packager_version": "r6",
  275. "release_gate_status": os.environ.get("HTH_RELEASE_GATE", "NOT RUN"),
  276. }
  277. man_json_bytes = json.dumps(man_json, indent=2).encode("utf-8") + b"\n"
  278. att["payload_manifest_sha256"] = hashlib.sha256(man_json_bytes).hexdigest()
  279. att_path = Path(str(out) + ".attestation.json")
  280. att_path.write_text(json.dumps(att, indent=2) + "\n", encoding="utf-8")
  281. print(f"zip={out}")
  282. print(f"bytes={out.stat().st_size}")
  283. print(f"sha256={digest}")
  284. print(f"sha256_sidecar={sha_path}")
  285. print(f"attestation={att_path}")
  286. print(f"top={root_name}/")
  287. return 0
  288. if __name__ == "__main__":
  289. raise SystemExit(main())