codex_harness.py 31 KB

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