package_hth_review.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. PACKAGE_EXCLUDED_PREFIXES = {
  29. "contracts/evidence",
  30. "profiles/prod2u-door-temp",
  31. "profiles/6400-sim-debug",
  32. }
  33. PACKAGE_EXCLUDED_FILES = {
  34. "RELEASE.zh-CN.md",
  35. "REQUIREMENTS_TRACEABILITY.md",
  36. "docs/architecture.zh-CN.md",
  37. "docs/compatibility-policy.zh-CN.md",
  38. "docs/failure-semantics.zh-CN.md",
  39. "docs/known-gaps.zh-CN.md",
  40. "docs/protocol-source-audit.zh-CN.md",
  41. "docs/safety-contract.zh-CN.md",
  42. "docs/signal-dictionary.zh-CN.md",
  43. }
  44. def zip_file_mode(path: Path) -> int:
  45. name = path.name
  46. if path.suffix == ".sh" or name in {"hthd", "hthctl", "hth-capture", "install.sh", "uninstall.sh"}:
  47. return 0o755
  48. if path.suffix == ".py":
  49. try:
  50. if path.read_bytes()[:2] == b"#!":
  51. return 0o755
  52. except OSError:
  53. pass
  54. if path.suffix in {".yaml", ".yml"} and ("example" in name or name in {"hthd.yaml"}):
  55. return 0o640
  56. return 0o644
  57. _ZIP_DATE = (2026, 1, 1, 0, 0, 0)
  58. def write_zip_file(zf: zipfile.ZipFile, name: str, data: bytes, mode: int = 0o644) -> None:
  59. info = zipfile.ZipInfo(name.replace("\\", "/"))
  60. info.create_system = 3
  61. info.date_time = _ZIP_DATE
  62. info.external_attr = (mode & 0o777) << 16
  63. info.compress_type = zipfile.ZIP_DEFLATED
  64. zf.writestr(info, data)
  65. def should_skip(path: Path, host_root: Path) -> bool:
  66. rel = path.relative_to(host_root)
  67. rel_posix = rel.as_posix()
  68. if rel_posix in PACKAGE_EXCLUDED_FILES:
  69. return True
  70. if any(rel_posix == prefix or rel_posix.startswith(prefix + "/") for prefix in PACKAGE_EXCLUDED_PREFIXES):
  71. return True
  72. for part in rel.parts:
  73. if part in SKIP_DIR_NAMES:
  74. return True
  75. if any(token in part for token in SKIP_NAME_SUBSTR):
  76. return True
  77. if rel.parts and rel.parts[0] == "reviews":
  78. return True
  79. if path.name in {"ACCEPTANCE_MATRIX.md", "_r6_quick_test.sh"}:
  80. return True
  81. if path.suffix in SKIP_SUFFIXES:
  82. return True
  83. return False
  84. def _tools_text() -> str:
  85. lines = []
  86. for args in (
  87. ["go", "version"],
  88. ["protoc", "--version"],
  89. ["python3", "--version"],
  90. ["git", "--version"],
  91. ):
  92. try:
  93. out = subprocess.check_output(args, stderr=subprocess.STDOUT, text=True)
  94. lines.append(out.strip())
  95. except (subprocess.CalledProcessError, FileNotFoundError) as exc:
  96. lines.append(f"{args[0]}: {exc}")
  97. return "\n".join(lines) + "\n"
  98. def snapshot_evidence(host_root: Path) -> dict[str, bytes]:
  99. mapping = {
  100. "evidence/6400/host-contract.json": host_root / "contracts" / "6400" / "host-contract.json",
  101. "evidence/6400/SHA256SUMS": host_root / "contracts" / "6400" / "SHA256SUMS",
  102. "evidence/6400/import-source.json": host_root / "generated" / "6400" / "import-source.json",
  103. "evidence/6400/profiles/6400-control.json": host_root / "profiles" / "6400-control" / "profile.json",
  104. "evidence/6400/profiles/6400-identification.json": host_root / "profiles" / "6400-identification" / "profile.json",
  105. "evidence/hth.proto": host_root / "api" / "proto" / "hth" / "api" / "v1" / "hth.proto",
  106. }
  107. out: dict[str, bytes] = {}
  108. sha_lines = []
  109. for name, path in mapping.items():
  110. if not path.is_file():
  111. continue
  112. data = path.read_bytes()
  113. out[name] = data
  114. sha_lines.append(f"{hashlib.sha256(data).hexdigest()} {name}")
  115. out["evidence/SHA256SUMS"] = ("\n".join(sha_lines) + "\n").encode("utf-8")
  116. return out
  117. def review_readme(*, stamp: str, head: str, short: str, run_id: str) -> str:
  118. return f"""# HTH 6400 engineering review
  119. Generated: {stamp} UTC
  120. Git HEAD: {head}
  121. Short: {short}
  122. Run ID: {run_id}
  123. ## Active contract
  124. Product: `6400-front-rear-v1`
  125. Canonical release profiles: `6400-control`, `6400-identification`
  126. Every valid Host command returns an independent zero-payload ACK. `SET_TARGET`
  127. returns `0x81`; `GET_SNAPSHOT` returns `0x82` ACK followed by the distinct
  128. `0x42` Snapshot Data frame; Identification `SET_STIMULUS` returns `0x83`.
  129. An ACK proves atomic command or snapshot-bank commit, not thermal attainment.
  130. Production `6400-control` does not expose stimulus.
  131. The active wire contract, source binding, and canonical profiles are under
  132. `evidence/6400/`. Legacy door-controller profiles, evidence, reviews, and
  133. release notes are intentionally excluded from this 6400 review package.
  134. ## Evidence boundaries
  135. Software simulation & integration acceptance: see run/run-manifest.json (Gate Evaluator, not hand-edited)
  136. Hardware validation: NOT RUN
  137. Real actuator validation: NOT RUN
  138. Release candidate readiness: NO unless the applicable release gates and controlled hardware validation pass
  139. Production readiness: NO
  140. ## Layout
  141. - `host/` standalone HTH daemon, proto, Python SDK, 6400 docs, and deploy files
  142. - `evidence/6400/` imported contract, provenance, and canonical release profiles
  143. - `run/` this-run logs only
  144. - `reviews/6400-migration.md` active 6400 integration note
  145. - `MANIFEST.json` / `MANIFEST` / `SHA256SUMS`
  146. ## Self-verify
  147. From the unzipped `hth-platform-r6/` directory:
  148. ```
  149. python3 host/tools/verify_review_package.py . --mode offline
  150. python3 host/tools/verify_review_package.py . --mode release
  151. ```
  152. """
  153. def git_info(repo: Path) -> tuple[str, str, str]:
  154. env_head = os.environ.get("HTH_GIT_COMMIT", "").strip()
  155. env_short = os.environ.get("HTH_GIT_SHORT", "").strip()
  156. def run(args: list[str]) -> str:
  157. try:
  158. out = subprocess.check_output(args, cwd=repo, stderr=subprocess.DEVNULL, text=True)
  159. return out.strip()
  160. except (subprocess.CalledProcessError, FileNotFoundError):
  161. return ""
  162. if env_head:
  163. short = env_short or env_head[:12]
  164. return env_head, short, os.environ.get("HTH_GIT_DIFFSTAT", "clean (commit bound via HTH_GIT_COMMIT)")
  165. if not (repo / ".git").exists() and run(["git", "rev-parse", "--is-inside-work-tree"]) != "true":
  166. return "unknown", "unknown", "n/a (not a git checkout or git unavailable)"
  167. head = run(["git", "rev-parse", "HEAD"]) or "unknown"
  168. short = run(["git", "rev-parse", "--short", "HEAD"]) or "unknown"
  169. stat_txt = run(["git", "diff", "--stat"]) or "clean or unavailable"
  170. return head, short, stat_txt[-2000:]
  171. def main() -> int:
  172. import time
  173. global _ZIP_DATE
  174. host_root = Path(__file__).resolve().parents[1]
  175. repo_root = host_root
  176. stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  177. head, short, diffstat = git_info(repo_root)
  178. run_id = os.environ.get("HTH_RUN_ID") or stamp
  179. epoch = os.environ.get("SOURCE_DATE_EPOCH")
  180. if not epoch:
  181. try:
  182. epoch = subprocess.check_output(
  183. ["git", "log", "-1", "--format=%ct"], cwd=repo_root, text=True
  184. ).strip()
  185. except (subprocess.CalledProcessError, FileNotFoundError):
  186. epoch = "1764000000"
  187. _ZIP_DATE = time.gmtime(int(epoch))[:6]
  188. out_dir = Path(os.environ.get("HTH_PACKAGE_DIR") or "/tmp")
  189. out_dir.mkdir(parents=True, exist_ok=True)
  190. out = out_dir / f"hth-engineering-review-{short}-{run_id}.zip"
  191. root_name = "hth-platform-r6"
  192. files: list[Path] = []
  193. for dirpath, dirnames, filenames in os.walk(host_root):
  194. pdir = Path(dirpath)
  195. 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)]
  196. for name in filenames:
  197. path = pdir / name
  198. if should_skip(path, host_root):
  199. continue
  200. files.append(path)
  201. files.sort()
  202. files = [p for p in files if "reviews/superseded" not in str(p).replace("\\", "/")]
  203. readme = review_readme(stamp=stamp, head=head, short=short, run_id=run_id)
  204. entries: list[tuple[str, bytes, int, str]] = []
  205. extras: dict[str, tuple[bytes, int, str]] = {
  206. f"{root_name}/GIT_HEAD": ((head + "\n").encode("utf-8"), 0o644, "meta"),
  207. f"{root_name}/GIT_DIFFSTAT.txt": ((diffstat + "\n").encode("utf-8"), 0o644, "meta"),
  208. f"{root_name}/TOOLS.txt": (_tools_text().encode("utf-8"), 0o644, "meta"),
  209. f"{root_name}/README_FOR_REVIEW.md": (readme.encode("utf-8"), 0o644, "meta"),
  210. }
  211. contract = json.loads((host_root / "contracts" / "6400" / "host-contract.json").read_text(encoding="utf-8"))
  212. ident = {
  213. "package": "hth-platform-6400-engineering-review-v1",
  214. "product": "6400-front-rear-v1",
  215. "protocol_contract_sha256": contract["contract_sha256"],
  216. "profile_ids": ["6400-control", "6400-identification"],
  217. "git_commit": head,
  218. "git_short": short,
  219. "run_id": run_id,
  220. "source_date_epoch": int(epoch),
  221. }
  222. extras[f"{root_name}/PACKAGE_IDENTITY.json"] = (json.dumps(ident, indent=2).encode("utf-8") + b"\n", 0o644, "meta")
  223. for name, data in snapshot_evidence(host_root).items():
  224. extras[f"{root_name}/{name}"] = (data, 0o644, "evidence")
  225. run_dir = os.environ.get("HTH_RUN_DIR", "").strip()
  226. if run_dir:
  227. rd = Path(run_dir)
  228. if rd.is_dir():
  229. for p in sorted(rd.iterdir()):
  230. if not p.is_file() or p.stat().st_size >= 32 * 1024 * 1024:
  231. continue
  232. name_u = p.name.upper()
  233. if "SUPERSEDED" in name_u or "NOT_FINAL" in name_u:
  234. continue
  235. extras[f"{root_name}/run/{p.name}"] = (p.read_bytes(), 0o644, "run")
  236. am = rd / "ACCEPTANCE_MATRIX.md"
  237. if am.is_file():
  238. extras[f"{root_name}/ACCEPTANCE_MATRIX.md"] = (am.read_bytes(), 0o644, "run")
  239. migration = host_root / "docs" / "6400" / "migration.md"
  240. if migration.is_file():
  241. extras[f"{root_name}/reviews/6400-migration.md"] = (migration.read_bytes(), 0o644, "review")
  242. for tool in (
  243. "verify_review_package.py",
  244. "l0_contract_check.py",
  245. "evaluate_gates.py",
  246. "gen_run_manifest.py",
  247. "write_toolchain_manifest.py",
  248. "protocol_oracle.py",
  249. ):
  250. p = host_root / "tools" / tool
  251. if p.is_file():
  252. extras[f"{root_name}/verify/{tool}"] = (p.read_bytes(), zip_file_mode(p), "verify")
  253. with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
  254. manifest_lines = []
  255. sha_lines = []
  256. man_json = []
  257. members: list[tuple[str, bytes, int, str]] = []
  258. for path in files:
  259. rel = Path(root_name) / "host" / path.relative_to(host_root)
  260. members.append((str(rel).replace("\\", "/"), path.read_bytes(), zip_file_mode(path), "host"))
  261. for name, (data, mode, klass) in extras.items():
  262. members.append((name.replace("\\", "/"), data, mode, klass))
  263. members.sort(key=lambda m: m[0])
  264. for name, data, mode, klass in members:
  265. write_zip_file(zf, name, data, mode)
  266. key = name[len(root_name) + 1 :]
  267. manifest_lines.append(key)
  268. digest = hashlib.sha256(data).hexdigest()
  269. sha_lines.append(f"{digest} {key}")
  270. man_json.append({"path": key, "size": len(data), "mode": f"{mode:04o}", "sha256": digest, "source_class": klass})
  271. write_zip_file(zf, f"{root_name}/MANIFEST", ("\n".join(manifest_lines) + "\n").encode("utf-8"), 0o644)
  272. write_zip_file(zf, f"{root_name}/SHA256SUMS", ("\n".join(sha_lines) + "\n").encode("utf-8"), 0o644)
  273. write_zip_file(zf, f"{root_name}/MANIFEST.json", json.dumps(man_json, indent=2).encode("utf-8") + b"\n", 0o644)
  274. digest = hashlib.sha256(out.read_bytes()).hexdigest()
  275. sha_path = Path(str(out) + ".sha256")
  276. sha_path.write_text(f"{digest} {out.name}\n", encoding="utf-8")
  277. tree = ""
  278. try:
  279. tree = subprocess.check_output(["git", "rev-parse", "HEAD^{tree}"], cwd=repo_root, text=True).strip()
  280. except (subprocess.CalledProcessError, FileNotFoundError):
  281. tree = "unknown"
  282. att = {
  283. "filename": out.name,
  284. "bytes": out.stat().st_size,
  285. "sha256": digest,
  286. "git_commit": head,
  287. "git_tree": tree,
  288. "run_id": run_id,
  289. "source_date_epoch": int(epoch),
  290. "packager": "host/tools/package_hth_review.py",
  291. "packager_version": "r6",
  292. "release_gate_status": os.environ.get("HTH_RELEASE_GATE", "NOT RUN"),
  293. }
  294. man_json_bytes = json.dumps(man_json, indent=2).encode("utf-8") + b"\n"
  295. att["payload_manifest_sha256"] = hashlib.sha256(man_json_bytes).hexdigest()
  296. att_path = Path(str(out) + ".attestation.json")
  297. att_path.write_text(json.dumps(att, indent=2) + "\n", encoding="utf-8")
  298. print(f"zip={out}")
  299. print(f"bytes={out.stat().st_size}")
  300. print(f"sha256={digest}")
  301. print(f"sha256_sidecar={sha_path}")
  302. print(f"attestation={att_path}")
  303. print(f"top={root_name}/")
  304. return 0
  305. if __name__ == "__main__":
  306. raise SystemExit(main())