#!/usr/bin/env python3 """Small offline coordinator for the frozen multi-project UART refactor.""" from __future__ import annotations import hashlib import json import re import shutil import subprocess import uuid from datetime import datetime, timezone from pathlib import Path from typing import Any, Mapping RUN_ID_RE = re.compile(r"^[0-9a-f]{32}$") COMMIT_RE = re.compile(r"^[0-9a-f]{8}$") PROJECT_ID = "prod2u-door-temp" PROJECT_PATH = Path("projects/prod2u-door-temp/project.json") SOURCE_PATHS = ( "src/generated/prod2u_door_temp_params.vh", "src/common/uart_rx_byte.v", "src/common/uart_tx_byte.v", "src/common/crc16_serial.v", "src/common/frame_rx.v", "src/common/frame_tx.v", "src/common/payload_ram.v", "src/modules/output_target_ram.v", "src/modules/pwm_scheduler.v", "src/modules/door_motor_engine.v", "src/modules/i2c_word_reader.v", "src/modules/temperature_reader.v", "src/modules/temperature_ram.v", "src/project/command_controller.v", "src/project/project_adapter.v", "src/rtl/prod2u_por.v", "src/rtl/prod2u_p4_i2c_stop_start_read.v", "src/top/prod2u_p4_normal_v3_top.v", ) PROTOCOL_PATH = Path("docs/prod2u-door-temp-protocol.zh-CN.md") REQUIREMENTS_PATH = Path("projects/prod2u-door-temp/requirements.zh-CN.md") VERIFICATION_TARGETS_PATH = Path("config/prod2u_p4_verification_targets_v1.json") def new_run_id() -> str: return uuid.uuid4().hex def sha256_file(path: Path) -> str: digest = hashlib.sha256() with Path(path).open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _canonical_sha256(value: Mapping[str, Any]) -> str: encoded = json.dumps(dict(value), sort_keys=True, separators=(",", ":"), ensure_ascii=True) return hashlib.sha256(encoded.encode("ascii")).hexdigest() def _repo_root(root: Path | None = None) -> Path: return Path(root or Path(__file__).resolve().parents[1]).resolve() def build_source_manifest(root: Path | None = None) -> dict[str, Any]: repo = _repo_root(root) project_path = repo / PROJECT_PATH missing = [path for path in SOURCE_PATHS if not (repo / path).is_file()] if missing: raise FileNotFoundError(f"missing active source: {missing[0]}") source_hashes = {path: sha256_file(repo / path) for path in SOURCE_PATHS} payload = { "schema": "prod2u-simple-source-manifest-v1", "project_id": PROJECT_ID, "project": PROJECT_PATH.as_posix(), "project_sha256": sha256_file(project_path), "sources": list(SOURCE_PATHS), "source_sha256": source_hashes, } payload["manifest_sha256"] = _canonical_sha256(payload) return payload def current_commit8(root: Path | None = None) -> str: repo = _repo_root(root) result = subprocess.run( ["git", "rev-parse", "--short=8", "HEAD"], cwd=repo, check=True, capture_output=True, text=True, ) commit = result.stdout.strip().lower() if not COMMIT_RE.fullmatch(commit): raise ValueError(f"unexpected commit: {commit}") return commit def _write_json(path: Path, value: Mapping[str, Any]) -> None: Path(path).parent.mkdir(parents=True, exist_ok=True) Path(path).write_text(json.dumps(dict(value), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n") def init_run(run_id: str, root: Path | None = None) -> Path: if not RUN_ID_RE.fullmatch(run_id): raise ValueError("run_id must be 32 lowercase hexadecimal characters") repo = _repo_root(root) run_root = repo / "runs" / run_id run_root.mkdir(parents=True, exist_ok=True) _write_json( run_root / "plan.json", { "schema": "prod2u-simple-run-plan-v1", "run_id": run_id, "project_id": PROJECT_ID, "status": "DESIGN_FROZEN", "authority": "CPLD_多项目_UART协议_项目适配_Codex并行Harness_详细设计_v1.0.md", "hardware_access": {"com": False, "jtag": False, "programming": False, "drivers": False}, }, ) _write_json(run_root / "source-manifest.json", build_source_manifest(repo)) return run_root def create_unverified_package( *, bitstream: Path, project: Path, commit: str, run_id: str, output_root: Path, td_receipt: Path | None = None, ) -> Path: if not COMMIT_RE.fullmatch(commit): raise ValueError("commit must be 8 lowercase hexadecimal characters") if not RUN_ID_RE.fullmatch(run_id): raise ValueError("run_id must be 32 lowercase hexadecimal characters") bitstream = Path(bitstream) project = Path(project) if not bitstream.is_file() or bitstream.stat().st_size == 0: raise FileNotFoundError(f"bitstream is missing or empty: {bitstream}") if not project.is_file(): raise FileNotFoundError(f"project is missing: {project}") bitstream_sha256 = sha256_file(bitstream) package = Path(output_root) / PROJECT_ID / f"{commit}-{bitstream_sha256[:16]}" package.mkdir(parents=True, exist_ok=True) package_bitstream = package / bitstream.name package_project = package / "project.json" shutil.copy2(bitstream, package_bitstream) shutil.copy2(project, package_project) repo = _repo_root() artifacts = { "protocol.md": repo / PROTOCOL_PATH, "requirements.zh-CN.md": repo / REQUIREMENTS_PATH, "verification_targets.json": repo / VERIFICATION_TARGETS_PATH, } for name, source in artifacts.items(): if not source.is_file(): raise FileNotFoundError(f"package source is missing: {source}") shutil.copy2(source, package / name) _write_json(package / "source_manifest.json", build_source_manifest(repo)) if td_receipt is not None: receipt = Path(td_receipt) if not receipt.is_file(): raise FileNotFoundError(f"TD receipt is missing: {receipt}") shutil.copy2(receipt, package / "td_receipt.json") (package / "project_config_sha256.txt").write_text( sha256_file(package_project) + "\n", encoding="ascii", newline="\n" ) (package / "bitstream_sha256.txt").write_text( sha256_file(package_bitstream) + "\n", encoding="ascii", newline="\n" ) file_sha256 = { path.relative_to(package).as_posix(): sha256_file(path) for path in sorted(package.iterdir()) if path.is_file() and path.name != "package_manifest.json" } manifest = { "schema": "prod2u-simple-package-manifest-v1", "status": "UNVERIFIED", "run_id": run_id, "project_id": PROJECT_ID, "commit": commit, "created_at": datetime.now(timezone.utc).isoformat(), "bitstream": package_bitstream.name, "bitstream_sha256": sha256_file(package_bitstream), "project": "project.json", "project_sha256": sha256_file(package_project), "td_receipt": "td_receipt.json" if td_receipt is not None else None, "td_receipt_sha256": ( sha256_file(package / "td_receipt.json") if td_receipt is not None else None ), "file_sha256": file_sha256, "hardware_validation": "not_run", } _write_json(package / "package_manifest.json", manifest) return package def main() -> int: import argparse parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest="command", required=True) sub.add_parser("run-id") init = sub.add_parser("init") init.add_argument("--run-id", required=True) init.add_argument("--root", type=Path) manifest = sub.add_parser("manifest") manifest.add_argument("--root", type=Path) package = sub.add_parser("package") package.add_argument("--bitstream", type=Path, required=True) package.add_argument("--project", type=Path, default=PROJECT_PATH) package.add_argument("--commit", required=True) package.add_argument("--run-id", required=True) package.add_argument("--output-root", type=Path, default=Path("dist")) package.add_argument("--td-receipt", type=Path) args = parser.parse_args() if args.command == "run-id": print(new_run_id()) elif args.command == "init": print(init_run(args.run_id, args.root)) elif args.command == "manifest": print(json.dumps(build_source_manifest(args.root), indent=2, sort_keys=True)) else: print(create_unverified_package( bitstream=args.bitstream, project=args.project, commit=args.commit, run_id=args.run_id, output_root=args.output_root, td_receipt=args.td_receipt, )) return 0 if __name__ == "__main__": raise SystemExit(main())