codex_harness.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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, project_config_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. "project_config_sha256": project_config_sha256,
  51. "authority_boundary": "Offline package placeholder. No COM, JTAG, programming, or board action.",
  52. }
  53. def _copy_bound_receipt(
  54. source: Path,
  55. destination: Path,
  56. *,
  57. run_id: str,
  58. commit: str,
  59. bitstream_sha256: str,
  60. project_config_sha256: str,
  61. ) -> dict[str, Any]:
  62. try:
  63. value = json.loads(Path(source).read_text(encoding="utf-8-sig"))
  64. except (OSError, UnicodeError, json.JSONDecodeError) as exc:
  65. raise ValueError(f"receipt is not readable JSON: {source}") from exc
  66. if not isinstance(value, dict):
  67. raise ValueError(f"receipt root must be an object: {source}")
  68. bindings = {
  69. "verification_run_id": run_id,
  70. "commit": commit,
  71. "bitstream_sha256": bitstream_sha256,
  72. "project_config_sha256": project_config_sha256,
  73. }
  74. for field, expected in bindings.items():
  75. observed = value.get(field)
  76. if observed not in {None, "", expected}:
  77. raise ValueError(f"receipt binding mismatch for {field}: {source}")
  78. value[field] = expected
  79. value["source_receipt_sha256"] = sha256_file(source)
  80. _write_json(destination, value)
  81. return value
  82. def _package_file_hashes(package: Path) -> dict[str, str]:
  83. excluded = {
  84. "package-info.json",
  85. "package_manifest.json",
  86. "evidence/package-selftest-result.json",
  87. }
  88. return {
  89. path.relative_to(package).as_posix(): sha256_file(path)
  90. for path in sorted(package.rglob("*"))
  91. if path.is_file() and path.relative_to(package).as_posix() not in excluded
  92. }
  93. def new_run_id() -> str:
  94. return uuid.uuid4().hex
  95. def sha256_file(path: Path) -> str:
  96. digest = hashlib.sha256()
  97. with Path(path).open("rb") as stream:
  98. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  99. digest.update(chunk)
  100. return digest.hexdigest()
  101. def _canonical_sha256(value: Mapping[str, Any]) -> str:
  102. encoded = json.dumps(dict(value), sort_keys=True, separators=(",", ":"), ensure_ascii=True)
  103. return hashlib.sha256(encoded.encode("ascii")).hexdigest()
  104. def _repo_root(root: Path | None = None) -> Path:
  105. return Path(root or Path(__file__).resolve().parents[1]).resolve()
  106. def build_source_manifest(root: Path | None = None) -> dict[str, Any]:
  107. repo = _repo_root(root)
  108. project_path = repo / PROJECT_PATH
  109. missing = [path for path in SOURCE_PATHS if not (repo / path).is_file()]
  110. if missing:
  111. raise FileNotFoundError(f"missing active source: {missing[0]}")
  112. source_hashes = {path: sha256_file(repo / path) for path in SOURCE_PATHS}
  113. payload = {
  114. "schema": "prod2u-simple-source-manifest-v1",
  115. "project_id": PROJECT_ID,
  116. "project": PROJECT_PATH.as_posix(),
  117. "project_sha256": sha256_file(project_path),
  118. "sources": list(SOURCE_PATHS),
  119. "source_sha256": source_hashes,
  120. }
  121. payload["manifest_sha256"] = _canonical_sha256(payload)
  122. return payload
  123. def current_commit8(root: Path | None = None) -> str:
  124. repo = _repo_root(root)
  125. result = subprocess.run(
  126. ["git", "rev-parse", "--short=8", "HEAD"],
  127. cwd=repo,
  128. check=True,
  129. capture_output=True,
  130. text=True,
  131. )
  132. commit = result.stdout.strip().lower()
  133. if not COMMIT_RE.fullmatch(commit):
  134. raise ValueError(f"unexpected commit: {commit}")
  135. return commit
  136. def _write_json(path: Path, value: Mapping[str, Any]) -> None:
  137. Path(path).parent.mkdir(parents=True, exist_ok=True)
  138. Path(path).write_text(json.dumps(dict(value), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
  139. def init_run(run_id: str, root: Path | None = None) -> Path:
  140. if not RUN_ID_RE.fullmatch(run_id):
  141. raise ValueError("run_id must be 32 lowercase hexadecimal characters")
  142. repo = _repo_root(root)
  143. run_root = repo / "runs" / run_id
  144. run_root.mkdir(parents=True, exist_ok=True)
  145. _write_json(
  146. run_root / "plan.json",
  147. {
  148. "schema": "prod2u-simple-run-plan-v1",
  149. "run_id": run_id,
  150. "project_id": PROJECT_ID,
  151. "status": "DESIGN_FROZEN",
  152. "authority": "CPLD_多项目_UART协议_项目适配_Codex并行Harness_详细设计_v1.0.md",
  153. "hardware_access": {"com": False, "jtag": False, "programming": False, "drivers": False},
  154. },
  155. )
  156. _write_json(run_root / "source-manifest.json", build_source_manifest(repo))
  157. return run_root
  158. def create_unverified_package(
  159. *,
  160. bitstream: Path,
  161. project: Path,
  162. commit: str,
  163. run_id: str,
  164. output_root: Path,
  165. td_receipt: Path | None = None,
  166. verification_receipts: Mapping[str, Path] | None = None,
  167. ) -> Path:
  168. if not COMMIT_RE.fullmatch(commit):
  169. raise ValueError("commit must be 8 lowercase hexadecimal characters")
  170. if not RUN_ID_RE.fullmatch(run_id):
  171. raise ValueError("run_id must be 32 lowercase hexadecimal characters")
  172. bitstream = Path(bitstream)
  173. project = Path(project)
  174. if not bitstream.is_file() or bitstream.stat().st_size == 0:
  175. raise FileNotFoundError(f"bitstream is missing or empty: {bitstream}")
  176. if not project.is_file():
  177. raise FileNotFoundError(f"project is missing: {project}")
  178. bitstream_sha256 = sha256_file(bitstream)
  179. package = Path(output_root) / PROJECT_ID / f"{commit}-{bitstream_sha256[:16]}"
  180. package.mkdir(parents=True, exist_ok=True)
  181. package_bitstream = package / "fw.bit"
  182. package_project = package / "project.json"
  183. evidence = package / "evidence"
  184. evidence.mkdir(parents=True, exist_ok=True)
  185. shutil.copy2(bitstream, package_bitstream)
  186. shutil.copy2(project, package_project)
  187. repo = _repo_root()
  188. artifacts = {
  189. "protocol.md": repo / PROTOCOL_PATH,
  190. "requirements.zh-CN.md": repo / REQUIREMENTS_PATH,
  191. "verification_targets.json": repo / VERIFICATION_TARGETS_PATH,
  192. }
  193. for name, source in artifacts.items():
  194. if not source.is_file():
  195. raise FileNotFoundError(f"package source is missing: {source}")
  196. shutil.copy2(source, package / name)
  197. project_config_sha256 = sha256_file(package_project)
  198. source_manifest = build_source_manifest(repo)
  199. _write_json(package / "source_manifest.json", source_manifest)
  200. receipt_sources = dict(verification_receipts or {})
  201. if td_receipt is not None:
  202. receipt = Path(td_receipt)
  203. if not receipt.is_file():
  204. raise FileNotFoundError(f"TD receipt is missing: {receipt}")
  205. _copy_bound_receipt(
  206. receipt,
  207. evidence / "td-primary-receipt.json",
  208. run_id=run_id,
  209. commit=commit,
  210. bitstream_sha256=bitstream_sha256,
  211. project_config_sha256=project_config_sha256,
  212. )
  213. else:
  214. _write_json(
  215. evidence / "td-primary-receipt.json",
  216. _receipt_payload(name="td-primary", run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256),
  217. )
  218. receipt_specs = {
  219. "td-confirmation": "td-confirmation-receipt.json",
  220. "python-unit": "python-unit-receipt.json",
  221. "icarus": "icarus-receipt.json",
  222. "verilator": "verilator-receipt.json",
  223. "cocotb": "cocotb-receipt.json",
  224. "formal": "formal-receipt.json",
  225. }
  226. for name, filename in receipt_specs.items():
  227. source = receipt_sources.get(name)
  228. if source is not None:
  229. source_path = Path(source)
  230. if not source_path.is_file():
  231. raise FileNotFoundError(f"verification receipt is missing: {source_path}")
  232. _copy_bound_receipt(
  233. source_path,
  234. evidence / filename,
  235. run_id=run_id,
  236. commit=commit,
  237. bitstream_sha256=bitstream_sha256,
  238. project_config_sha256=project_config_sha256,
  239. )
  240. else:
  241. _write_json(
  242. evidence / filename,
  243. _receipt_payload(name=name, run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256),
  244. )
  245. _write_json(
  246. evidence / "package-selftest-result.json",
  247. {
  248. "schema": "prod2u-p4-normal-v3-package-selftest-result-v1",
  249. "status": "not_run",
  250. "verification_run_id": run_id,
  251. "commit": commit,
  252. "bitstream_sha256": bitstream_sha256,
  253. },
  254. )
  255. (package / "project_config_sha256.txt").write_text(
  256. sha256_file(package_project) + "\n", encoding="ascii", newline="\n"
  257. )
  258. (package / "bitstream_sha256.txt").write_text(
  259. sha256_file(package_bitstream) + "\n", encoding="ascii", newline="\n"
  260. )
  261. td_status = "not_run"
  262. td_synthesis_input_hash = None
  263. confirmation_bitstream_sha256 = None
  264. confirmation_synthesis_input_hash = None
  265. try:
  266. td_value = json.loads((evidence / "td-primary-receipt.json").read_text(encoding="utf-8-sig"))
  267. if isinstance(td_value, Mapping) and td_value.get("status") in {"pass", "fail", "blocked", "not_run"}:
  268. td_status = str(td_value["status"])
  269. td_synthesis_input_hash = td_value.get("synthesis_input_hash")
  270. except (OSError, UnicodeError, json.JSONDecodeError):
  271. td_status = "fail"
  272. try:
  273. confirmation_value = json.loads((evidence / "td-confirmation-receipt.json").read_text(encoding="utf-8-sig"))
  274. if isinstance(confirmation_value, Mapping) and confirmation_value.get("status") == "pass":
  275. confirmation_bitstream_sha256 = confirmation_value.get("bitstream_sha256")
  276. confirmation_synthesis_input_hash = confirmation_value.get("synthesis_input_hash")
  277. except (OSError, UnicodeError, json.JSONDecodeError):
  278. pass
  279. def receipt_status(filename: str) -> str:
  280. try:
  281. value = json.loads((evidence / filename).read_text(encoding="utf-8-sig"))
  282. except (OSError, UnicodeError, json.JSONDecodeError):
  283. return "fail"
  284. return str(value.get("status", "fail")) if isinstance(value, Mapping) else "fail"
  285. validation_summary = {
  286. "schema": "prod2u-p4-normal-v3-validation-summary-v1",
  287. "status": "UNVERIFIED",
  288. "delivery_mode": "urgent_single_td",
  289. "verification_complete": False,
  290. "confirmation_td_present": True,
  291. "verification_run_id": run_id,
  292. "commit": commit,
  293. "bitstream_sha256": bitstream_sha256,
  294. "project_config_sha256": sha256_file(package_project),
  295. "layers": {
  296. "python_unit": {"status": receipt_status("python-unit-receipt.json")},
  297. "icarus": {"status": receipt_status("icarus-receipt.json")},
  298. "verilator": {"status": receipt_status("verilator-receipt.json")},
  299. "cocotb": {"status": receipt_status("cocotb-receipt.json")},
  300. "formal": {"status": receipt_status("formal-receipt.json")},
  301. "td_primary": {"status": td_status},
  302. "td_confirmation": {"status": receipt_status("td-confirmation-receipt.json")},
  303. "td_confirmation_artifacts": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"},
  304. "td_confirmation_bitstream": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"},
  305. "td_confirmation_synthesis": {"status": "pass" if confirmation_synthesis_input_hash else "not_run"},
  306. "td_confirmation_manifest": {"status": "pass" if confirmation_synthesis_input_hash else "not_run"},
  307. "resource_confirmation": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"},
  308. },
  309. "hardware_validation": "not_run",
  310. }
  311. _write_json(evidence / "validation-summary.json", validation_summary)
  312. _write_json(package / "verification_summary.json", validation_summary)
  313. package_info = {
  314. "schema": PACKAGE_INFO_SCHEMA,
  315. "profile": RUNTIME_PROFILE,
  316. "project_id": PROJECT_ID,
  317. "delivery_mode": "urgent_single_td",
  318. "verification_complete": False,
  319. "confirmation_td_present": True,
  320. "verification_run_id": run_id,
  321. "commit": commit,
  322. "bitstream": "fw.bit",
  323. "bitstream_sha256": bitstream_sha256,
  324. "project": "project.json",
  325. "project_sha256": sha256_file(package_project),
  326. "project_config_sha256": sha256_file(package_project),
  327. "source_manifest_sha256": sha256_file(package / "source_manifest.json"),
  328. "synthesis_input_hash": td_synthesis_input_hash,
  329. "confirmation_bitstream_sha256": confirmation_bitstream_sha256,
  330. "confirmation_synthesis_input_hash": confirmation_synthesis_input_hash,
  331. "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
  332. "confirmation_td_receipt_sha256": sha256_file(evidence / "td-confirmation-receipt.json"),
  333. "validation_summary_sha256": sha256_file(evidence / "validation-summary.json"),
  334. "package_selftest_result_sha256": sha256_file(evidence / "package-selftest-result.json"),
  335. "file_sha256": _package_file_hashes(package),
  336. "hardware_validation": "not_run",
  337. }
  338. _write_json(package / "package-info.json", package_info)
  339. manifest = {
  340. "schema": PACKAGE_MANIFEST_SCHEMA,
  341. "status": "UNVERIFIED",
  342. "run_id": run_id,
  343. "project_id": PROJECT_ID,
  344. "commit": commit,
  345. "created_at": datetime.now(timezone.utc).isoformat(),
  346. "bitstream": "fw.bit",
  347. "bitstream_sha256": sha256_file(package_bitstream),
  348. "project": "project.json",
  349. "project_sha256": sha256_file(package_project),
  350. "package_info": "package-info.json",
  351. "package_info_sha256": sha256_file(package / "package-info.json"),
  352. "td_receipt": "evidence/td-primary-receipt.json",
  353. "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
  354. "file_sha256": _package_file_hashes(package),
  355. "hardware_validation": "not_run",
  356. }
  357. _write_json(package / "package_manifest.json", manifest)
  358. return package
  359. def main() -> int:
  360. import argparse
  361. parser = argparse.ArgumentParser(description=__doc__)
  362. sub = parser.add_subparsers(dest="command", required=True)
  363. sub.add_parser("run-id")
  364. init = sub.add_parser("init")
  365. init.add_argument("--run-id", required=True)
  366. init.add_argument("--root", type=Path)
  367. manifest = sub.add_parser("manifest")
  368. manifest.add_argument("--root", type=Path)
  369. package = sub.add_parser("package")
  370. package.add_argument("--bitstream", type=Path, required=True)
  371. package.add_argument("--project", type=Path, default=PROJECT_PATH)
  372. package.add_argument("--commit", required=True)
  373. package.add_argument("--run-id", required=True)
  374. package.add_argument("--output-root", type=Path, default=Path("dist"))
  375. package.add_argument("--td-receipt", type=Path)
  376. package.add_argument(
  377. "--receipt",
  378. action="append",
  379. default=[],
  380. metavar="NAME=PATH",
  381. help="bind an additional receipt under evidence (NAME: python-unit, icarus, verilator, cocotb, formal, td-confirmation)",
  382. )
  383. args = parser.parse_args()
  384. if args.command == "run-id":
  385. print(new_run_id())
  386. elif args.command == "init":
  387. print(init_run(args.run_id, args.root))
  388. elif args.command == "manifest":
  389. print(json.dumps(build_source_manifest(args.root), indent=2, sort_keys=True))
  390. else:
  391. receipt_map: dict[str, Path] = {}
  392. for item in args.receipt:
  393. name, separator, raw_path = item.partition("=")
  394. if not separator or not name or not raw_path:
  395. raise SystemExit(f"invalid --receipt value: {item!r}; expected NAME=PATH")
  396. receipt_map[name] = Path(raw_path)
  397. print(create_unverified_package(
  398. bitstream=args.bitstream,
  399. project=args.project,
  400. commit=args.commit,
  401. run_id=args.run_id,
  402. output_root=args.output_root,
  403. td_receipt=args.td_receipt,
  404. verification_receipts=receipt_map,
  405. ))
  406. return 0
  407. if __name__ == "__main__":
  408. raise SystemExit(main())