codex_harness.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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, PurePosixPath
  12. from typing import Any, Iterable, Mapping, Sequence
  13. RUN_ID_RE = re.compile(r"^[0-9a-f]{32}$")
  14. COMMIT_RE = re.compile(r"^[0-9a-f]{8}$")
  15. FULL_COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")
  16. AGENT_TASK_REPORT_SCHEMA = "prod2u-native-agent-task-report-v1"
  17. AGENT_SELECTION_SOURCES = frozenset(
  18. {"explicit", "inherited", "automatic", "default", "not_exposed", "unknown"}
  19. )
  20. AGENT_TASK_STATUSES = frozenset({"completed", "blocked", "failed", "integration_conflict"})
  21. PROJECT_ID = "prod2u-door-temp"
  22. PROJECT_PATH = Path("projects/prod2u-door-temp/project.json")
  23. SOURCE_PATHS = (
  24. "src/generated/prod2u_door_temp_params.vh",
  25. "src/common/uart_rx_byte.v",
  26. "src/common/uart_tx_byte.v",
  27. "src/common/crc16_serial.v",
  28. "src/common/frame_rx.v",
  29. "src/common/frame_tx.v",
  30. "src/common/payload_ram.v",
  31. "src/modules/output_target_ram.v",
  32. "src/modules/pwm_scheduler.v",
  33. "src/modules/door_motor_engine.v",
  34. "src/modules/i2c_word_reader.v",
  35. "src/modules/temperature_reader.v",
  36. "src/modules/temperature_ram.v",
  37. "src/project/command_controller.v",
  38. "src/project/project_adapter.v",
  39. "src/rtl/prod2u_por.v",
  40. "src/rtl/prod2u_p4_i2c_stop_start_read.v",
  41. "src/top/prod2u_p4_normal_v3_top.v",
  42. )
  43. PROTOCOL_PATH = Path("docs/prod2u-door-temp-protocol.zh-CN.md")
  44. REQUIREMENTS_PATH = Path("projects/prod2u-door-temp/requirements.zh-CN.md")
  45. VERIFICATION_TARGETS_PATH = Path("config/prod2u_p4_verification_targets_v1.json")
  46. PACKAGE_INFO_SCHEMA = "prod2u-p4-normal-v3-folder-package-info-v3"
  47. PACKAGE_MANIFEST_SCHEMA = "prod2u-simple-package-manifest-v2"
  48. RUNTIME_PROFILE = "prod2u-door-temp-115200-v1"
  49. def _receipt_payload(*, name: str, run_id: str, commit: str, bitstream_sha256: str, project_config_sha256: str) -> dict[str, Any]:
  50. return {
  51. "schema": f"prod2u-p4-normal-v3-{name}-receipt-v1",
  52. "status": "not_run",
  53. "verification_run_id": run_id,
  54. "commit": commit,
  55. "bitstream_sha256": bitstream_sha256,
  56. "project_config_sha256": project_config_sha256,
  57. "authority_boundary": "Offline package placeholder. No COM, JTAG, programming, or board action.",
  58. }
  59. def _copy_bound_receipt(
  60. source: Path,
  61. destination: Path,
  62. *,
  63. run_id: str,
  64. commit: str,
  65. bitstream_sha256: str,
  66. project_config_sha256: str,
  67. ) -> dict[str, Any]:
  68. try:
  69. value = json.loads(Path(source).read_text(encoding="utf-8-sig"))
  70. except (OSError, UnicodeError, json.JSONDecodeError) as exc:
  71. raise ValueError(f"receipt is not readable JSON: {source}") from exc
  72. if not isinstance(value, dict):
  73. raise ValueError(f"receipt root must be an object: {source}")
  74. bindings = {
  75. "verification_run_id": run_id,
  76. "commit": commit,
  77. "bitstream_sha256": bitstream_sha256,
  78. "project_config_sha256": project_config_sha256,
  79. }
  80. for field, expected in bindings.items():
  81. observed = value.get(field)
  82. if observed not in {None, "", expected}:
  83. raise ValueError(f"receipt binding mismatch for {field}: {source}")
  84. value[field] = expected
  85. value["source_receipt_sha256"] = sha256_file(source)
  86. _write_json(destination, value)
  87. return value
  88. def _package_file_hashes(package: Path) -> dict[str, str]:
  89. excluded = {
  90. "package-info.json",
  91. "package_manifest.json",
  92. "evidence/package-selftest-result.json",
  93. }
  94. return {
  95. path.relative_to(package).as_posix(): sha256_file(path)
  96. for path in sorted(package.rglob("*"))
  97. if path.is_file() and path.relative_to(package).as_posix() not in excluded
  98. }
  99. def new_run_id() -> str:
  100. return uuid.uuid4().hex
  101. def sha256_file(path: Path) -> str:
  102. digest = hashlib.sha256()
  103. with Path(path).open("rb") as stream:
  104. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  105. digest.update(chunk)
  106. return digest.hexdigest()
  107. def _canonical_sha256(value: Mapping[str, Any]) -> str:
  108. encoded = json.dumps(dict(value), sort_keys=True, separators=(",", ":"), ensure_ascii=True)
  109. return hashlib.sha256(encoded.encode("ascii")).hexdigest()
  110. def _repo_root(root: Path | None = None) -> Path:
  111. return Path(root or Path(__file__).resolve().parents[1]).resolve()
  112. def _run_git(
  113. root: Path,
  114. args: Sequence[str],
  115. *,
  116. timeout_seconds: float = 10.0,
  117. check: bool = True,
  118. ) -> subprocess.CompletedProcess[bytes]:
  119. if timeout_seconds <= 0:
  120. raise ValueError("timeout_seconds must be positive")
  121. values = [str(value) for value in args]
  122. if not values or any(not value for value in values):
  123. raise ValueError("git args must be a non-empty sequence of non-empty strings")
  124. return subprocess.run(
  125. ["git", "-C", str(_repo_root(root)), *values],
  126. capture_output=True,
  127. check=check,
  128. shell=False,
  129. text=False,
  130. timeout=timeout_seconds,
  131. )
  132. def build_source_manifest(root: Path | None = None) -> dict[str, Any]:
  133. repo = _repo_root(root)
  134. project_path = repo / PROJECT_PATH
  135. missing = [path for path in SOURCE_PATHS if not (repo / path).is_file()]
  136. if missing:
  137. raise FileNotFoundError(f"missing active source: {missing[0]}")
  138. source_hashes = {path: sha256_file(repo / path) for path in SOURCE_PATHS}
  139. payload = {
  140. "schema": "prod2u-simple-source-manifest-v1",
  141. "project_id": PROJECT_ID,
  142. "project": PROJECT_PATH.as_posix(),
  143. "project_sha256": sha256_file(project_path),
  144. "sources": list(SOURCE_PATHS),
  145. "source_sha256": source_hashes,
  146. }
  147. payload["manifest_sha256"] = _canonical_sha256(payload)
  148. return payload
  149. def current_commit8(root: Path | None = None) -> str:
  150. repo = _repo_root(root)
  151. result = _run_git(repo, ["rev-parse", "--short=8", "HEAD"])
  152. commit = result.stdout.decode("ascii").strip().lower()
  153. if not COMMIT_RE.fullmatch(commit):
  154. raise ValueError(f"unexpected commit: {commit}")
  155. return commit
  156. def _validate_full_commit(value: Any, field: str, *, allow_none: bool = False) -> str | None:
  157. if value is None and allow_none:
  158. return None
  159. if not isinstance(value, str) or not FULL_COMMIT_RE.fullmatch(value):
  160. raise ValueError(f"{field} must be a 40-character lowercase hexadecimal commit")
  161. return value
  162. def _validate_observation_fields(native_thread: Mapping[str, Any]) -> None:
  163. if native_thread.get("model_policy") != "unconstrained":
  164. raise ValueError("native_thread.model_policy must be unconstrained")
  165. if native_thread.get("reasoning_effort_policy") != "unconstrained":
  166. raise ValueError("native_thread.reasoning_effort_policy must be unconstrained")
  167. for field in ("model_selection_source", "effort_selection_source"):
  168. value = native_thread.get(field)
  169. if value is not None and value not in AGENT_SELECTION_SOURCES:
  170. raise ValueError(f"{field} has an unsupported selection source")
  171. observation_source = native_thread.get("observation_source")
  172. if observation_source is not None and not isinstance(observation_source, str):
  173. raise ValueError("observation_source must be a string or null")
  174. for field in ("observed_model", "observed_reasoning_effort", "observed_permission_mode"):
  175. value = native_thread.get(field)
  176. if value is not None and not isinstance(value, str):
  177. raise ValueError(f"{field} must be a string or null")
  178. def _normalise_repo_path(value: Any, *, owned: bool = False) -> str:
  179. if not isinstance(value, str) or not value:
  180. raise ValueError("path must be a non-empty string")
  181. raw = value.replace("\\", "/")
  182. if raw.startswith("/") or re.match(r"^[A-Za-z]:", raw):
  183. raise ValueError(f"path must be relative: {value}")
  184. if any(part == ".." for part in PurePosixPath(raw).parts):
  185. raise ValueError(f"path contains parent traversal: {value}")
  186. normalised = PurePosixPath(raw).as_posix()
  187. if normalised in {"", "."}:
  188. raise ValueError(f"path is not a file or directory: {value}")
  189. if owned and any(token in normalised for token in "*?["):
  190. raise ValueError("owned paths must not contain glob syntax")
  191. return normalised
  192. def _normalise_owned_path(value: Any) -> str:
  193. directory = isinstance(value, str) and value.replace("\\", "/").endswith("/")
  194. normalised = _normalise_repo_path(value, owned=True)
  195. return normalised.rstrip("/") + "/" if directory else normalised
  196. def parse_name_status_z(payload: bytes) -> list[tuple[str, tuple[str, ...]]]:
  197. tokens = payload.split(b"\0")
  198. if tokens and tokens[-1] == b"":
  199. tokens.pop()
  200. events: list[tuple[str, tuple[str, ...]]] = []
  201. index = 0
  202. while index < len(tokens):
  203. try:
  204. status = tokens[index].decode("utf-8", "surrogateescape")
  205. except UnicodeDecodeError as exc:
  206. raise ValueError("git status contains undecodable status") from exc
  207. index += 1
  208. if not status:
  209. raise ValueError("git status contains an empty status")
  210. path_count = 2 if status[0] in {"R", "C"} else 1
  211. if index + path_count > len(tokens):
  212. raise ValueError("git status has an incomplete path record")
  213. paths = tuple(token.decode("utf-8", "surrogateescape") for token in tokens[index : index + path_count])
  214. events.append((status, paths))
  215. index += path_count
  216. return events
  217. def validate_changed_paths(
  218. events: Iterable[tuple[str, Iterable[str]]],
  219. owned_paths: Iterable[str],
  220. ) -> list[str]:
  221. owned = [_normalise_owned_path(path) for path in owned_paths]
  222. changed: list[str] = []
  223. for _status, raw_paths in events:
  224. for raw_path in raw_paths:
  225. path = _normalise_repo_path(raw_path)
  226. changed.append(path)
  227. if not any(
  228. path == candidate
  229. or (candidate.endswith("/") and path.startswith(candidate))
  230. for candidate in owned
  231. ):
  232. raise ValueError(f"changed path is outside owned paths: {path}")
  233. return changed
  234. def changed_paths_for_result(
  235. root: Path,
  236. assigned_base_commit: str,
  237. result_commit: str,
  238. owned_paths: Iterable[str],
  239. ) -> list[str]:
  240. _validate_full_commit(assigned_base_commit, "assigned_base_commit")
  241. _validate_full_commit(result_commit, "result_commit")
  242. result = _run_git(
  243. root,
  244. ["diff", "--name-status", "-z", "--find-renames", assigned_base_commit, result_commit],
  245. )
  246. return validate_changed_paths(parse_name_status_z(result.stdout), owned_paths)
  247. def validate_agent_task_report(
  248. report: Mapping[str, Any],
  249. *,
  250. expected_run_id: str,
  251. expected_base_commit: str,
  252. root: Path | None = None,
  253. expected_dependencies: Mapping[str, Mapping[str, str | None]] | None = None,
  254. ) -> dict[str, Any]:
  255. if report.get("schema") != AGENT_TASK_REPORT_SCHEMA:
  256. raise ValueError("unexpected agent task report schema")
  257. if not RUN_ID_RE.fullmatch(expected_run_id) or report.get("run_id") != expected_run_id:
  258. raise ValueError("run_id mismatch")
  259. _validate_full_commit(expected_base_commit, "expected_base_commit")
  260. assigned_base = _validate_full_commit(report.get("assigned_base_commit"), "assigned_base_commit")
  261. if assigned_base != expected_base_commit:
  262. raise ValueError("stale assigned base mismatch")
  263. if not isinstance(report.get("task_id"), str) or not report["task_id"]:
  264. raise ValueError("task_id must be non-empty")
  265. if not isinstance(report.get("feature_branch"), str) or not report["feature_branch"]:
  266. raise ValueError("feature_branch must be non-empty")
  267. if not isinstance(report.get("worktree"), str) or not report["worktree"]:
  268. raise ValueError("worktree must be non-empty")
  269. status = report.get("status")
  270. if status not in AGENT_TASK_STATUSES:
  271. raise ValueError("unsupported agent task status")
  272. dependencies = report.get("dependencies", [])
  273. if not isinstance(dependencies, list):
  274. raise ValueError("dependencies must be a list")
  275. dependency_map: dict[str, dict[str, str | None]] = {}
  276. for dependency in dependencies:
  277. if not isinstance(dependency, Mapping) or not isinstance(dependency.get("task_id"), str):
  278. raise ValueError("dependency entries must contain task_id")
  279. task_id = dependency["task_id"]
  280. result_commit = _validate_full_commit(
  281. dependency.get("result_commit"), f"dependency {task_id} result_commit", allow_none=True
  282. )
  283. integration_commit = _validate_full_commit(
  284. dependency.get("integration_commit"),
  285. f"dependency {task_id} integration_commit",
  286. allow_none=True,
  287. )
  288. dependency_map[task_id] = {
  289. "result_commit": result_commit,
  290. "integration_commit": integration_commit,
  291. }
  292. if expected_dependencies is not None and dependency_map != dict(expected_dependencies):
  293. raise ValueError("stale dependency mismatch")
  294. native_thread = report.get("native_thread")
  295. if not isinstance(native_thread, Mapping):
  296. raise ValueError("native_thread must be an object")
  297. _validate_observation_fields(native_thread)
  298. owned_paths = report.get("owned_paths", [])
  299. if not isinstance(owned_paths, list):
  300. raise ValueError("owned_paths must be a list")
  301. [_normalise_owned_path(path) for path in owned_paths]
  302. result_commit = _validate_full_commit(report.get("result_commit"), "result_commit", allow_none=True)
  303. integration_commit = _validate_full_commit(
  304. report.get("integration_commit"), "integration_commit", allow_none=True
  305. )
  306. read_only_report = report.get("read_only_report")
  307. if result_commit is None and (not isinstance(read_only_report, str) or not read_only_report):
  308. raise ValueError("task report requires result_commit or read_only_report")
  309. if root is not None and result_commit is not None:
  310. resolved = _run_git(root, ["rev-parse", "--verify", f"{result_commit}^{{commit}}"]).stdout
  311. if resolved.decode("ascii", "strict").strip().lower() != result_commit:
  312. raise ValueError("result commit does not resolve to the supplied full SHA")
  313. ancestry = _run_git(
  314. root,
  315. ["merge-base", "--is-ancestor", assigned_base, result_commit],
  316. check=False,
  317. )
  318. if ancestry.returncode != 0:
  319. raise ValueError("stale result commit is not based on assigned base")
  320. changed_paths_for_result(root, assigned_base, result_commit, owned_paths)
  321. if root is not None and integration_commit is not None:
  322. _run_git(root, ["rev-parse", "--verify", f"{integration_commit}^{{commit}}"])
  323. return dict(report)
  324. def aggregate_agent_receipt_bindings(
  325. receipts: Mapping[str, Mapping[str, Any]],
  326. *,
  327. expected_run_id: str,
  328. expected_commit: str,
  329. ) -> dict[str, Any]:
  330. if not RUN_ID_RE.fullmatch(expected_run_id):
  331. raise ValueError("expected_run_id must be 32 lowercase hexadecimal characters")
  332. aggregate: dict[str, Any] = {
  333. "schema": "prod2u-native-agent-receipt-aggregate-v1",
  334. "run_id": expected_run_id,
  335. "commit": expected_commit,
  336. "receipts": {},
  337. }
  338. for name, receipt in receipts.items():
  339. if not isinstance(receipt, Mapping):
  340. raise ValueError(f"receipt must be an object: {name}")
  341. observed_run_id = receipt.get("verification_run_id", receipt.get("run_id"))
  342. if observed_run_id != expected_run_id:
  343. raise ValueError(f"receipt run_id mismatch: {name}")
  344. if receipt.get("commit") != expected_commit:
  345. raise ValueError(f"receipt commit mismatch: {name}")
  346. hashes: dict[str, str] = {}
  347. for field, value in receipt.items():
  348. if field.endswith("_sha256"):
  349. if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):
  350. raise ValueError(f"receipt hash is invalid: {name}.{field}")
  351. hashes[field] = value
  352. aggregate["receipts"][name] = hashes
  353. return aggregate
  354. def _write_json(path: Path, value: Mapping[str, Any]) -> None:
  355. Path(path).parent.mkdir(parents=True, exist_ok=True)
  356. Path(path).write_text(json.dumps(dict(value), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
  357. def init_run(run_id: str, root: Path | None = None) -> Path:
  358. if not RUN_ID_RE.fullmatch(run_id):
  359. raise ValueError("run_id must be 32 lowercase hexadecimal characters")
  360. repo = _repo_root(root)
  361. run_root = repo / "runs" / run_id
  362. run_root.mkdir(parents=True, exist_ok=True)
  363. _write_json(
  364. run_root / "plan.json",
  365. {
  366. "schema": "prod2u-simple-run-plan-v1",
  367. "run_id": run_id,
  368. "project_id": PROJECT_ID,
  369. "status": "DESIGN_FROZEN",
  370. "authority": "CPLD_多项目_UART协议_项目适配_Codex并行Harness_详细设计_v1.0.md",
  371. "hardware_access": {"com": False, "jtag": False, "programming": False, "drivers": False},
  372. },
  373. )
  374. _write_json(run_root / "source-manifest.json", build_source_manifest(repo))
  375. return run_root
  376. def create_unverified_package(
  377. *,
  378. bitstream: Path,
  379. project: Path,
  380. commit: str,
  381. run_id: str,
  382. output_root: Path,
  383. td_receipt: Path | None = None,
  384. verification_receipts: Mapping[str, Path] | None = None,
  385. ) -> Path:
  386. if not COMMIT_RE.fullmatch(commit):
  387. raise ValueError("commit must be 8 lowercase hexadecimal characters")
  388. if not RUN_ID_RE.fullmatch(run_id):
  389. raise ValueError("run_id must be 32 lowercase hexadecimal characters")
  390. bitstream = Path(bitstream)
  391. project = Path(project)
  392. if not bitstream.is_file() or bitstream.stat().st_size == 0:
  393. raise FileNotFoundError(f"bitstream is missing or empty: {bitstream}")
  394. if not project.is_file():
  395. raise FileNotFoundError(f"project is missing: {project}")
  396. bitstream_sha256 = sha256_file(bitstream)
  397. package = Path(output_root) / PROJECT_ID / f"{commit}-{bitstream_sha256[:16]}"
  398. package.mkdir(parents=True, exist_ok=True)
  399. package_bitstream = package / "fw.bit"
  400. package_project = package / "project.json"
  401. evidence = package / "evidence"
  402. evidence.mkdir(parents=True, exist_ok=True)
  403. shutil.copy2(bitstream, package_bitstream)
  404. shutil.copy2(project, package_project)
  405. repo = _repo_root()
  406. artifacts = {
  407. "protocol.md": repo / PROTOCOL_PATH,
  408. "requirements.zh-CN.md": repo / REQUIREMENTS_PATH,
  409. "verification_targets.json": repo / VERIFICATION_TARGETS_PATH,
  410. }
  411. for name, source in artifacts.items():
  412. if not source.is_file():
  413. raise FileNotFoundError(f"package source is missing: {source}")
  414. shutil.copy2(source, package / name)
  415. project_config_sha256 = sha256_file(package_project)
  416. source_manifest = build_source_manifest(repo)
  417. _write_json(package / "source_manifest.json", source_manifest)
  418. receipt_sources = dict(verification_receipts or {})
  419. if td_receipt is not None:
  420. receipt = Path(td_receipt)
  421. if not receipt.is_file():
  422. raise FileNotFoundError(f"TD receipt is missing: {receipt}")
  423. _copy_bound_receipt(
  424. receipt,
  425. evidence / "td-primary-receipt.json",
  426. run_id=run_id,
  427. commit=commit,
  428. bitstream_sha256=bitstream_sha256,
  429. project_config_sha256=project_config_sha256,
  430. )
  431. else:
  432. _write_json(
  433. evidence / "td-primary-receipt.json",
  434. _receipt_payload(name="td-primary", run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256),
  435. )
  436. receipt_specs = {
  437. "td-confirmation": "td-confirmation-receipt.json",
  438. "python-unit": "python-unit-receipt.json",
  439. "icarus": "icarus-receipt.json",
  440. "verilator": "verilator-receipt.json",
  441. "cocotb": "cocotb-receipt.json",
  442. "formal": "formal-receipt.json",
  443. }
  444. for name, filename in receipt_specs.items():
  445. source = receipt_sources.get(name)
  446. if source is not None:
  447. source_path = Path(source)
  448. if not source_path.is_file():
  449. raise FileNotFoundError(f"verification receipt is missing: {source_path}")
  450. _copy_bound_receipt(
  451. source_path,
  452. evidence / filename,
  453. run_id=run_id,
  454. commit=commit,
  455. bitstream_sha256=bitstream_sha256,
  456. project_config_sha256=project_config_sha256,
  457. )
  458. else:
  459. _write_json(
  460. evidence / filename,
  461. _receipt_payload(name=name, run_id=run_id, commit=commit, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256),
  462. )
  463. _write_json(
  464. evidence / "package-selftest-result.json",
  465. {
  466. "schema": "prod2u-p4-normal-v3-package-selftest-result-v1",
  467. "status": "not_run",
  468. "verification_run_id": run_id,
  469. "commit": commit,
  470. "bitstream_sha256": bitstream_sha256,
  471. },
  472. )
  473. (package / "project_config_sha256.txt").write_text(
  474. sha256_file(package_project) + "\n", encoding="ascii", newline="\n"
  475. )
  476. (package / "bitstream_sha256.txt").write_text(
  477. sha256_file(package_bitstream) + "\n", encoding="ascii", newline="\n"
  478. )
  479. td_status = "not_run"
  480. td_synthesis_input_hash = None
  481. confirmation_bitstream_sha256 = None
  482. confirmation_synthesis_input_hash = None
  483. try:
  484. td_value = json.loads((evidence / "td-primary-receipt.json").read_text(encoding="utf-8-sig"))
  485. if isinstance(td_value, Mapping) and td_value.get("status") in {"pass", "fail", "blocked", "not_run"}:
  486. td_status = str(td_value["status"])
  487. td_synthesis_input_hash = td_value.get("synthesis_input_hash")
  488. except (OSError, UnicodeError, json.JSONDecodeError):
  489. td_status = "fail"
  490. try:
  491. confirmation_value = json.loads((evidence / "td-confirmation-receipt.json").read_text(encoding="utf-8-sig"))
  492. if isinstance(confirmation_value, Mapping) and confirmation_value.get("status") == "pass":
  493. confirmation_bitstream_sha256 = confirmation_value.get("bitstream_sha256")
  494. confirmation_synthesis_input_hash = confirmation_value.get("synthesis_input_hash")
  495. except (OSError, UnicodeError, json.JSONDecodeError):
  496. pass
  497. def receipt_status(filename: str) -> str:
  498. try:
  499. value = json.loads((evidence / filename).read_text(encoding="utf-8-sig"))
  500. except (OSError, UnicodeError, json.JSONDecodeError):
  501. return "fail"
  502. return str(value.get("status", "fail")) if isinstance(value, Mapping) else "fail"
  503. validation_summary = {
  504. "schema": "prod2u-p4-normal-v3-validation-summary-v1",
  505. "status": "UNVERIFIED",
  506. "delivery_mode": "urgent_single_td",
  507. "verification_complete": False,
  508. "confirmation_td_present": True,
  509. "verification_run_id": run_id,
  510. "commit": commit,
  511. "bitstream_sha256": bitstream_sha256,
  512. "project_config_sha256": sha256_file(package_project),
  513. "layers": {
  514. "python_unit": {"status": receipt_status("python-unit-receipt.json")},
  515. "icarus": {"status": receipt_status("icarus-receipt.json")},
  516. "verilator": {"status": receipt_status("verilator-receipt.json")},
  517. "cocotb": {"status": receipt_status("cocotb-receipt.json")},
  518. "formal": {"status": receipt_status("formal-receipt.json")},
  519. "td_primary": {"status": td_status},
  520. "td_confirmation": {"status": receipt_status("td-confirmation-receipt.json")},
  521. "td_confirmation_artifacts": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"},
  522. "td_confirmation_bitstream": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"},
  523. "td_confirmation_synthesis": {"status": "pass" if confirmation_synthesis_input_hash else "not_run"},
  524. "td_confirmation_manifest": {"status": "pass" if confirmation_synthesis_input_hash else "not_run"},
  525. "resource_confirmation": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"},
  526. },
  527. "hardware_validation": "not_run",
  528. }
  529. _write_json(evidence / "validation-summary.json", validation_summary)
  530. _write_json(package / "verification_summary.json", validation_summary)
  531. package_info = {
  532. "schema": PACKAGE_INFO_SCHEMA,
  533. "profile": RUNTIME_PROFILE,
  534. "project_id": PROJECT_ID,
  535. "delivery_mode": "urgent_single_td",
  536. "verification_complete": False,
  537. "confirmation_td_present": True,
  538. "verification_run_id": run_id,
  539. "commit": commit,
  540. "bitstream": "fw.bit",
  541. "bitstream_sha256": bitstream_sha256,
  542. "project": "project.json",
  543. "project_sha256": sha256_file(package_project),
  544. "project_config_sha256": sha256_file(package_project),
  545. "source_manifest_sha256": sha256_file(package / "source_manifest.json"),
  546. "synthesis_input_hash": td_synthesis_input_hash,
  547. "confirmation_bitstream_sha256": confirmation_bitstream_sha256,
  548. "confirmation_synthesis_input_hash": confirmation_synthesis_input_hash,
  549. "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
  550. "confirmation_td_receipt_sha256": sha256_file(evidence / "td-confirmation-receipt.json"),
  551. "validation_summary_sha256": sha256_file(evidence / "validation-summary.json"),
  552. "package_selftest_result_sha256": sha256_file(evidence / "package-selftest-result.json"),
  553. "file_sha256": _package_file_hashes(package),
  554. "hardware_validation": "not_run",
  555. }
  556. _write_json(package / "package-info.json", package_info)
  557. manifest = {
  558. "schema": PACKAGE_MANIFEST_SCHEMA,
  559. "status": "UNVERIFIED",
  560. "run_id": run_id,
  561. "project_id": PROJECT_ID,
  562. "commit": commit,
  563. "created_at": datetime.now(timezone.utc).isoformat(),
  564. "bitstream": "fw.bit",
  565. "bitstream_sha256": sha256_file(package_bitstream),
  566. "project": "project.json",
  567. "project_sha256": sha256_file(package_project),
  568. "package_info": "package-info.json",
  569. "package_info_sha256": sha256_file(package / "package-info.json"),
  570. "td_receipt": "evidence/td-primary-receipt.json",
  571. "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"),
  572. "file_sha256": _package_file_hashes(package),
  573. "hardware_validation": "not_run",
  574. }
  575. _write_json(package / "package_manifest.json", manifest)
  576. return package
  577. def main() -> int:
  578. import argparse
  579. parser = argparse.ArgumentParser(description=__doc__)
  580. sub = parser.add_subparsers(dest="command", required=True)
  581. sub.add_parser("run-id")
  582. init = sub.add_parser("init")
  583. init.add_argument("--run-id", required=True)
  584. init.add_argument("--root", type=Path)
  585. manifest = sub.add_parser("manifest")
  586. manifest.add_argument("--root", type=Path)
  587. package = sub.add_parser("package")
  588. package.add_argument("--bitstream", type=Path, required=True)
  589. package.add_argument("--project", type=Path, default=PROJECT_PATH)
  590. package.add_argument("--commit", required=True)
  591. package.add_argument("--run-id", required=True)
  592. package.add_argument("--output-root", type=Path, default=Path("dist"))
  593. package.add_argument("--td-receipt", type=Path)
  594. package.add_argument(
  595. "--receipt",
  596. action="append",
  597. default=[],
  598. metavar="NAME=PATH",
  599. help="bind an additional receipt under evidence (NAME: python-unit, icarus, verilator, cocotb, formal, td-confirmation)",
  600. )
  601. args = parser.parse_args()
  602. if args.command == "run-id":
  603. print(new_run_id())
  604. elif args.command == "init":
  605. print(init_run(args.run_id, args.root))
  606. elif args.command == "manifest":
  607. print(json.dumps(build_source_manifest(args.root), indent=2, sort_keys=True))
  608. else:
  609. receipt_map: dict[str, Path] = {}
  610. for item in args.receipt:
  611. name, separator, raw_path = item.partition("=")
  612. if not separator or not name or not raw_path:
  613. raise SystemExit(f"invalid --receipt value: {item!r}; expected NAME=PATH")
  614. receipt_map[name] = Path(raw_path)
  615. print(create_unverified_package(
  616. bitstream=args.bitstream,
  617. project=args.project,
  618. commit=args.commit,
  619. run_id=args.run_id,
  620. output_root=args.output_root,
  621. td_receipt=args.td_receipt,
  622. verification_receipts=receipt_map,
  623. ))
  624. return 0
  625. if __name__ == "__main__":
  626. raise SystemExit(main())