codex_harness.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. #!/usr/bin/env python3
  2. """Small offline coordinator for the frozen multi-project UART refactor."""
  3. from __future__ import annotations
  4. import hashlib
  5. import json
  6. import re
  7. import shutil
  8. import subprocess
  9. import uuid
  10. from datetime import datetime, timezone
  11. from pathlib import Path
  12. from typing import Any, Mapping
  13. RUN_ID_RE = re.compile(r"^[0-9a-f]{32}$")
  14. COMMIT_RE = re.compile(r"^[0-9a-f]{8}$")
  15. PROJECT_ID = "prod2u-door-temp"
  16. PROJECT_PATH = Path("projects/prod2u-door-temp/project.json")
  17. SOURCE_PATHS = (
  18. "src/generated/prod2u_door_temp_params.vh",
  19. "src/common/uart_rx_byte.v",
  20. "src/common/uart_tx_byte.v",
  21. "src/common/crc16_serial.v",
  22. "src/common/frame_rx.v",
  23. "src/common/frame_tx.v",
  24. "src/common/payload_ram.v",
  25. "src/modules/output_target_ram.v",
  26. "src/modules/pwm_scheduler.v",
  27. "src/modules/door_motor_engine.v",
  28. "src/modules/i2c_word_reader.v",
  29. "src/modules/temperature_reader.v",
  30. "src/modules/temperature_ram.v",
  31. "src/project/command_controller.v",
  32. "src/project/project_adapter.v",
  33. "src/rtl/prod2u_por.v",
  34. "src/rtl/prod2u_p4_i2c_stop_start_read.v",
  35. "src/top/prod2u_p4_normal_v3_top.v",
  36. )
  37. PROTOCOL_PATH = Path("docs/prod2u-door-temp-protocol.zh-CN.md")
  38. REQUIREMENTS_PATH = Path("projects/prod2u-door-temp/requirements.zh-CN.md")
  39. VERIFICATION_TARGETS_PATH = Path("config/prod2u_p4_verification_targets_v1.json")
  40. def new_run_id() -> str:
  41. return uuid.uuid4().hex
  42. def sha256_file(path: Path) -> str:
  43. digest = hashlib.sha256()
  44. with Path(path).open("rb") as stream:
  45. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  46. digest.update(chunk)
  47. return digest.hexdigest()
  48. def _canonical_sha256(value: Mapping[str, Any]) -> str:
  49. encoded = json.dumps(dict(value), sort_keys=True, separators=(",", ":"), ensure_ascii=True)
  50. return hashlib.sha256(encoded.encode("ascii")).hexdigest()
  51. def _repo_root(root: Path | None = None) -> Path:
  52. return Path(root or Path(__file__).resolve().parents[1]).resolve()
  53. def build_source_manifest(root: Path | None = None) -> dict[str, Any]:
  54. repo = _repo_root(root)
  55. project_path = repo / PROJECT_PATH
  56. missing = [path for path in SOURCE_PATHS if not (repo / path).is_file()]
  57. if missing:
  58. raise FileNotFoundError(f"missing active source: {missing[0]}")
  59. source_hashes = {path: sha256_file(repo / path) for path in SOURCE_PATHS}
  60. payload = {
  61. "schema": "prod2u-simple-source-manifest-v1",
  62. "project_id": PROJECT_ID,
  63. "project": PROJECT_PATH.as_posix(),
  64. "project_sha256": sha256_file(project_path),
  65. "sources": list(SOURCE_PATHS),
  66. "source_sha256": source_hashes,
  67. }
  68. payload["manifest_sha256"] = _canonical_sha256(payload)
  69. return payload
  70. def current_commit8(root: Path | None = None) -> str:
  71. repo = _repo_root(root)
  72. result = subprocess.run(
  73. ["git", "rev-parse", "--short=8", "HEAD"],
  74. cwd=repo,
  75. check=True,
  76. capture_output=True,
  77. text=True,
  78. )
  79. commit = result.stdout.strip().lower()
  80. if not COMMIT_RE.fullmatch(commit):
  81. raise ValueError(f"unexpected commit: {commit}")
  82. return commit
  83. def _write_json(path: Path, value: Mapping[str, Any]) -> None:
  84. Path(path).parent.mkdir(parents=True, exist_ok=True)
  85. Path(path).write_text(json.dumps(dict(value), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
  86. def init_run(run_id: str, root: Path | None = None) -> Path:
  87. if not RUN_ID_RE.fullmatch(run_id):
  88. raise ValueError("run_id must be 32 lowercase hexadecimal characters")
  89. repo = _repo_root(root)
  90. run_root = repo / "runs" / run_id
  91. run_root.mkdir(parents=True, exist_ok=True)
  92. _write_json(
  93. run_root / "plan.json",
  94. {
  95. "schema": "prod2u-simple-run-plan-v1",
  96. "run_id": run_id,
  97. "project_id": PROJECT_ID,
  98. "status": "DESIGN_FROZEN",
  99. "authority": "CPLD_多项目_UART协议_项目适配_Codex并行Harness_详细设计_v1.0.md",
  100. "hardware_access": {"com": False, "jtag": False, "programming": False, "drivers": False},
  101. },
  102. )
  103. _write_json(run_root / "source-manifest.json", build_source_manifest(repo))
  104. return run_root
  105. def create_unverified_package(
  106. *,
  107. bitstream: Path,
  108. project: Path,
  109. commit: str,
  110. run_id: str,
  111. output_root: Path,
  112. td_receipt: Path | None = None,
  113. ) -> Path:
  114. if not COMMIT_RE.fullmatch(commit):
  115. raise ValueError("commit must be 8 lowercase hexadecimal characters")
  116. if not RUN_ID_RE.fullmatch(run_id):
  117. raise ValueError("run_id must be 32 lowercase hexadecimal characters")
  118. bitstream = Path(bitstream)
  119. project = Path(project)
  120. if not bitstream.is_file() or bitstream.stat().st_size == 0:
  121. raise FileNotFoundError(f"bitstream is missing or empty: {bitstream}")
  122. if not project.is_file():
  123. raise FileNotFoundError(f"project is missing: {project}")
  124. bitstream_sha256 = sha256_file(bitstream)
  125. package = Path(output_root) / PROJECT_ID / f"{commit}-{bitstream_sha256[:16]}"
  126. package.mkdir(parents=True, exist_ok=True)
  127. package_bitstream = package / bitstream.name
  128. package_project = package / "project.json"
  129. shutil.copy2(bitstream, package_bitstream)
  130. shutil.copy2(project, package_project)
  131. repo = _repo_root()
  132. artifacts = {
  133. "protocol.md": repo / PROTOCOL_PATH,
  134. "requirements.zh-CN.md": repo / REQUIREMENTS_PATH,
  135. "verification_targets.json": repo / VERIFICATION_TARGETS_PATH,
  136. }
  137. for name, source in artifacts.items():
  138. if not source.is_file():
  139. raise FileNotFoundError(f"package source is missing: {source}")
  140. shutil.copy2(source, package / name)
  141. _write_json(package / "source_manifest.json", build_source_manifest(repo))
  142. if td_receipt is not None:
  143. receipt = Path(td_receipt)
  144. if not receipt.is_file():
  145. raise FileNotFoundError(f"TD receipt is missing: {receipt}")
  146. shutil.copy2(receipt, package / "td_receipt.json")
  147. (package / "project_config_sha256.txt").write_text(
  148. sha256_file(package_project) + "\n", encoding="ascii", newline="\n"
  149. )
  150. (package / "bitstream_sha256.txt").write_text(
  151. sha256_file(package_bitstream) + "\n", encoding="ascii", newline="\n"
  152. )
  153. file_sha256 = {
  154. path.relative_to(package).as_posix(): sha256_file(path)
  155. for path in sorted(package.iterdir())
  156. if path.is_file() and path.name != "package_manifest.json"
  157. }
  158. manifest = {
  159. "schema": "prod2u-simple-package-manifest-v1",
  160. "status": "UNVERIFIED",
  161. "run_id": run_id,
  162. "project_id": PROJECT_ID,
  163. "commit": commit,
  164. "created_at": datetime.now(timezone.utc).isoformat(),
  165. "bitstream": package_bitstream.name,
  166. "bitstream_sha256": sha256_file(package_bitstream),
  167. "project": "project.json",
  168. "project_sha256": sha256_file(package_project),
  169. "td_receipt": "td_receipt.json" if td_receipt is not None else None,
  170. "td_receipt_sha256": (
  171. sha256_file(package / "td_receipt.json")
  172. if td_receipt is not None
  173. else None
  174. ),
  175. "file_sha256": file_sha256,
  176. "hardware_validation": "not_run",
  177. }
  178. _write_json(package / "package_manifest.json", manifest)
  179. return package
  180. def main() -> int:
  181. import argparse
  182. parser = argparse.ArgumentParser(description=__doc__)
  183. sub = parser.add_subparsers(dest="command", required=True)
  184. sub.add_parser("run-id")
  185. init = sub.add_parser("init")
  186. init.add_argument("--run-id", required=True)
  187. init.add_argument("--root", type=Path)
  188. manifest = sub.add_parser("manifest")
  189. manifest.add_argument("--root", type=Path)
  190. package = sub.add_parser("package")
  191. package.add_argument("--bitstream", type=Path, required=True)
  192. package.add_argument("--project", type=Path, default=PROJECT_PATH)
  193. package.add_argument("--commit", required=True)
  194. package.add_argument("--run-id", required=True)
  195. package.add_argument("--output-root", type=Path, default=Path("dist"))
  196. package.add_argument("--td-receipt", type=Path)
  197. args = parser.parse_args()
  198. if args.command == "run-id":
  199. print(new_run_id())
  200. elif args.command == "init":
  201. print(init_run(args.run_id, args.root))
  202. elif args.command == "manifest":
  203. print(json.dumps(build_source_manifest(args.root), indent=2, sort_keys=True))
  204. else:
  205. print(create_unverified_package(
  206. bitstream=args.bitstream,
  207. project=args.project,
  208. commit=args.commit,
  209. run_id=args.run_id,
  210. output_root=args.output_root,
  211. td_receipt=args.td_receipt,
  212. ))
  213. return 0
  214. if __name__ == "__main__":
  215. raise SystemExit(main())