codex_harness.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. PACKAGE_INFO_SCHEMA = "prod2u-p4-normal-v3-folder-package-info-v3"
  41. PACKAGE_MANIFEST_SCHEMA = "prod2u-simple-package-manifest-v2"
  42. RUNTIME_PROFILE = "prod2u-door-temp-115200-v1"
  43. def _receipt_payload(*, name: str, run_id: str, commit: str, bitstream_sha256: str) -> dict[str, Any]:
  44. return {
  45. "schema": f"prod2u-p4-normal-v3-{name}-receipt-v1",
  46. "status": "not_run",
  47. "verification_run_id": run_id,
  48. "commit": commit,
  49. "bitstream_sha256": bitstream_sha256,
  50. "authority_boundary": "Offline package placeholder. No COM, JTAG, programming, or board action.",
  51. }
  52. def _package_file_hashes(package: Path) -> dict[str, str]:
  53. excluded = {
  54. "package-info.json",
  55. "package_manifest.json",
  56. "evidence/package-selftest-result.json",
  57. }
  58. return {
  59. path.relative_to(package).as_posix(): sha256_file(path)
  60. for path in sorted(package.rglob("*"))
  61. if path.is_file() and path.relative_to(package).as_posix() not in excluded
  62. }
  63. def new_run_id() -> str:
  64. return uuid.uuid4().hex
  65. def sha256_file(path: Path) -> str:
  66. digest = hashlib.sha256()
  67. with Path(path).open("rb") as stream:
  68. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  69. digest.update(chunk)
  70. return digest.hexdigest()
  71. def _canonical_sha256(value: Mapping[str, Any]) -> str:
  72. encoded = json.dumps(dict(value), sort_keys=True, separators=(",", ":"), ensure_ascii=True)
  73. return hashlib.sha256(encoded.encode("ascii")).hexdigest()
  74. def _repo_root(root: Path | None = None) -> Path:
  75. return Path(root or Path(__file__).resolve().parents[1]).resolve()
  76. def build_source_manifest(root: Path | None = None) -> dict[str, Any]:
  77. repo = _repo_root(root)
  78. project_path = repo / PROJECT_PATH
  79. missing = [path for path in SOURCE_PATHS if not (repo / path).is_file()]
  80. if missing:
  81. raise FileNotFoundError(f"missing active source: {missing[0]}")
  82. source_hashes = {path: sha256_file(repo / path) for path in SOURCE_PATHS}
  83. payload = {
  84. "schema": "prod2u-simple-source-manifest-v1",
  85. "project_id": PROJECT_ID,
  86. "project": PROJECT_PATH.as_posix(),
  87. "project_sha256": sha256_file(project_path),
  88. "sources": list(SOURCE_PATHS),
  89. "source_sha256": source_hashes,
  90. }
  91. payload["manifest_sha256"] = _canonical_sha256(payload)
  92. return payload
  93. def current_commit8(root: Path | None = None) -> str:
  94. repo = _repo_root(root)
  95. result = subprocess.run(
  96. ["git", "rev-parse", "--short=8", "HEAD"],
  97. cwd=repo,
  98. check=True,
  99. capture_output=True,
  100. text=True,
  101. )
  102. commit = result.stdout.strip().lower()
  103. if not COMMIT_RE.fullmatch(commit):
  104. raise ValueError(f"unexpected commit: {commit}")
  105. return commit
  106. def _write_json(path: Path, value: Mapping[str, Any]) -> None:
  107. Path(path).parent.mkdir(parents=True, exist_ok=True)
  108. Path(path).write_text(json.dumps(dict(value), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
  109. def init_run(run_id: str, root: Path | None = None) -> Path:
  110. if not RUN_ID_RE.fullmatch(run_id):
  111. raise ValueError("run_id must be 32 lowercase hexadecimal characters")
  112. repo = _repo_root(root)
  113. run_root = repo / "runs" / run_id
  114. run_root.mkdir(parents=True, exist_ok=True)
  115. _write_json(
  116. run_root / "plan.json",
  117. {
  118. "schema": "prod2u-simple-run-plan-v1",
  119. "run_id": run_id,
  120. "project_id": PROJECT_ID,
  121. "status": "DESIGN_FROZEN",
  122. "authority": "CPLD_多项目_UART协议_项目适配_Codex并行Harness_详细设计_v1.0.md",
  123. "hardware_access": {"com": False, "jtag": False, "programming": False, "drivers": False},
  124. },
  125. )
  126. _write_json(run_root / "source-manifest.json", build_source_manifest(repo))
  127. return run_root
  128. def create_unverified_package(
  129. *,
  130. bitstream: Path,
  131. project: Path,
  132. commit: str,
  133. run_id: str,
  134. output_root: Path,
  135. td_receipt: Path | None = None,
  136. ) -> Path:
  137. if not COMMIT_RE.fullmatch(commit):
  138. raise ValueError("commit must be 8 lowercase hexadecimal characters")
  139. if not RUN_ID_RE.fullmatch(run_id):
  140. raise ValueError("run_id must be 32 lowercase hexadecimal characters")
  141. bitstream = Path(bitstream)
  142. project = Path(project)
  143. if not bitstream.is_file() or bitstream.stat().st_size == 0:
  144. raise FileNotFoundError(f"bitstream is missing or empty: {bitstream}")
  145. if not project.is_file():
  146. raise FileNotFoundError(f"project is missing: {project}")
  147. bitstream_sha256 = sha256_file(bitstream)
  148. package = Path(output_root) / PROJECT_ID / f"{commit}-{bitstream_sha256[:16]}"
  149. package.mkdir(parents=True, exist_ok=True)
  150. package_bitstream = package / "fw.bit"
  151. package_project = package / "project.json"
  152. evidence = package / "evidence"
  153. evidence.mkdir(parents=True, exist_ok=True)
  154. shutil.copy2(bitstream, package_bitstream)
  155. shutil.copy2(project, package_project)
  156. repo = _repo_root()
  157. artifacts = {
  158. "protocol.md": repo / PROTOCOL_PATH,
  159. "requirements.zh-CN.md": repo / REQUIREMENTS_PATH,
  160. "verification_targets.json": repo / VERIFICATION_TARGETS_PATH,
  161. }
  162. for name, source in artifacts.items():
  163. if not source.is_file():
  164. raise FileNotFoundError(f"package source is missing: {source}")
  165. shutil.copy2(source, package / name)
  166. source_manifest = build_source_manifest(repo)
  167. _write_json(package / "source_manifest.json", source_manifest)
  168. if td_receipt is not None:
  169. receipt = Path(td_receipt)
  170. if not receipt.is_file():
  171. raise FileNotFoundError(f"TD receipt is missing: {receipt}")
  172. shutil.copy2(receipt, evidence / "td-primary-receipt.json")
  173. else:
  174. _write_json(
  175. evidence / "td-primary-receipt.json",
  176. _receipt_payload(name="td-primary", run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256),
  177. )
  178. _write_json(
  179. evidence / "td-confirmation-receipt.json",
  180. _receipt_payload(name="td-confirmation", run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256),
  181. )
  182. for name in ("python-unit", "icarus", "verilator", "cocotb", "formal"):
  183. _write_json(
  184. evidence / f"{name}-receipt.json",
  185. _receipt_payload(name=name, run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256),
  186. )
  187. _write_json(
  188. evidence / "package-selftest-result.json",
  189. {
  190. "schema": "prod2u-p4-normal-v3-package-selftest-result-v1",
  191. "status": "not_run",
  192. "verification_run_id": run_id,
  193. "commit": commit,
  194. "bitstream_sha256": bitstream_sha256,
  195. },
  196. )
  197. (package / "project_config_sha256.txt").write_text(
  198. sha256_file(package_project) + "\n", encoding="ascii", newline="\n"
  199. )
  200. (package / "bitstream_sha256.txt").write_text(
  201. sha256_file(package_bitstream) + "\n", encoding="ascii", newline="\n"
  202. )
  203. td_status = "not_run"
  204. try:
  205. td_value = json.loads((evidence / "td-primary-receipt.json").read_text(encoding="utf-8-sig"))
  206. if isinstance(td_value, Mapping) and td_value.get("status") in {"pass", "fail", "blocked", "not_run"}:
  207. td_status = str(td_value["status"])
  208. except (OSError, UnicodeError, json.JSONDecodeError):
  209. td_status = "fail"
  210. validation_summary = {
  211. "schema": "prod2u-p4-normal-v3-validation-summary-v1",
  212. "status": "UNVERIFIED",
  213. "delivery_mode": "urgent_single_td",
  214. "verification_complete": False,
  215. "confirmation_td_present": True,
  216. "verification_run_id": run_id,
  217. "commit": commit,
  218. "bitstream_sha256": bitstream_sha256,
  219. "project_config_sha256": sha256_file(package_project),
  220. "layers": {
  221. "python_unit": {"status": "not_run"},
  222. "icarus": {"status": "not_run"},
  223. "verilator": {"status": "not_run"},
  224. "cocotb": {"status": "not_run"},
  225. "formal": {"status": "not_run"},
  226. "td_primary": {"status": td_status},
  227. "td_confirmation": {"status": "not_run"},
  228. "td_confirmation_artifacts": {"status": "not_run"},
  229. "td_confirmation_bitstream": {"status": "not_run"},
  230. "td_confirmation_synthesis": {"status": "not_run"},
  231. "td_confirmation_manifest": {"status": "not_run"},
  232. "resource_confirmation": {"status": "not_run"},
  233. },
  234. "hardware_validation": "not_run",
  235. }
  236. _write_json(evidence / "validation-summary.json", validation_summary)
  237. _write_json(package / "verification_summary.json", validation_summary)
  238. package_info = {
  239. "schema": PACKAGE_INFO_SCHEMA,
  240. "profile": RUNTIME_PROFILE,
  241. "project_id": PROJECT_ID,
  242. "delivery_mode": "urgent_single_td",
  243. "verification_complete": False,
  244. "confirmation_td_present": True,
  245. "verification_run_id": run_id,
  246. "commit": commit,
  247. "bitstream": "fw.bit",
  248. "bitstream_sha256": bitstream_sha256,
  249. "project": "project.json",
  250. "project_sha256": sha256_file(package_project),
  251. "project_config_sha256": sha256_file(package_project),
  252. "source_manifest_sha256": sha256_file(package / "source_manifest.json"),
  253. "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
  254. "confirmation_td_receipt_sha256": sha256_file(evidence / "td-confirmation-receipt.json"),
  255. "validation_summary_sha256": sha256_file(evidence / "validation-summary.json"),
  256. "package_selftest_result_sha256": sha256_file(evidence / "package-selftest-result.json"),
  257. "file_sha256": _package_file_hashes(package),
  258. "hardware_validation": "not_run",
  259. }
  260. _write_json(package / "package-info.json", package_info)
  261. manifest = {
  262. "schema": PACKAGE_MANIFEST_SCHEMA,
  263. "status": "UNVERIFIED",
  264. "run_id": run_id,
  265. "project_id": PROJECT_ID,
  266. "commit": commit,
  267. "created_at": datetime.now(timezone.utc).isoformat(),
  268. "bitstream": "fw.bit",
  269. "bitstream_sha256": sha256_file(package_bitstream),
  270. "project": "project.json",
  271. "project_sha256": sha256_file(package_project),
  272. "package_info": "package-info.json",
  273. "package_info_sha256": sha256_file(package / "package-info.json"),
  274. "td_receipt": "evidence/td-primary-receipt.json",
  275. "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
  276. "file_sha256": _package_file_hashes(package),
  277. "hardware_validation": "not_run",
  278. }
  279. _write_json(package / "package_manifest.json", manifest)
  280. return package
  281. def main() -> int:
  282. import argparse
  283. parser = argparse.ArgumentParser(description=__doc__)
  284. sub = parser.add_subparsers(dest="command", required=True)
  285. sub.add_parser("run-id")
  286. init = sub.add_parser("init")
  287. init.add_argument("--run-id", required=True)
  288. init.add_argument("--root", type=Path)
  289. manifest = sub.add_parser("manifest")
  290. manifest.add_argument("--root", type=Path)
  291. package = sub.add_parser("package")
  292. package.add_argument("--bitstream", type=Path, required=True)
  293. package.add_argument("--project", type=Path, default=PROJECT_PATH)
  294. package.add_argument("--commit", required=True)
  295. package.add_argument("--run-id", required=True)
  296. package.add_argument("--output-root", type=Path, default=Path("dist"))
  297. package.add_argument("--td-receipt", type=Path)
  298. args = parser.parse_args()
  299. if args.command == "run-id":
  300. print(new_run_id())
  301. elif args.command == "init":
  302. print(init_run(args.run_id, args.root))
  303. elif args.command == "manifest":
  304. print(json.dumps(build_source_manifest(args.root), indent=2, sort_keys=True))
  305. else:
  306. print(create_unverified_package(
  307. bitstream=args.bitstream,
  308. project=args.project,
  309. commit=args.commit,
  310. run_id=args.run_id,
  311. output_root=args.output_root,
  312. td_receipt=args.td_receipt,
  313. ))
  314. return 0
  315. if __name__ == "__main__":
  316. raise SystemExit(main())