| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348 |
- #!/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) -> 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,
- "authority_boundary": "Offline package placeholder. No COM, JTAG, programming, or board action.",
- }
- 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,
- ) -> 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)
- source_manifest = build_source_manifest(repo)
- _write_json(package / "source_manifest.json", source_manifest)
- 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, evidence / "td-primary-receipt.json")
- else:
- _write_json(
- evidence / "td-primary-receipt.json",
- _receipt_payload(name="td-primary", run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256),
- )
- _write_json(
- evidence / "td-confirmation-receipt.json",
- _receipt_payload(name="td-confirmation", run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256),
- )
- for name in ("python-unit", "icarus", "verilator", "cocotb", "formal"):
- _write_json(
- evidence / f"{name}-receipt.json",
- _receipt_payload(name=name, run_id=run_id, commit=commit, bitstream_sha256=bitstream_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"
- 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"])
- except (OSError, UnicodeError, json.JSONDecodeError):
- td_status = "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": "not_run"},
- "icarus": {"status": "not_run"},
- "verilator": {"status": "not_run"},
- "cocotb": {"status": "not_run"},
- "formal": {"status": "not_run"},
- "td_primary": {"status": td_status},
- "td_confirmation": {"status": "not_run"},
- "td_confirmation_artifacts": {"status": "not_run"},
- "td_confirmation_bitstream": {"status": "not_run"},
- "td_confirmation_synthesis": {"status": "not_run"},
- "td_confirmation_manifest": {"status": "not_run"},
- "resource_confirmation": {"status": "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"),
- "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)
- 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())
|