package_hth_algorithm_kit.py 3.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #!/usr/bin/env python3
  2. """Build the director-facing algorithm kit. No Go, proto, RTL, or review docs."""
  3. from __future__ import annotations
  4. import hashlib
  5. import json
  6. import os
  7. import sys
  8. import zipfile
  9. from datetime import datetime, timezone
  10. from pathlib import Path
  11. from package_hth_review import write_zip_file
  12. ROOT_NAME = "hth-algorithm-kit"
  13. def _sha(data: bytes) -> str:
  14. return hashlib.sha256(data).hexdigest()
  15. def main() -> int:
  16. host = Path(__file__).resolve().parents[1]
  17. sdk = host / "sdk" / "python"
  18. sys.path.insert(0, str(sdk))
  19. commit = os.environ.get("HTH_GIT_COMMIT", "unknown")
  20. short = commit[:7] if commit != "unknown" else "unknown"
  21. version = "0.2.0"
  22. out_dir = Path(os.environ.get("HTH_PACKAGE_DIR") or os.environ.get("TEMP") or "/tmp")
  23. out_dir.mkdir(parents=True, exist_ok=True)
  24. wheel = Path(os.environ.get("HTH_SDK_WHEEL") or "")
  25. if not wheel.is_file():
  26. dist = list((sdk / "dist").glob("hth_sdk-*.whl")) if (sdk / "dist").is_dir() else []
  27. if not dist:
  28. raise SystemExit("set HTH_SDK_WHEEL to a built wheel")
  29. wheel = sorted(dist)[-1]
  30. epoch = int(os.environ.get("SOURCE_DATE_EPOCH") or 0)
  31. items: list[tuple[str, bytes, int]] = []
  32. def add(name: str, data: bytes, mode: int = 0o644) -> None:
  33. items.append((f"{ROOT_NAME}/{name}", data, mode))
  34. add("README_10_MINUTES.md", (host / "docs" / "simple" / "README_10_MINUTES.md").read_bytes())
  35. add("ALGORITHM_API.md", (host / "docs" / "simple" / "ALGORITHM_API.md").read_bytes())
  36. add(wheel.name, wheel.read_bytes())
  37. add("quickstart.py", (sdk / "examples" / "quickstart.py").read_bytes())
  38. add("policy_template.py", (sdk / "examples" / "policy_template.py").read_bytes())
  39. add("closed_loop_demo.py", (sdk / "examples" / "closed_loop_demo.py").read_bytes())
  40. add("offline_replay_demo.py", (sdk / "examples" / "offline_replay_demo.py").read_bytes())
  41. add("algorithm_quickstart.ipynb", (sdk / "examples" / "algorithm_quickstart.ipynb").read_bytes())
  42. add(
  43. "scenarios/README.md",
  44. b"SIMULATION ONLY\nNOT IDENTIFIED FROM REAL HARDWARE\nNOT A PHYSICAL VALIDATION MODEL\n",
  45. )
  46. from hth_sdk.replay import write_sample_replay
  47. replay = Path(os.environ.get("TMPDIR") or "/tmp") / "hth-sample-replay.jsonl"
  48. write_sample_replay(replay)
  49. add("sample_replay/sample.jsonl", replay.read_bytes())
  50. manifest = {
  51. "name": ROOT_NAME,
  52. "version": version,
  53. "git_commit": commit,
  54. "created_utc": datetime.fromtimestamp(epoch or 0, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
  55. if epoch
  56. else datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
  57. "files": [n.split("/", 1)[1] for n, _, _ in items],
  58. "note": "Director kit. Mock/Replay only. Hardware validation NOT RUN.",
  59. }
  60. add("MANIFEST.json", (json.dumps(manifest, indent=2, sort_keys=True) + "\n").encode())
  61. items.sort(key=lambda x: x[0])
  62. sums = []
  63. for name, data, _ in items:
  64. sums.append(f"{_sha(data)} {name.split('/', 1)[1]}")
  65. items.append((f"{ROOT_NAME}/SHA256SUMS", ("\n".join(sums) + "\n").encode(), 0o644))
  66. items.sort(key=lambda x: x[0])
  67. zip_path = out_dir / f"hth-algorithm-kit-{version}-{short}.zip"
  68. with zipfile.ZipFile(zip_path, "w") as zf:
  69. for name, data, mode in items:
  70. write_zip_file(zf, name, data, mode)
  71. digest = _sha(zip_path.read_bytes())
  72. (out_dir / (zip_path.name + ".sha256")).write_text(f"{digest} {zip_path.name}\n", encoding="utf-8")
  73. att = {
  74. "filename": zip_path.name,
  75. "bytes": zip_path.stat().st_size,
  76. "sha256": digest,
  77. "git_commit": commit,
  78. "packager": "host/tools/package_hth_algorithm_kit.py",
  79. "kind": "algorithm-kit",
  80. }
  81. (out_dir / (zip_path.name + ".attestation.json")).write_text(json.dumps(att, indent=2) + "\n", encoding="utf-8")
  82. print(zip_path)
  83. return 0
  84. if __name__ == "__main__":
  85. raise SystemExit(main())