codex_harness.py 39 KB

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