| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349 |
- #!/usr/bin/env python3
- """Package the standalone HTH repository under a compatibility ``host/`` prefix.
- Works without the `zip` / `rsync` binaries.
- """
- from __future__ import annotations
- import hashlib
- import json
- 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"}
- PACKAGE_EXCLUDED_PREFIXES = {
- "contracts/evidence",
- "profiles/prod2u-door-temp",
- "profiles/6400-sim-debug",
- }
- PACKAGE_EXCLUDED_FILES = {
- "RELEASE.zh-CN.md",
- "REQUIREMENTS_TRACEABILITY.md",
- "docs/architecture.zh-CN.md",
- "docs/compatibility-policy.zh-CN.md",
- "docs/failure-semantics.zh-CN.md",
- "docs/known-gaps.zh-CN.md",
- "docs/protocol-source-audit.zh-CN.md",
- "docs/safety-contract.zh-CN.md",
- "docs/signal-dictionary.zh-CN.md",
- }
- def zip_file_mode(path: Path) -> int:
- name = path.name
- if path.suffix == ".sh" or name in {"hthd", "hthctl", "hth-capture", "install.sh", "uninstall.sh"}:
- return 0o755
- if path.suffix == ".py":
- try:
- if path.read_bytes()[:2] == b"#!":
- return 0o755
- except OSError:
- pass
- if path.suffix in {".yaml", ".yml"} and ("example" in name or name in {"hthd.yaml"}):
- return 0o640
- return 0o644
- _ZIP_DATE = (2026, 1, 1, 0, 0, 0)
- 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.date_time = _ZIP_DATE
- info.external_attr = (mode & 0o777) << 16
- info.compress_type = zipfile.ZIP_DEFLATED
- zf.writestr(info, data)
- def should_skip(path: Path, host_root: Path) -> bool:
- rel = path.relative_to(host_root)
- rel_posix = rel.as_posix()
- if rel_posix in PACKAGE_EXCLUDED_FILES:
- return True
- if any(rel_posix == prefix or rel_posix.startswith(prefix + "/") for prefix in PACKAGE_EXCLUDED_PREFIXES):
- return True
- 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 rel.parts and rel.parts[0] == "reviews":
- return True
- if path.name in {"ACCEPTANCE_MATRIX.md", "_r6_quick_test.sh"}:
- 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(host_root: Path) -> dict[str, bytes]:
- mapping = {
- "evidence/6400/host-contract.json": host_root / "contracts" / "6400" / "host-contract.json",
- "evidence/6400/SHA256SUMS": host_root / "contracts" / "6400" / "SHA256SUMS",
- "evidence/6400/import-source.json": host_root / "generated" / "6400" / "import-source.json",
- "evidence/6400/profiles/6400-control.json": host_root / "profiles" / "6400-control" / "profile.json",
- "evidence/6400/profiles/6400-identification.json": host_root / "profiles" / "6400-identification" / "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 review_readme(*, stamp: str, head: str, short: str, run_id: str) -> str:
- return f"""# HTH 6400 engineering review
- Generated: {stamp} UTC
- Git HEAD: {head}
- Short: {short}
- Run ID: {run_id}
- ## Active contract
- Product: `6400-front-rear-v1`
- Canonical release profiles: `6400-control`, `6400-identification`
- Every valid Host command returns an independent zero-payload ACK. `SET_TARGET`
- returns `0x81`; `GET_SNAPSHOT` returns `0x82` ACK followed by the distinct
- `0x42` Snapshot Data frame; Identification `SET_STIMULUS` returns `0x83`.
- An ACK proves atomic command or snapshot-bank commit, not thermal attainment.
- Production `6400-control` does not expose stimulus.
- The active wire contract, source binding, and canonical profiles are under
- `evidence/6400/`. Legacy door-controller profiles, evidence, reviews, and
- release notes are intentionally excluded from this 6400 review package.
- ## Evidence boundaries
- Software simulation & integration acceptance: see run/run-manifest.json (Gate Evaluator, not hand-edited)
- Hardware validation: NOT RUN
- Real actuator validation: NOT RUN
- Release candidate readiness: NO unless the applicable release gates and controlled hardware validation pass
- Production readiness: NO
- ## Layout
- - `host/` standalone HTH daemon, proto, Python SDK, 6400 docs, and deploy files
- - `evidence/6400/` imported contract, provenance, and canonical release profiles
- - `run/` this-run logs only
- - `reviews/6400-migration.md` active 6400 integration note
- - `MANIFEST.json` / `MANIFEST` / `SHA256SUMS`
- ## Self-verify
- From the unzipped `hth-platform-r6/` directory:
- ```
- python3 host/tools/verify_review_package.py . --mode offline
- python3 host/tools/verify_review_package.py . --mode release
- ```
- """
- def git_info(repo: Path) -> tuple[str, str, str]:
- env_head = os.environ.get("HTH_GIT_COMMIT", "").strip()
- env_short = os.environ.get("HTH_GIT_SHORT", "").strip()
- 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 env_head:
- short = env_short or env_head[:12]
- return env_head, short, os.environ.get("HTH_GIT_DIFFSTAT", "clean (commit bound via HTH_GIT_COMMIT)")
- 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:
- import time
- global _ZIP_DATE
- host_root = Path(__file__).resolve().parents[1]
- repo_root = host_root
- stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
- head, short, diffstat = git_info(repo_root)
- run_id = os.environ.get("HTH_RUN_ID") or stamp
- epoch = os.environ.get("SOURCE_DATE_EPOCH")
- if not epoch:
- try:
- epoch = subprocess.check_output(
- ["git", "log", "-1", "--format=%ct"], cwd=repo_root, text=True
- ).strip()
- except (subprocess.CalledProcessError, FileNotFoundError):
- epoch = "1764000000"
- _ZIP_DATE = time.gmtime(int(epoch))[:6]
- out_dir = Path(os.environ.get("HTH_PACKAGE_DIR") or "/tmp")
- out_dir.mkdir(parents=True, exist_ok=True)
- out = out_dir / f"hth-engineering-review-{short}-{run_id}.zip"
- root_name = "hth-platform-r6"
- 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()
- files = [p for p in files if "reviews/superseded" not in str(p).replace("\\", "/")]
- readme = review_readme(stamp=stamp, head=head, short=short, run_id=run_id)
- entries: list[tuple[str, bytes, int, str]] = []
- extras: dict[str, tuple[bytes, int, str]] = {
- f"{root_name}/GIT_HEAD": ((head + "\n").encode("utf-8"), 0o644, "meta"),
- f"{root_name}/GIT_DIFFSTAT.txt": ((diffstat + "\n").encode("utf-8"), 0o644, "meta"),
- f"{root_name}/TOOLS.txt": (_tools_text().encode("utf-8"), 0o644, "meta"),
- f"{root_name}/README_FOR_REVIEW.md": (readme.encode("utf-8"), 0o644, "meta"),
- }
- contract = json.loads((host_root / "contracts" / "6400" / "host-contract.json").read_text(encoding="utf-8"))
- ident = {
- "package": "hth-platform-6400-engineering-review-v1",
- "product": "6400-front-rear-v1",
- "protocol_contract_sha256": contract["contract_sha256"],
- "profile_ids": ["6400-control", "6400-identification"],
- "git_commit": head,
- "git_short": short,
- "run_id": run_id,
- "source_date_epoch": int(epoch),
- }
- extras[f"{root_name}/PACKAGE_IDENTITY.json"] = (json.dumps(ident, indent=2).encode("utf-8") + b"\n", 0o644, "meta")
- for name, data in snapshot_evidence(host_root).items():
- extras[f"{root_name}/{name}"] = (data, 0o644, "evidence")
- 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[f"{root_name}/run/{p.name}"] = (p.read_bytes(), 0o644, "run")
- am = rd / "ACCEPTANCE_MATRIX.md"
- if am.is_file():
- extras[f"{root_name}/ACCEPTANCE_MATRIX.md"] = (am.read_bytes(), 0o644, "run")
- migration = host_root / "docs" / "6400" / "migration.md"
- if migration.is_file():
- extras[f"{root_name}/reviews/6400-migration.md"] = (migration.read_bytes(), 0o644, "review")
- for tool in (
- "verify_review_package.py",
- "l0_contract_check.py",
- "evaluate_gates.py",
- "gen_run_manifest.py",
- "write_toolchain_manifest.py",
- "protocol_oracle.py",
- ):
- p = host_root / "tools" / tool
- if p.is_file():
- extras[f"{root_name}/verify/{tool}"] = (p.read_bytes(), zip_file_mode(p), "verify")
- with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
- manifest_lines = []
- sha_lines = []
- man_json = []
- members: list[tuple[str, bytes, int, str]] = []
- for path in files:
- rel = Path(root_name) / "host" / path.relative_to(host_root)
- members.append((str(rel).replace("\\", "/"), path.read_bytes(), zip_file_mode(path), "host"))
- for name, (data, mode, klass) in extras.items():
- members.append((name.replace("\\", "/"), data, mode, klass))
- members.sort(key=lambda m: m[0])
- for name, data, mode, klass in members:
- write_zip_file(zf, name, data, mode)
- key = name[len(root_name) + 1 :]
- manifest_lines.append(key)
- digest = hashlib.sha256(data).hexdigest()
- sha_lines.append(f"{digest} {key}")
- man_json.append({"path": key, "size": len(data), "mode": f"{mode:04o}", "sha256": digest, "source_class": klass})
- write_zip_file(zf, f"{root_name}/MANIFEST", ("\n".join(manifest_lines) + "\n").encode("utf-8"), 0o644)
- write_zip_file(zf, f"{root_name}/SHA256SUMS", ("\n".join(sha_lines) + "\n").encode("utf-8"), 0o644)
- write_zip_file(zf, f"{root_name}/MANIFEST.json", json.dumps(man_json, indent=2).encode("utf-8") + b"\n", 0o644)
- digest = hashlib.sha256(out.read_bytes()).hexdigest()
- sha_path = Path(str(out) + ".sha256")
- sha_path.write_text(f"{digest} {out.name}\n", encoding="utf-8")
- tree = ""
- try:
- tree = subprocess.check_output(["git", "rev-parse", "HEAD^{tree}"], cwd=repo_root, text=True).strip()
- except (subprocess.CalledProcessError, FileNotFoundError):
- tree = "unknown"
- att = {
- "filename": out.name,
- "bytes": out.stat().st_size,
- "sha256": digest,
- "git_commit": head,
- "git_tree": tree,
- "run_id": run_id,
- "source_date_epoch": int(epoch),
- "packager": "host/tools/package_hth_review.py",
- "packager_version": "r6",
- "release_gate_status": os.environ.get("HTH_RELEASE_GATE", "NOT RUN"),
- }
- man_json_bytes = json.dumps(man_json, indent=2).encode("utf-8") + b"\n"
- att["payload_manifest_sha256"] = hashlib.sha256(man_json_bytes).hexdigest()
- att_path = Path(str(out) + ".attestation.json")
- att_path.write_text(json.dumps(att, indent=2) + "\n", encoding="utf-8")
- print(f"zip={out}")
- print(f"bytes={out.stat().st_size}")
- print(f"sha256={digest}")
- print(f"sha256_sidecar={sha_path}")
- print(f"attestation={att_path}")
- print(f"top={root_name}/")
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|