#!/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") PACKAGE_INFO_SCHEMA = "prod2u-p4-normal-v3-folder-package-info-v3" PACKAGE_MANIFEST_SCHEMA = "prod2u-simple-package-manifest-v2" RUNTIME_PROFILE = "prod2u-door-temp-115200-v1" def _receipt_payload(*, name: str, run_id: str, commit: str, bitstream_sha256: str, project_config_sha256: str) -> dict[str, Any]: return { "schema": f"prod2u-p4-normal-v3-{name}-receipt-v1", "status": "not_run", "verification_run_id": run_id, "commit": commit, "bitstream_sha256": bitstream_sha256, "project_config_sha256": project_config_sha256, "authority_boundary": "Offline package placeholder. No COM, JTAG, programming, or board action.", } def _copy_bound_receipt( source: Path, destination: Path, *, run_id: str, commit: str, bitstream_sha256: str, project_config_sha256: str, ) -> dict[str, Any]: try: value = json.loads(Path(source).read_text(encoding="utf-8-sig")) except (OSError, UnicodeError, json.JSONDecodeError) as exc: raise ValueError(f"receipt is not readable JSON: {source}") from exc if not isinstance(value, dict): raise ValueError(f"receipt root must be an object: {source}") bindings = { "verification_run_id": run_id, "commit": commit, "bitstream_sha256": bitstream_sha256, "project_config_sha256": project_config_sha256, } for field, expected in bindings.items(): observed = value.get(field) if observed not in {None, "", expected}: raise ValueError(f"receipt binding mismatch for {field}: {source}") value[field] = expected value["source_receipt_sha256"] = sha256_file(source) _write_json(destination, value) return value def _package_file_hashes(package: Path) -> dict[str, str]: excluded = { "package-info.json", "package_manifest.json", "evidence/package-selftest-result.json", } return { path.relative_to(package).as_posix(): sha256_file(path) for path in sorted(package.rglob("*")) if path.is_file() and path.relative_to(package).as_posix() not in excluded } 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, verification_receipts: Mapping[str, 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 / "fw.bit" package_project = package / "project.json" evidence = package / "evidence" evidence.mkdir(parents=True, exist_ok=True) 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) project_config_sha256 = sha256_file(package_project) source_manifest = build_source_manifest(repo) _write_json(package / "source_manifest.json", source_manifest) receipt_sources = dict(verification_receipts or {}) if td_receipt is not None: receipt = Path(td_receipt) if not receipt.is_file(): raise FileNotFoundError(f"TD receipt is missing: {receipt}") _copy_bound_receipt( receipt, evidence / "td-primary-receipt.json", run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256, ) else: _write_json( evidence / "td-primary-receipt.json", _receipt_payload(name="td-primary", run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256), ) receipt_specs = { "td-confirmation": "td-confirmation-receipt.json", "python-unit": "python-unit-receipt.json", "icarus": "icarus-receipt.json", "verilator": "verilator-receipt.json", "cocotb": "cocotb-receipt.json", "formal": "formal-receipt.json", } for name, filename in receipt_specs.items(): source = receipt_sources.get(name) if source is not None: source_path = Path(source) if not source_path.is_file(): raise FileNotFoundError(f"verification receipt is missing: {source_path}") _copy_bound_receipt( source_path, evidence / filename, run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256, ) else: _write_json( evidence / filename, _receipt_payload(name=name, run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256), ) _write_json( evidence / "package-selftest-result.json", { "schema": "prod2u-p4-normal-v3-package-selftest-result-v1", "status": "not_run", "verification_run_id": run_id, "commit": commit, "bitstream_sha256": bitstream_sha256, }, ) (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" ) td_status = "not_run" td_synthesis_input_hash = None confirmation_bitstream_sha256 = None confirmation_synthesis_input_hash = None try: td_value = json.loads((evidence / "td-primary-receipt.json").read_text(encoding="utf-8-sig")) if isinstance(td_value, Mapping) and td_value.get("status") in {"pass", "fail", "blocked", "not_run"}: td_status = str(td_value["status"]) td_synthesis_input_hash = td_value.get("synthesis_input_hash") except (OSError, UnicodeError, json.JSONDecodeError): td_status = "fail" try: confirmation_value = json.loads((evidence / "td-confirmation-receipt.json").read_text(encoding="utf-8-sig")) if isinstance(confirmation_value, Mapping) and confirmation_value.get("status") == "pass": confirmation_bitstream_sha256 = confirmation_value.get("bitstream_sha256") confirmation_synthesis_input_hash = confirmation_value.get("synthesis_input_hash") except (OSError, UnicodeError, json.JSONDecodeError): pass def receipt_status(filename: str) -> str: try: value = json.loads((evidence / filename).read_text(encoding="utf-8-sig")) except (OSError, UnicodeError, json.JSONDecodeError): return "fail" return str(value.get("status", "fail")) if isinstance(value, Mapping) else "fail" validation_summary = { "schema": "prod2u-p4-normal-v3-validation-summary-v1", "status": "UNVERIFIED", "delivery_mode": "urgent_single_td", "verification_complete": False, "confirmation_td_present": True, "verification_run_id": run_id, "commit": commit, "bitstream_sha256": bitstream_sha256, "project_config_sha256": sha256_file(package_project), "layers": { "python_unit": {"status": receipt_status("python-unit-receipt.json")}, "icarus": {"status": receipt_status("icarus-receipt.json")}, "verilator": {"status": receipt_status("verilator-receipt.json")}, "cocotb": {"status": receipt_status("cocotb-receipt.json")}, "formal": {"status": receipt_status("formal-receipt.json")}, "td_primary": {"status": td_status}, "td_confirmation": {"status": receipt_status("td-confirmation-receipt.json")}, "td_confirmation_artifacts": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"}, "td_confirmation_bitstream": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"}, "td_confirmation_synthesis": {"status": "pass" if confirmation_synthesis_input_hash else "not_run"}, "td_confirmation_manifest": {"status": "pass" if confirmation_synthesis_input_hash else "not_run"}, "resource_confirmation": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"}, }, "hardware_validation": "not_run", } _write_json(evidence / "validation-summary.json", validation_summary) _write_json(package / "verification_summary.json", validation_summary) package_info = { "schema": PACKAGE_INFO_SCHEMA, "profile": RUNTIME_PROFILE, "project_id": PROJECT_ID, "delivery_mode": "urgent_single_td", "verification_complete": False, "confirmation_td_present": True, "verification_run_id": run_id, "commit": commit, "bitstream": "fw.bit", "bitstream_sha256": bitstream_sha256, "project": "project.json", "project_sha256": sha256_file(package_project), "project_config_sha256": sha256_file(package_project), "source_manifest_sha256": sha256_file(package / "source_manifest.json"), "synthesis_input_hash": td_synthesis_input_hash, "confirmation_bitstream_sha256": confirmation_bitstream_sha256, "confirmation_synthesis_input_hash": confirmation_synthesis_input_hash, "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"), "confirmation_td_receipt_sha256": sha256_file(evidence / "td-confirmation-receipt.json"), "validation_summary_sha256": sha256_file(evidence / "validation-summary.json"), "package_selftest_result_sha256": sha256_file(evidence / "package-selftest-result.json"), "file_sha256": _package_file_hashes(package), "hardware_validation": "not_run", } _write_json(package / "package-info.json", package_info) manifest = { "schema": PACKAGE_MANIFEST_SCHEMA, "status": "UNVERIFIED", "run_id": run_id, "project_id": PROJECT_ID, "commit": commit, "created_at": datetime.now(timezone.utc).isoformat(), "bitstream": "fw.bit", "bitstream_sha256": sha256_file(package_bitstream), "project": "project.json", "project_sha256": sha256_file(package_project), "package_info": "package-info.json", "package_info_sha256": sha256_file(package / "package-info.json"), "td_receipt": "evidence/td-primary-receipt.json", "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"), "file_sha256": _package_file_hashes(package), "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) package.add_argument( "--receipt", action="append", default=[], metavar="NAME=PATH", help="bind an additional receipt under evidence (NAME: python-unit, icarus, verilator, cocotb, formal, td-confirmation)", ) 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: receipt_map: dict[str, Path] = {} for item in args.receipt: name, separator, raw_path = item.partition("=") if not separator or not name or not raw_path: raise SystemExit(f"invalid --receipt value: {item!r}; expected NAME=PATH") receipt_map[name] = Path(raw_path) 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, verification_receipts=receipt_map, )) return 0 if __name__ == "__main__": raise SystemExit(main())