package_hth_review.py 12 KB

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