package_hth_review.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 os
  8. import subprocess
  9. import zipfile
  10. from datetime import datetime, timezone
  11. from pathlib import Path
  12. SKIP_DIR_NAMES = {
  13. ".git",
  14. ".venv-sdk",
  15. ".venv",
  16. "__pycache__",
  17. ".pytest_cache",
  18. ".mypy_cache",
  19. ".ruff_cache",
  20. "bin",
  21. "dist",
  22. "build",
  23. "artifacts",
  24. }
  25. SKIP_SUFFIXES = {".sock", ".pyc", ".pyo"}
  26. SKIP_NAME_SUBSTR = {".egg-info"}
  27. def zip_file_mode(path: Path) -> int:
  28. if path.suffix == ".sh" or path.name in {"hthd", "hthctl", "hth-capture", "install.sh"}:
  29. return 0o755
  30. if path.suffix == ".py":
  31. try:
  32. if path.read_bytes()[:2] == b"#!":
  33. return 0o755
  34. except OSError:
  35. pass
  36. return 0o644
  37. def write_zip_file(zf: zipfile.ZipFile, name: str, data: bytes, mode: int = 0o644) -> None:
  38. info = zipfile.ZipInfo(name.replace("\\", "/"))
  39. info.create_system = 3
  40. info.external_attr = (mode & 0o777) << 16
  41. zf.writestr(info, data)
  42. def should_skip(path: Path, host_root: Path) -> bool:
  43. rel = path.relative_to(host_root)
  44. for part in rel.parts:
  45. if part in SKIP_DIR_NAMES:
  46. return True
  47. if any(token in part for token in SKIP_NAME_SUBSTR):
  48. return True
  49. if path.suffix in SKIP_SUFFIXES:
  50. return True
  51. return False
  52. def _tools_text() -> str:
  53. lines = []
  54. for args in (
  55. ["go", "version"],
  56. ["protoc", "--version"],
  57. ["python3", "--version"],
  58. ["git", "--version"],
  59. ):
  60. try:
  61. out = subprocess.check_output(args, stderr=subprocess.STDOUT, text=True)
  62. lines.append(out.strip())
  63. except (subprocess.CalledProcessError, FileNotFoundError) as exc:
  64. lines.append(f"{args[0]}: {exc}")
  65. return "\n".join(lines) + "\n"
  66. def snapshot_evidence(repo: Path, host_root: Path) -> dict[str, bytes]:
  67. mapping = {
  68. "evidence/host-contract.json": repo / "src" / "generated" / "host-contract.json",
  69. "evidence/golden-vectors.json": repo / "src" / "generated" / "golden-vectors.json",
  70. "evidence/prod2u-door-temp-protocol.zh-CN.md": repo / "docs" / "prod2u-door-temp-protocol.zh-CN.md",
  71. "evidence/project.json": repo / "projects" / "prod2u-door-temp" / "project.json",
  72. "evidence/profile.json": host_root / "profiles" / "prod2u-door-temp" / "profile.json",
  73. "evidence/hth.proto": host_root / "api" / "proto" / "hth" / "api" / "v1" / "hth.proto",
  74. }
  75. out: dict[str, bytes] = {}
  76. sha_lines = []
  77. for name, path in mapping.items():
  78. if not path.is_file():
  79. continue
  80. data = path.read_bytes()
  81. out[name] = data
  82. sha_lines.append(f"{hashlib.sha256(data).hexdigest()} {name}")
  83. out["evidence/SHA256SUMS"] = ("\n".join(sha_lines) + "\n").encode("utf-8")
  84. return out
  85. def git_info(repo: Path) -> tuple[str, str, str]:
  86. def run(args: list[str]) -> str:
  87. try:
  88. out = subprocess.check_output(args, cwd=repo, stderr=subprocess.DEVNULL, text=True)
  89. return out.strip()
  90. except (subprocess.CalledProcessError, FileNotFoundError):
  91. return ""
  92. if not (repo / ".git").exists() and run(["git", "rev-parse", "--is-inside-work-tree"]) != "true":
  93. return "unknown", "unknown", "n/a (not a git checkout or git unavailable)"
  94. head = run(["git", "rev-parse", "HEAD"]) or "unknown"
  95. short = run(["git", "rev-parse", "--short", "HEAD"]) or "unknown"
  96. stat_txt = run(["git", "diff", "--stat"]) or "clean or unavailable"
  97. return head, short, stat_txt[-2000:]
  98. def main() -> int:
  99. host_root = Path(__file__).resolve().parents[1]
  100. repo_root = host_root.parent
  101. stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  102. head, short, diffstat = git_info(repo_root)
  103. out = Path(f"/tmp/hth-platform-safety-closure-r3-{short}-{stamp}.zip")
  104. files: list[Path] = []
  105. for dirpath, dirnames, filenames in os.walk(host_root):
  106. pdir = Path(dirpath)
  107. 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)]
  108. for name in filenames:
  109. path = pdir / name
  110. if should_skip(path, host_root):
  111. continue
  112. files.append(path)
  113. files.sort()
  114. readme = f"""# hth platform safety closure r3
  115. Generated: {stamp} UTC
  116. Git HEAD: {head}
  117. Short: {short}
  118. Run dir: {os.environ.get("HTH_RUN_DIR", "(none)")}
  119. ## Honesty
  120. Software safety acceptance: BLOCKED
  121. Hardware validation: NOT RUN
  122. Real actuator validation: NOT RUN
  123. Architecture direction: PASS
  124. Ready for controlled hardware validation: NO
  125. Protocol: percent-close doors 0..100, GET_MOTOR_STATUS exists, NO ACK,
  126. watchdog 30s fed only by SET_ALL after startup, GET_TEMP dropped during startup.
  127. Door 0 is FULL OPEN not STOP.
  128. ## Layout
  129. - `host/` — daemon, proto, Python SDK, docs, deploy, reviews
  130. - `run/` — this-run logs only (not superseded evidence)
  131. - `MANIFEST` / `SHA256SUMS`
  132. ## Self-verify
  133. From the unzipped `hth-platform/` directory:
  134. ```
  135. python3 host/tools/verify_review_package.py .
  136. python3 host/tools/l0_contract_check.py --repo-root . --evidence-root evidence
  137. python3 host/tools/protocol_oracle.py --golden evidence/golden-vectors.json --min-positive 8 --min-negative 2 --min-frames 6
  138. ```
  139. `--repo-root` must be the directory that contains `host/` (this unzipped `hth-platform/` tree).
  140. """
  141. manifest_lines = []
  142. sha_lines = []
  143. extras: dict[str, bytes] = {
  144. "hth-platform/GIT_HEAD": (head + "\n").encode("utf-8"),
  145. "hth-platform/GIT_DIFFSTAT.txt": (diffstat + "\n").encode("utf-8"),
  146. "hth-platform/TOOLS.txt": _tools_text().encode("utf-8"),
  147. "hth-platform/README_FOR_REVIEW.md": readme.encode("utf-8"),
  148. }
  149. for name, data in snapshot_evidence(repo_root, host_root).items():
  150. extras["hth-platform/" + name] = data
  151. aliases = {
  152. "evidence/host-contract.json": "src/generated/host-contract.json",
  153. "evidence/golden-vectors.json": "src/generated/golden-vectors.json",
  154. "evidence/project.json": "projects/prod2u-door-temp/project.json",
  155. "evidence/prod2u-door-temp-protocol.zh-CN.md": "docs/prod2u-door-temp-protocol.zh-CN.md",
  156. }
  157. if name in aliases:
  158. extras["hth-platform/" + aliases[name]] = data
  159. run_dir = os.environ.get("HTH_RUN_DIR", "").strip()
  160. if run_dir:
  161. rd = Path(run_dir)
  162. if rd.is_dir():
  163. for p in sorted(rd.iterdir()):
  164. if not p.is_file() or p.stat().st_size >= 32 * 1024 * 1024:
  165. continue
  166. name_u = p.name.upper()
  167. if "SUPERSEDED" in name_u or "NOT_FINAL" in name_u:
  168. continue
  169. extras["hth-platform/run/" + p.name] = p.read_bytes()
  170. # Do not copy superseded /tmp/hth-gotest.log or other-run artifacts.
  171. with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED) as zf:
  172. for path in files:
  173. rel = Path("hth-platform") / "host" / path.relative_to(host_root)
  174. data = path.read_bytes()
  175. write_zip_file(zf, str(rel), data, zip_file_mode(path))
  176. key = str(rel.relative_to("hth-platform")).replace("\\", "/")
  177. manifest_lines.append(key)
  178. sha_lines.append(f"{hashlib.sha256(data).hexdigest()} {key}")
  179. for name, data in extras.items():
  180. write_zip_file(zf, name, data, 0o644)
  181. key = name[len("hth-platform/") :]
  182. manifest_lines.append(key)
  183. sha_lines.append(f"{hashlib.sha256(data).hexdigest()} {key}")
  184. write_zip_file(zf, "hth-platform/MANIFEST", ("\n".join(manifest_lines) + "\n").encode("utf-8"), 0o644)
  185. write_zip_file(zf, "hth-platform/SHA256SUMS", ("\n".join(sha_lines) + "\n").encode("utf-8"), 0o644)
  186. digest = hashlib.sha256(out.read_bytes()).hexdigest()
  187. print(f"zip={out}")
  188. print(f"bytes={out.stat().st_size}")
  189. print(f"sha256={digest}")
  190. print("top=hth-platform/")
  191. return 0
  192. if __name__ == "__main__":
  193. raise SystemExit(main())