| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229 |
- #!/usr/bin/env python3
- """Draft packager: zip host/ (no .git, venv, caches) to /tmp/hth-platform-review-*.zip.
- Parent may run this later. Works without the `zip` / `rsync` binaries.
- """
- from __future__ import annotations
- import hashlib
- import os
- import subprocess
- import zipfile
- from datetime import datetime, timezone
- from pathlib import Path
- SKIP_DIR_NAMES = {
- ".git",
- ".venv-sdk",
- ".venv",
- "__pycache__",
- ".pytest_cache",
- ".mypy_cache",
- ".ruff_cache",
- "bin",
- "dist",
- "build",
- "artifacts",
- }
- SKIP_SUFFIXES = {".sock", ".pyc", ".pyo"}
- SKIP_NAME_SUBSTR = {".egg-info"}
- def zip_file_mode(path: Path) -> int:
- if path.suffix == ".sh" or path.name in {"hthd", "hthctl", "hth-capture", "install.sh"}:
- return 0o755
- if path.suffix == ".py":
- try:
- if path.read_bytes()[:2] == b"#!":
- return 0o755
- except OSError:
- pass
- return 0o644
- def write_zip_file(zf: zipfile.ZipFile, name: str, data: bytes, mode: int = 0o644) -> None:
- info = zipfile.ZipInfo(name.replace("\\", "/"))
- info.create_system = 3
- info.external_attr = (mode & 0o777) << 16
- zf.writestr(info, data)
- def should_skip(path: Path, host_root: Path) -> bool:
- rel = path.relative_to(host_root)
- for part in rel.parts:
- if part in SKIP_DIR_NAMES:
- return True
- if any(token in part for token in SKIP_NAME_SUBSTR):
- return True
- if path.suffix in SKIP_SUFFIXES:
- return True
- return False
- def _tools_text() -> str:
- lines = []
- for args in (
- ["go", "version"],
- ["protoc", "--version"],
- ["python3", "--version"],
- ["git", "--version"],
- ):
- try:
- out = subprocess.check_output(args, stderr=subprocess.STDOUT, text=True)
- lines.append(out.strip())
- except (subprocess.CalledProcessError, FileNotFoundError) as exc:
- lines.append(f"{args[0]}: {exc}")
- return "\n".join(lines) + "\n"
- def snapshot_evidence(repo: Path, host_root: Path) -> dict[str, bytes]:
- mapping = {
- "evidence/host-contract.json": repo / "src" / "generated" / "host-contract.json",
- "evidence/golden-vectors.json": repo / "src" / "generated" / "golden-vectors.json",
- "evidence/prod2u-door-temp-protocol.zh-CN.md": repo / "docs" / "prod2u-door-temp-protocol.zh-CN.md",
- "evidence/project.json": repo / "projects" / "prod2u-door-temp" / "project.json",
- "evidence/profile.json": host_root / "profiles" / "prod2u-door-temp" / "profile.json",
- "evidence/hth.proto": host_root / "api" / "proto" / "hth" / "api" / "v1" / "hth.proto",
- }
- out: dict[str, bytes] = {}
- sha_lines = []
- for name, path in mapping.items():
- if not path.is_file():
- continue
- data = path.read_bytes()
- out[name] = data
- sha_lines.append(f"{hashlib.sha256(data).hexdigest()} {name}")
- out["evidence/SHA256SUMS"] = ("\n".join(sha_lines) + "\n").encode("utf-8")
- return out
- def git_info(repo: Path) -> tuple[str, str, str]:
- def run(args: list[str]) -> str:
- try:
- out = subprocess.check_output(args, cwd=repo, stderr=subprocess.DEVNULL, text=True)
- return out.strip()
- except (subprocess.CalledProcessError, FileNotFoundError):
- return ""
- if not (repo / ".git").exists() and run(["git", "rev-parse", "--is-inside-work-tree"]) != "true":
- return "unknown", "unknown", "n/a (not a git checkout or git unavailable)"
- head = run(["git", "rev-parse", "HEAD"]) or "unknown"
- short = run(["git", "rev-parse", "--short", "HEAD"]) or "unknown"
- stat_txt = run(["git", "diff", "--stat"]) or "clean or unavailable"
- return head, short, stat_txt[-2000:]
- def main() -> int:
- host_root = Path(__file__).resolve().parents[1]
- repo_root = host_root.parent
- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
- head, short, diffstat = git_info(repo_root)
- out = Path(f"/tmp/hth-platform-safety-closure-r3-{short}-{stamp}.zip")
- files: list[Path] = []
- for dirpath, dirnames, filenames in os.walk(host_root):
- pdir = Path(dirpath)
- 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)]
- for name in filenames:
- path = pdir / name
- if should_skip(path, host_root):
- continue
- files.append(path)
- files.sort()
- readme = f"""# hth platform safety closure r3
- Generated: {stamp} UTC
- Git HEAD: {head}
- Short: {short}
- Run dir: {os.environ.get("HTH_RUN_DIR", "(none)")}
- ## Honesty
- Software safety acceptance: BLOCKED
- Hardware validation: NOT RUN
- Real actuator validation: NOT RUN
- Architecture direction: PASS
- Ready for controlled hardware validation: NO
- Protocol: percent-close doors 0..100, GET_MOTOR_STATUS exists, NO ACK,
- watchdog 30s fed only by SET_ALL after startup, GET_TEMP dropped during startup.
- Door 0 is FULL OPEN not STOP.
- ## Layout
- - `host/` — daemon, proto, Python SDK, docs, deploy, reviews
- - `run/` — this-run logs only (not superseded evidence)
- - `MANIFEST` / `SHA256SUMS`
- ## Self-verify
- From the unzipped `hth-platform/` directory:
- ```
- python3 host/tools/verify_review_package.py .
- python3 host/tools/l0_contract_check.py --repo-root . --evidence-root evidence
- python3 host/tools/protocol_oracle.py --golden evidence/golden-vectors.json --min-positive 8 --min-negative 2 --min-frames 6
- ```
- `--repo-root` must be the directory that contains `host/` (this unzipped `hth-platform/` tree).
- """
- manifest_lines = []
- sha_lines = []
- extras: dict[str, bytes] = {
- "hth-platform/GIT_HEAD": (head + "\n").encode("utf-8"),
- "hth-platform/GIT_DIFFSTAT.txt": (diffstat + "\n").encode("utf-8"),
- "hth-platform/TOOLS.txt": _tools_text().encode("utf-8"),
- "hth-platform/README_FOR_REVIEW.md": readme.encode("utf-8"),
- }
- for name, data in snapshot_evidence(repo_root, host_root).items():
- extras["hth-platform/" + name] = data
- aliases = {
- "evidence/host-contract.json": "src/generated/host-contract.json",
- "evidence/golden-vectors.json": "src/generated/golden-vectors.json",
- "evidence/project.json": "projects/prod2u-door-temp/project.json",
- "evidence/prod2u-door-temp-protocol.zh-CN.md": "docs/prod2u-door-temp-protocol.zh-CN.md",
- }
- if name in aliases:
- extras["hth-platform/" + aliases[name]] = data
- run_dir = os.environ.get("HTH_RUN_DIR", "").strip()
- if run_dir:
- rd = Path(run_dir)
- if rd.is_dir():
- for p in sorted(rd.iterdir()):
- if not p.is_file() or p.stat().st_size >= 32 * 1024 * 1024:
- continue
- name_u = p.name.upper()
- if "SUPERSEDED" in name_u or "NOT_FINAL" in name_u:
- continue
- extras["hth-platform/run/" + p.name] = p.read_bytes()
- # Do not copy superseded /tmp/hth-gotest.log or other-run artifacts.
- with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED) as zf:
- for path in files:
- rel = Path("hth-platform") / "host" / path.relative_to(host_root)
- data = path.read_bytes()
- write_zip_file(zf, str(rel), data, zip_file_mode(path))
- key = str(rel.relative_to("hth-platform")).replace("\\", "/")
- manifest_lines.append(key)
- sha_lines.append(f"{hashlib.sha256(data).hexdigest()} {key}")
- for name, data in extras.items():
- write_zip_file(zf, name, data, 0o644)
- key = name[len("hth-platform/") :]
- manifest_lines.append(key)
- sha_lines.append(f"{hashlib.sha256(data).hexdigest()} {key}")
- write_zip_file(zf, "hth-platform/MANIFEST", ("\n".join(manifest_lines) + "\n").encode("utf-8"), 0o644)
- write_zip_file(zf, "hth-platform/SHA256SUMS", ("\n".join(sha_lines) + "\n").encode("utf-8"), 0o644)
- digest = hashlib.sha256(out.read_bytes()).hexdigest()
- print(f"zip={out}")
- print(f"bytes={out.stat().st_size}")
- print(f"sha256={digest}")
- print("top=hth-platform/")
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|