#!/usr/bin/env python3 """L0: contract SHA snapshot, gen_profile drift, gofmt, optional buf lint.""" from __future__ import annotations import argparse import hashlib import json import subprocess import sys import tempfile from pathlib import Path HOST = Path(__file__).resolve().parents[1] REPO = HOST.parent SKIP_GO_PREFIXES = ("internal/gen/",) def sha256(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() def check_gofmt() -> list[str]: files: list[str] = [] for path in HOST.rglob("*.go"): rel = path.relative_to(HOST).as_posix() if rel.startswith(SKIP_GO_PREFIXES) or "/gen/" in rel: continue files.append(str(path)) if not files: return [] out = subprocess.check_output(["gofmt", "-l", *files], text=True) return [line for line in out.splitlines() if line.strip()] def check_profile_drift() -> str | None: gen = HOST / "tools" / "gen_profile.py" committed = HOST / "profiles" / "prod2u-door-temp" / "profile.json" with tempfile.TemporaryDirectory() as tmp: out = Path(tmp) / "profile.json" subprocess.check_call([sys.executable, str(gen), "--repo-root", str(REPO), "--out", str(out)]) got = json.loads(out.read_text(encoding="utf-8")) want = json.loads(committed.read_text(encoding="utf-8")) if got != want: return "gen_profile.py output differs from host/profiles/prod2u-door-temp/profile.json" return None def evidence() -> dict[str, str]: paths = { "host-contract.json": REPO / "src" / "generated" / "host-contract.json", "golden-vectors.json": REPO / "src" / "generated" / "golden-vectors.json", "prod2u-door-temp-protocol.zh-CN.md": REPO / "docs" / "prod2u-door-temp-protocol.zh-CN.md", "project.json": REPO / "projects" / "prod2u-door-temp" / "project.json", "profile.json": HOST / "profiles" / "prod2u-door-temp" / "profile.json", "hth.proto": HOST / "api" / "proto" / "hth" / "api" / "v1" / "hth.proto", } out: dict[str, str] = {} for name, path in paths.items(): if path.is_file(): out[name] = sha256(path) else: out[name] = "MISSING" return out def maybe_buf() -> str: try: buf = subprocess.run(["buf", "--version"], capture_output=True, text=True) except FileNotFoundError: return "buf: NOT RUN (binary missing)" if buf.returncode != 0: return "buf: NOT RUN (binary missing)" lint = subprocess.run(["buf", "lint"], cwd=HOST, capture_output=True, text=True) if lint.returncode != 0: return f"buf lint FAIL\n{lint.stdout}\n{lint.stderr}" desc = HOST / "api" / "proto" / "hth.api.v1.desc.prev" if desc.is_file(): against = f"{desc}#format=binpb" brk = subprocess.run( ["buf", "breaking", "--against", against], cwd=HOST, capture_output=True, text=True, ) if brk.returncode != 0: return f"buf breaking FAIL\n{brk.stdout}\n{brk.stderr}" return f"buf lint PASS; buf breaking PASS against {desc.name}" return "buf lint PASS; buf breaking NOT RUN (no previous descriptor)" def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--repo-root", type=Path, default=None) ap.add_argument("--evidence-root", type=Path, default=None) ap.add_argument( "--mode", choices=("offline", "release"), default="offline", help="offline: buf missing is PARTIAL; release: buf lint+breaking required", ) args = ap.parse_args() global HOST, REPO if args.repo_root is not None: REPO = args.repo_root.resolve() if (REPO / "host" / "go.mod").is_file(): HOST = REPO / "host" elif (REPO / "go.mod").is_file(): HOST = REPO ev_root = args.evidence_root.resolve() if args.evidence_root else None ev = evidence() if ev_root is not None: for name in list(ev): alt = ev_root / name if alt.is_file(): ev[name] = sha256(alt) print("L0_EVIDENCE_SHA256") for k, v in ev.items(): print(f"{v} {k}") if v == "MISSING": print("L0_FAIL missing evidence file", k, file=sys.stderr) return 1 dirty = check_gofmt() if dirty: print("L0_FAIL gofmt", file=sys.stderr) print("\n".join(dirty), file=sys.stderr) return 1 print("gofmt: clean") drift = check_profile_drift() if drift: print("L0_FAIL", drift, file=sys.stderr) return 1 print("gen_profile: no drift") oracle = HOST / "tools" / "protocol_oracle.py" golden = REPO / "src" / "generated" / "golden-vectors.json" if ev_root is not None and (ev_root / "golden-vectors.json").is_file(): golden = ev_root / "golden-vectors.json" elif not golden.is_file() and (REPO / "evidence" / "golden-vectors.json").is_file(): golden = REPO / "evidence" / "golden-vectors.json" o = subprocess.run( [ sys.executable, str(oracle), "--golden", str(golden), "--min-positive", "8", "--min-negative", "2", "--min-frames", "6", ], capture_output=True, text=True, ) print(o.stdout.strip()) if o.returncode != 0: print("L0_FAIL oracle", file=sys.stderr) print(o.stderr, file=sys.stderr) return 1 buf_line = maybe_buf() print(buf_line) buf_missing = "NOT RUN" in buf_line buf_fail = "FAIL" in buf_line if args.mode == "release": if buf_missing or buf_fail: print("L0_RELEASE_GATE_FAIL buf required", file=sys.stderr) print(buf_line, file=sys.stderr) return 1 print("L0_RELEASE_CONTRACT_GATE_PASS") print("L0_CONTRACT_CHECK_PASS") return 0 if buf_fail: print("L0_FAIL buf", file=sys.stderr) return 1 if buf_missing: print("L0_OFFLINE_EVIDENCE_CHECK_PARTIAL") print("buf NOT RUN") return 0 print("L0_OFFLINE_EVIDENCE_CHECK_PASS") print("L0_CONTRACT_CHECK_PASS") return 0 if __name__ == "__main__": raise SystemExit(main())