codex_harness.py 35 KB

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