#!/usr/bin/env python3 """Small offline coordinator for the frozen multi-project UART refactor.""" from __future__ import annotations import hashlib import json import os import re import shutil import subprocess import uuid from datetime import datetime, timezone from pathlib import Path, PurePosixPath from typing import Any, Iterable, Mapping, Sequence RUN_ID_RE = re.compile(r"^[0-9a-f]{32}$") COMMIT_RE = re.compile(r"^[0-9a-f]{8}$") FULL_COMMIT_RE = re.compile(r"^[0-9a-f]{40}$") SHA256_RE = re.compile(r"^[0-9a-f]{64}$") AGENT_TASK_REPORT_SCHEMA = "prod2u-native-agent-task-report-v1" AGENT_SELECTION_SOURCES = frozenset( {"explicit", "inherited", "automatic", "default", "not_exposed", "unknown"} ) AGENT_TASK_STATUSES = frozenset({"completed", "blocked", "failed", "integration_conflict"}) PROJECT_ID = "prod2u-door-temp" PROJECT_PATH = Path("projects/prod2u-door-temp/project.json") SOURCE_MANIFEST_PATH = Path("src/generated/td-source-manifest.json") PROTOCOL_PATH = Path("docs/prod2u-door-temp-protocol.zh-CN.md") REQUIREMENTS_PATH = Path("projects/prod2u-door-temp/requirements.zh-CN.md") VERIFICATION_TARGETS_PATH = Path("config/prod2u_p4_verification_targets_v1.json") PACKAGE_INFO_SCHEMA = "prod2u-p4-normal-v3-folder-package-info-v3" PACKAGE_MANIFEST_SCHEMA = "prod2u-simple-package-manifest-v2" RUNTIME_PROFILE = "prod2u-door-temp-115200-v1" def _receipt_payload(*, name: str, run_id: str, commit: str, bitstream_sha256: str, project_config_sha256: str) -> dict[str, Any]: return { "schema": f"prod2u-p4-normal-v3-{name}-receipt-v1", "status": "not_run", "verification_run_id": run_id, "commit": commit, "bitstream_sha256": bitstream_sha256, "project_config_sha256": project_config_sha256, "authority_boundary": "Offline package placeholder. No COM, JTAG, programming, or board action.", } def _copy_bound_receipt( source: Path, destination: Path, *, run_id: str, commit: str, bitstream_sha256: str, project_config_sha256: str, preserve_bitstream_sha256: bool = False, require_bitstream_sha256: bool = False, ) -> dict[str, Any]: try: value = json.loads(Path(source).read_text(encoding="utf-8-sig")) except (OSError, UnicodeError, json.JSONDecodeError) as exc: raise ValueError(f"receipt is not readable JSON: {source}") from exc if not isinstance(value, dict): raise ValueError(f"receipt root must be an object: {source}") bindings = { "verification_run_id": run_id, "commit": commit, "project_config_sha256": project_config_sha256, } for field, expected in bindings.items(): observed = value.get(field) if observed not in {None, "", expected}: raise ValueError(f"receipt binding mismatch for {field}: {source}") value[field] = expected if not preserve_bitstream_sha256: observed = value.get("bitstream_sha256") if value.get("status") == "pass" and require_bitstream_sha256 and observed != bitstream_sha256: raise ValueError(f"authoritative receipt bitstream binding mismatch: {source}") if observed not in {None, ""} and observed != bitstream_sha256: raise ValueError(f"receipt bitstream binding mismatch: {source}") if observed not in {None, ""}: value["bitstream_sha256"] = bitstream_sha256 elif value.get("status") == "pass" and not SHA256_RE.fullmatch(str(value.get("bitstream_sha256", ""))): raise ValueError(f"confirmation receipt requires its own bitstream SHA256: {source}") value["commit_full"] = commit value["source_receipt_sha256"] = sha256_file(source) _write_json(destination, value) return value def _package_file_hashes(package: Path) -> dict[str, str]: excluded = { "package-info.json", "package_manifest.json", "evidence/package-selftest-result.json", } return { path.relative_to(package).as_posix(): sha256_file(path) for path in sorted(package.rglob("*")) if path.is_file() and path.relative_to(package).as_posix() not in excluded } def new_run_id() -> str: return uuid.uuid4().hex def sha256_file(path: Path) -> str: digest = hashlib.sha256() with Path(path).open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _canonical_sha256(value: Mapping[str, Any]) -> str: encoded = json.dumps(dict(value), sort_keys=True, separators=(",", ":"), ensure_ascii=True) return hashlib.sha256(encoded.encode("ascii")).hexdigest() def _repo_root(root: Path | None = None) -> Path: candidate = Path(root or Path(__file__).resolve().parents[1]).expanduser().resolve() if not candidate.is_dir(): raise ValueError(f"repository root is not a directory: {candidate}") return candidate def _run_git( root: Path, args: Sequence[str], *, timeout_seconds: float = 10.0, check: bool = True, ) -> subprocess.CompletedProcess[bytes]: if timeout_seconds <= 0: raise ValueError("timeout_seconds must be positive") values = [str(value) for value in args] if not values or any(not value for value in values): raise ValueError("git args must be a non-empty sequence of non-empty strings") return subprocess.run( ["git", "-C", str(_repo_root(root)), *values], cwd=_repo_root(root), capture_output=True, check=check, shell=False, text=False, timeout=timeout_seconds, ) def build_source_manifest(root: Path | None = None) -> dict[str, Any]: repo = _repo_root(root) project_path = repo / PROJECT_PATH generated_path = repo / SOURCE_MANIFEST_PATH try: generated = json.loads(generated_path.read_text(encoding="utf-8-sig")) except (OSError, UnicodeError, json.JSONDecodeError) as exc: raise ValueError(f"generated source manifest is not readable: {generated_path}") from exc if not isinstance(generated, Mapping) or not isinstance(generated.get("sources"), list): raise ValueError("generated source manifest has no sources list") source_paths = [] for value in generated["sources"]: if not isinstance(value, str) or not value: raise ValueError("generated source manifest contains an invalid path") candidate = Path(value) if candidate.is_absolute() or ".." in candidate.parts: raise ValueError(f"generated source manifest contains unsafe path: {value}") source_paths.append(candidate.as_posix()) if len(source_paths) != len(set(source_paths)): raise ValueError("generated source manifest contains duplicate paths") missing = [path for path in source_paths if not (repo / path).is_file()] if missing: raise FileNotFoundError(f"missing active source: {missing[0]}") source_hashes = {path: sha256_file(repo / path) for path in source_paths} payload = { "schema": "prod2u-simple-source-manifest-v1", "project_id": PROJECT_ID, "project": PROJECT_PATH.as_posix(), "project_sha256": sha256_file(project_path), "generated_source_manifest": SOURCE_MANIFEST_PATH.as_posix(), "generated_source_manifest_sha256": sha256_file(generated_path), "sources": source_paths, "source_sha256": source_hashes, } payload["manifest_sha256"] = _canonical_sha256(payload) return payload def _git_identity(root: Path) -> dict[str, str]: repo = _repo_root(root) top = _run_git(repo, ["rev-parse", "--show-toplevel"]).stdout.decode("utf-8", "strict").strip() branch = _run_git(repo, ["branch", "--show-current"]).stdout.decode("utf-8", "strict").strip() head = _run_git(repo, ["rev-parse", "HEAD"]).stdout.decode("ascii", "strict").strip().lower() actual_root = Path(top).expanduser().resolve() if actual_root != repo: raise ValueError(f"worktree root mismatch: expected {repo}, git reports {actual_root}") if not FULL_COMMIT_RE.fullmatch(head): raise ValueError("worktree HEAD is not a full commit") return {"root": str(actual_root), "branch": branch, "head": head} def validate_worktree_identity( root: Path, *, expected_branch: str | None = None, expected_head: str | None = None, assigned_base_commit: str | None = None, protected_root: Path | None = None, ) -> dict[str, str]: identity = _git_identity(root) protected_value = protected_root or os.environ.get("PROD2U_PROTECTED_REPO_ROOT") if protected_value and Path(protected_value).expanduser().resolve() == Path(identity["root"]): raise ValueError("protected_worktree_violation: writes are forbidden in protected repository") if expected_branch is not None and identity["branch"] != expected_branch: raise ValueError("worktree branch does not match expected branch") if expected_head is not None: _validate_full_commit(expected_head, "expected_head") if identity["head"] != expected_head: raise ValueError("worktree HEAD does not match expected HEAD") if assigned_base_commit is not None: _validate_full_commit(assigned_base_commit, "assigned_base_commit") ancestry = _run_git(Path(identity["root"]), ["merge-base", "--is-ancestor", assigned_base_commit, identity["head"]], check=False) if ancestry.returncode != 0: raise ValueError("assigned base is not an ancestor of worktree HEAD") return identity def current_commit8(root: Path | None = None) -> str: repo = _repo_root(root) result = _run_git(repo, ["rev-parse", "--short=8", "HEAD"]) commit = result.stdout.decode("ascii").strip().lower() if not COMMIT_RE.fullmatch(commit): raise ValueError(f"unexpected commit: {commit}") return commit def _validate_full_commit(value: Any, field: str, *, allow_none: bool = False) -> str | None: if value is None and allow_none: return None if not isinstance(value, str) or not FULL_COMMIT_RE.fullmatch(value): raise ValueError(f"{field} must be a 40-character lowercase hexadecimal commit") return value def _validate_observation_fields(native_thread: Mapping[str, Any]) -> None: if native_thread.get("model_policy") != "unconstrained": raise ValueError("native_thread.model_policy must be unconstrained") if native_thread.get("reasoning_effort_policy") != "unconstrained": raise ValueError("native_thread.reasoning_effort_policy must be unconstrained") for field in ("model_selection_source", "effort_selection_source"): value = native_thread.get(field) if value is not None and value not in AGENT_SELECTION_SOURCES: raise ValueError(f"{field} has an unsupported selection source") observation_source = native_thread.get("observation_source") if observation_source is not None and not isinstance(observation_source, str): raise ValueError("observation_source must be a string or null") for field in ("observed_model", "observed_reasoning_effort", "observed_permission_mode"): value = native_thread.get(field) if value is not None and not isinstance(value, str): raise ValueError(f"{field} must be a string or null") def _normalise_repo_path(value: Any, *, owned: bool = False) -> str: if not isinstance(value, str) or not value: raise ValueError("path must be a non-empty string") raw = value.replace("\\", "/") if raw.startswith("/") or re.match(r"^[A-Za-z]:", raw): raise ValueError(f"path must be relative: {value}") if any(part == ".." for part in PurePosixPath(raw).parts): raise ValueError(f"path contains parent traversal: {value}") normalised = PurePosixPath(raw).as_posix() if normalised in {"", "."}: raise ValueError(f"path is not a file or directory: {value}") if owned and any(token in normalised for token in "*?["): raise ValueError("owned paths must not contain glob syntax") return normalised def _normalise_owned_path(value: Any) -> str: directory = isinstance(value, str) and value.replace("\\", "/").endswith("/") normalised = _normalise_repo_path(value, owned=True) return normalised.rstrip("/") + "/" if directory else normalised def parse_name_status_z(payload: bytes) -> list[tuple[str, tuple[str, ...]]]: tokens = payload.split(b"\0") if tokens and tokens[-1] == b"": tokens.pop() events: list[tuple[str, tuple[str, ...]]] = [] index = 0 while index < len(tokens): try: status = tokens[index].decode("utf-8", "surrogateescape") except UnicodeDecodeError as exc: raise ValueError("git status contains undecodable status") from exc index += 1 if not status: raise ValueError("git status contains an empty status") path_count = 2 if status[0] in {"R", "C"} else 1 if index + path_count > len(tokens): raise ValueError("git status has an incomplete path record") paths = tuple(token.decode("utf-8", "surrogateescape") for token in tokens[index : index + path_count]) events.append((status, paths)) index += path_count return events def validate_changed_paths( events: Iterable[tuple[str, Iterable[str]]], owned_paths: Iterable[str], ) -> list[str]: owned = [_normalise_owned_path(path) for path in owned_paths] changed: list[str] = [] for _status, raw_paths in events: for raw_path in raw_paths: path = _normalise_repo_path(raw_path) changed.append(path) if not any( path == candidate or (candidate.endswith("/") and path.startswith(candidate)) for candidate in owned ): raise ValueError(f"changed path is outside owned paths: {path}") return changed def changed_paths_for_result( root: Path, assigned_base_commit: str, result_commit: str, owned_paths: Iterable[str], ) -> list[str]: _validate_full_commit(assigned_base_commit, "assigned_base_commit") _validate_full_commit(result_commit, "result_commit") result = _run_git( root, ["diff", "--name-status", "-z", "--find-renames", assigned_base_commit, result_commit], ) return validate_changed_paths(parse_name_status_z(result.stdout), owned_paths) def validate_agent_task_report( report: Mapping[str, Any], *, expected_run_id: str, expected_base_commit: str, root: Path | None = None, expected_dependencies: Mapping[str, Mapping[str, str | None]] | None = None, ) -> dict[str, Any]: if report.get("schema") != AGENT_TASK_REPORT_SCHEMA: raise ValueError("unexpected agent task report schema") if not RUN_ID_RE.fullmatch(expected_run_id) or report.get("run_id") != expected_run_id: raise ValueError("run_id mismatch") _validate_full_commit(expected_base_commit, "expected_base_commit") assigned_base = _validate_full_commit(report.get("assigned_base_commit"), "assigned_base_commit") if assigned_base != expected_base_commit: raise ValueError("stale assigned base mismatch") if not isinstance(report.get("task_id"), str) or not report["task_id"]: raise ValueError("task_id must be non-empty") feature_branch = report.get("feature_branch") if not isinstance(feature_branch, str) or not feature_branch.strip(): raise ValueError("feature_branch must be non-empty") worktree = report.get("worktree") if not isinstance(worktree, str) or not worktree.strip(): raise ValueError("worktree must be non-empty") report_worktree = Path(worktree).expanduser().resolve() identity = validate_worktree_identity( report_worktree, expected_branch=feature_branch, assigned_base_commit=assigned_base, ) status = report.get("status") if status not in AGENT_TASK_STATUSES: raise ValueError("unsupported agent task status") dependencies = report.get("dependencies", []) if not isinstance(dependencies, list): raise ValueError("dependencies must be a list") dependency_map: dict[str, dict[str, str | None]] = {} for dependency in dependencies: if not isinstance(dependency, Mapping) or not isinstance(dependency.get("task_id"), str): raise ValueError("dependency entries must contain task_id") task_id = dependency["task_id"] if task_id in dependency_map: raise ValueError(f"duplicate dependency task_id: {task_id}") result_commit = _validate_full_commit( dependency.get("result_commit"), f"dependency {task_id} result_commit", allow_none=True ) integration_commit = _validate_full_commit( dependency.get("integration_commit"), f"dependency {task_id} integration_commit", allow_none=True, ) dependency_map[task_id] = { "result_commit": result_commit, "integration_commit": integration_commit, } if expected_dependencies is not None and dependency_map != dict(expected_dependencies): raise ValueError("stale dependency mismatch") native_thread = report.get("native_thread") if not isinstance(native_thread, Mapping): raise ValueError("native_thread must be an object") _validate_observation_fields(native_thread) owned_paths = report.get("owned_paths", []) if not isinstance(owned_paths, list): raise ValueError("owned_paths must be a list") [_normalise_owned_path(path) for path in owned_paths] result_commit = _validate_full_commit(report.get("result_commit"), "result_commit", allow_none=True) integration_commit = _validate_full_commit( report.get("integration_commit"), "integration_commit", allow_none=True ) read_only_report = report.get("read_only_report") if result_commit is None and not ( (isinstance(read_only_report, str) and read_only_report.strip()) or isinstance(read_only_report, Mapping) ): raise ValueError("task report requires result_commit or read_only_report") if result_commit is not None: resolved = _run_git(report_worktree, ["rev-parse", "--verify", f"{result_commit}^{{commit}}"]).stdout if resolved.decode("ascii", "strict").strip().lower() != result_commit: raise ValueError("result commit does not resolve to the supplied full SHA") if identity["head"] != result_commit: raise ValueError("report result_commit does not match report worktree HEAD") ancestry = _run_git( report_worktree, ["merge-base", "--is-ancestor", assigned_base, result_commit], check=False, ) if ancestry.returncode != 0: raise ValueError("stale result commit is not based on assigned base") changed_paths_for_result(report_worktree, assigned_base, result_commit, owned_paths) if root is not None and integration_commit is not None: _run_git(root, ["rev-parse", "--verify", f"{integration_commit}^{{commit}}"]) if result_commit is not None: ancestry = _run_git( root, ["merge-base", "--is-ancestor", result_commit, integration_commit], check=False, ) if ancestry.returncode != 0: raise ValueError("integration commit does not contain result commit") return dict(report) def aggregate_agent_receipt_bindings( receipts: Mapping[str, Mapping[str, Any]], *, expected_run_id: str, expected_commit: str, ) -> dict[str, Any]: if not RUN_ID_RE.fullmatch(expected_run_id): raise ValueError("expected_run_id must be 32 lowercase hexadecimal characters") aggregate: dict[str, Any] = { "schema": "prod2u-native-agent-receipt-aggregate-v1", "run_id": expected_run_id, "commit": expected_commit, "receipts": {}, } for name, receipt in receipts.items(): if not isinstance(receipt, Mapping): raise ValueError(f"receipt must be an object: {name}") observed_run_id = receipt.get("verification_run_id", receipt.get("run_id")) if observed_run_id != expected_run_id: raise ValueError(f"receipt run_id mismatch: {name}") if receipt.get("commit") != expected_commit: raise ValueError(f"receipt commit mismatch: {name}") hashes: dict[str, str] = {} for field, value in receipt.items(): if field.endswith("_sha256"): if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value): raise ValueError(f"receipt hash is invalid: {name}.{field}") hashes[field] = value aggregate["receipts"][name] = hashes return aggregate def _write_json(path: Path, value: Mapping[str, Any]) -> None: Path(path).parent.mkdir(parents=True, exist_ok=True) Path(path).write_text(json.dumps(dict(value), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n") def init_run(run_id: str, root: Path | None = None) -> Path: if not RUN_ID_RE.fullmatch(run_id): raise ValueError("run_id must be 32 lowercase hexadecimal characters") repo = _repo_root(root) run_root = repo / "runs" / run_id run_root.mkdir(parents=True, exist_ok=True) _write_json( run_root / "plan.json", { "schema": "prod2u-simple-run-plan-v1", "run_id": run_id, "project_id": PROJECT_ID, "status": "DESIGN_FROZEN", "authority": [ PROJECT_PATH.as_posix(), REQUIREMENTS_PATH.as_posix(), PROTOCOL_PATH.as_posix(), SOURCE_MANIFEST_PATH.as_posix(), ], "source_binding": build_source_manifest(repo), "hardware_access": {"com": False, "jtag": False, "programming": False, "drivers": False}, }, ) _write_json(run_root / "source-manifest.json", build_source_manifest(repo)) return run_root def create_unverified_package( *, bitstream: Path, project: Path, commit: str, run_id: str, output_root: Path, td_receipt: Path | None = None, verification_receipts: Mapping[str, Path] | None = None, production_integration_commit: str | None = None, source_manifest_sha256: str | None = None, td_receipt_sha256: str | None = None, package_class: str = "UNVERIFIED", ) -> Path: if not (COMMIT_RE.fullmatch(commit) or FULL_COMMIT_RE.fullmatch(commit)): raise ValueError("commit must be a full or 8-character lowercase hexadecimal SHA") if not RUN_ID_RE.fullmatch(run_id): raise ValueError("run_id must be 32 lowercase hexadecimal characters") if package_class not in { "UNVERIFIED", "UNVERIFIED_EARLY_BUILD", "UNVERIFIED_FINAL_CANDIDATE", }: raise ValueError("unsupported package class") early_fields = ( production_integration_commit, source_manifest_sha256, td_receipt_sha256, ) if package_class == "UNVERIFIED_EARLY_BUILD" and ( any(value is None for value in early_fields) or td_receipt is None ): raise ValueError("early package requires production commit and input hashes") if production_integration_commit is not None and not FULL_COMMIT_RE.fullmatch(production_integration_commit): raise ValueError("production integration commit must be a 40-character lowercase SHA") for name, value in ( ("source manifest", source_manifest_sha256), ("TD receipt", td_receipt_sha256), ): if value is not None and not SHA256_RE.fullmatch(value): raise ValueError(f"{name} hash must be 64 lowercase hexadecimal characters") bitstream = Path(bitstream) project = Path(project) if not bitstream.is_file() or bitstream.stat().st_size == 0: raise FileNotFoundError(f"bitstream is missing or empty: {bitstream}") if not project.is_file(): raise FileNotFoundError(f"project is missing: {project}") repo = _repo_root() canonical_project = (repo / PROJECT_PATH).resolve() if project.resolve() != canonical_project: raise ValueError("package project must be the canonical project.json") if FULL_COMMIT_RE.fullmatch(commit): commit_full = commit else: resolved = _run_git(repo, ["rev-parse", "HEAD"]).stdout.decode("ascii", "strict").strip().lower() if not FULL_COMMIT_RE.fullmatch(resolved) or resolved[:8] != commit: raise ValueError("short commit does not match the current full HEAD") commit_full = resolved compatibility_commit = commit bitstream_sha256 = sha256_file(bitstream) package = Path(output_root) / PROJECT_ID / f"{compatibility_commit}-{bitstream_sha256[:16]}" package.mkdir(parents=True, exist_ok=True) package_bitstream = package / "fw.bit" package_project = package / "project.json" evidence = package / "evidence" evidence.mkdir(parents=True, exist_ok=True) shutil.copy2(bitstream, package_bitstream) shutil.copy2(project, package_project) artifacts = { "protocol.md": repo / PROTOCOL_PATH, "requirements.zh-CN.md": repo / REQUIREMENTS_PATH, "verification_targets.json": repo / VERIFICATION_TARGETS_PATH, } for name, source in artifacts.items(): if not source.is_file(): raise FileNotFoundError(f"package source is missing: {source}") shutil.copy2(source, package / name) (package / "selftest.ps1").write_text( "$ErrorActionPreference = 'Stop'\r\n" "$bit = (Get-FileHash (Join-Path $PSScriptRoot 'fw.bit') -Algorithm SHA256).Hash.ToLowerInvariant()\r\n" "$expectedBit = (Get-Content (Join-Path $PSScriptRoot 'bitstream_sha256.txt') -Raw).Trim().ToLowerInvariant()\r\n" "if ($bit -ne $expectedBit) { throw 'bitstream hash mismatch' }\r\n" "$projectHash = (Get-FileHash (Join-Path $PSScriptRoot 'project.json') -Algorithm SHA256).Hash.ToLowerInvariant()\r\n" "$expectedProject = (Get-Content (Join-Path $PSScriptRoot 'project_config_sha256.txt') -Raw).Trim().ToLowerInvariant()\r\n" "if ($projectHash -ne $expectedProject) { throw 'project hash mismatch' }\r\n", encoding="ascii", newline="", ) project_config_sha256 = sha256_file(package_project) source_manifest = build_source_manifest(repo) _write_json(package / "source_manifest.json", source_manifest) observed_source_manifest_sha256 = sha256_file(package / "source_manifest.json") if source_manifest_sha256 is not None and source_manifest_sha256 != observed_source_manifest_sha256: raise ValueError("source manifest hash mismatch") receipt_sources = dict(verification_receipts or {}) if td_receipt is not None: receipt = Path(td_receipt) if not receipt.is_file(): raise FileNotFoundError(f"TD receipt is missing: {receipt}") if td_receipt_sha256 is not None and sha256_file(receipt) != td_receipt_sha256: raise ValueError("TD receipt hash mismatch") _copy_bound_receipt( receipt, evidence / "td-primary-receipt.json", run_id=run_id, commit=commit_full, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256, ) else: _write_json( evidence / "td-primary-receipt.json", _receipt_payload(name="td-primary", run_id=run_id, commit=commit_full, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256), ) receipt_specs = { "td-confirmation": "td-confirmation-receipt.json", "python-unit": "python-unit-receipt.json", "icarus": "icarus-receipt.json", "verilator": "verilator-receipt.json", "cocotb": "cocotb-receipt.json", "formal": "formal-receipt.json", } for name, filename in receipt_specs.items(): source = receipt_sources.get(name) if source is not None: source_path = Path(source) if not source_path.is_file(): raise FileNotFoundError(f"verification receipt is missing: {source_path}") _copy_bound_receipt( source_path, evidence / filename, run_id=run_id, commit=commit_full, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256, preserve_bitstream_sha256=name == "td-confirmation", require_bitstream_sha256=name == "td-primary", ) else: _write_json( evidence / filename, _receipt_payload(name=name, run_id=run_id, commit=commit_full, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256), ) _write_json( evidence / "package-selftest-result.json", { "schema": "prod2u-p4-normal-v3-package-selftest-result-v1", "status": "not_run", "verification_run_id": run_id, "commit": commit_full, "commit_full": commit_full, "bitstream_sha256": bitstream_sha256, }, ) (package / "project_config_sha256.txt").write_text( sha256_file(package_project) + "\n", encoding="ascii", newline="\n" ) (package / "bitstream_sha256.txt").write_text( sha256_file(package_bitstream) + "\n", encoding="ascii", newline="\n" ) td_status = "not_run" td_synthesis_input_hash = None confirmation_bitstream_sha256 = None confirmation_synthesis_input_hash = None try: td_value = json.loads((evidence / "td-primary-receipt.json").read_text(encoding="utf-8-sig")) if isinstance(td_value, Mapping) and td_value.get("status") in {"pass", "fail", "blocked", "not_run"}: td_status = str(td_value["status"]) td_synthesis_input_hash = td_value.get("synthesis_input_hash") except (OSError, UnicodeError, json.JSONDecodeError): td_status = "fail" try: confirmation_value = json.loads((evidence / "td-confirmation-receipt.json").read_text(encoding="utf-8-sig")) if isinstance(confirmation_value, Mapping) and confirmation_value.get("status") == "pass": confirmation_bitstream_sha256 = confirmation_value.get("bitstream_sha256") confirmation_synthesis_input_hash = confirmation_value.get("synthesis_input_hash") except (OSError, UnicodeError, json.JSONDecodeError): pass def receipt_status(filename: str) -> str: try: value = json.loads((evidence / filename).read_text(encoding="utf-8-sig")) except (OSError, UnicodeError, json.JSONDecodeError): return "fail" return str(value.get("status", "fail")) if isinstance(value, Mapping) else "fail" validation_summary = { "schema": "prod2u-p4-normal-v3-validation-summary-v1", "status": "UNVERIFIED", "delivery_mode": "normal_dual_td", "verification_complete": False, "confirmation_td_present": confirmation_bitstream_sha256 is not None, "verification_run_id": run_id, "commit": compatibility_commit, "commit_full": commit_full, "bitstream_sha256": bitstream_sha256, "project_config_sha256": sha256_file(package_project), "layers": { "python_unit": {"status": receipt_status("python-unit-receipt.json")}, "icarus": {"status": receipt_status("icarus-receipt.json")}, "verilator": {"status": receipt_status("verilator-receipt.json")}, "cocotb": {"status": receipt_status("cocotb-receipt.json")}, "formal": {"status": receipt_status("formal-receipt.json")}, "td_primary": {"status": td_status}, "td_confirmation": {"status": receipt_status("td-confirmation-receipt.json")}, "td_confirmation_artifacts": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"}, "td_confirmation_bitstream": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"}, "td_confirmation_synthesis": {"status": "pass" if confirmation_synthesis_input_hash else "not_run"}, "td_confirmation_manifest": {"status": "pass" if confirmation_synthesis_input_hash else "not_run"}, "resource_confirmation": {"status": "pass" if confirmation_bitstream_sha256 else "not_run"}, }, "hardware_validation": "not_run", "verification_scope": "offline", "board_validation": "not_run", "programming_validation": "not_run", "COM": False, "JTAG": False, } _write_json(evidence / "validation-summary.json", validation_summary) _write_json(package / "verification_summary.json", validation_summary) package_info = { "schema": PACKAGE_INFO_SCHEMA, "profile": RUNTIME_PROFILE, "project_id": PROJECT_ID, "delivery_mode": "normal_dual_td", "verification_complete": False, "confirmation_td_present": confirmation_bitstream_sha256 is not None, "verification_run_id": run_id, "commit": compatibility_commit, "commit_full": commit_full, "bitstream": "fw.bit", "bitstream_sha256": bitstream_sha256, "project": "project.json", "project_sha256": sha256_file(package_project), "project_config_sha256": sha256_file(package_project), "source_manifest_sha256": sha256_file(package / "source_manifest.json"), "production_integration_commit": production_integration_commit, "package_class": package_class, "synthesis_input_hash": td_synthesis_input_hash, "confirmation_bitstream_sha256": confirmation_bitstream_sha256, "confirmation_synthesis_input_hash": confirmation_synthesis_input_hash, "td_source_manifest_sha256": sha256_file(repo / SOURCE_MANIFEST_PATH), "canonical_bitstream_build": "primary", "bitstream_hash_equal": confirmation_bitstream_sha256 == bitstream_sha256 if confirmation_bitstream_sha256 else None, "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"), "td_source_receipt_sha256": td_receipt_sha256, "confirmation_td_receipt_sha256": sha256_file(evidence / "td-confirmation-receipt.json"), "validation_summary_sha256": sha256_file(evidence / "validation-summary.json"), "package_selftest_result_sha256": sha256_file(evidence / "package-selftest-result.json"), "file_sha256": _package_file_hashes(package), "hardware_validation": "not_run", "verification_scope": "offline", "board_validation": "not_run", "programming_validation": "not_run", "COM": False, "JTAG": False, } _write_json(package / "package-info.json", package_info) manifest = { "schema": PACKAGE_MANIFEST_SCHEMA, "status": "UNVERIFIED", "package_class": package_class, "run_id": run_id, "project_id": PROJECT_ID, "commit": compatibility_commit, "commit_full": commit_full, "production_integration_commit": production_integration_commit, "created_at": datetime.now(timezone.utc).isoformat(), "bitstream": "fw.bit", "bitstream_sha256": sha256_file(package_bitstream), "project": "project.json", "project_sha256": sha256_file(package_project), "source_manifest_sha256": observed_source_manifest_sha256, "package_info": "package-info.json", "package_info_sha256": sha256_file(package / "package-info.json"), "td_receipt": "evidence/td-primary-receipt.json", "td_receipt_sha256": sha256_file(evidence / "td-primary-receipt.json"), "td_source_receipt_sha256": td_receipt_sha256, "td_source_manifest_sha256": sha256_file(repo / SOURCE_MANIFEST_PATH), "canonical_bitstream_build": "primary", "confirmation_bitstream_sha256": confirmation_bitstream_sha256, "bitstream_hash_equal": confirmation_bitstream_sha256 == bitstream_sha256 if confirmation_bitstream_sha256 else None, "file_sha256": _package_file_hashes(package), "hardware_validation": "not_run", "verification_scope": "offline", "board_validation": "not_run", "programming_validation": "not_run", "COM": False, "JTAG": False, } _write_json(package / "package_manifest.json", manifest) return package def main() -> int: import argparse parser = argparse.ArgumentParser(description=__doc__) sub = parser.add_subparsers(dest="command", required=True) sub.add_parser("run-id") init = sub.add_parser("init") init.add_argument("--run-id", required=True) init.add_argument("--root", type=Path) manifest = sub.add_parser("manifest") manifest.add_argument("--root", type=Path) package = sub.add_parser("package") package.add_argument("--bitstream", type=Path, required=True) package.add_argument("--project", type=Path, default=PROJECT_PATH) package.add_argument("--commit", required=True) package.add_argument("--run-id", required=True) package.add_argument("--output-root", type=Path, default=Path("dist")) package.add_argument("--td-receipt", type=Path) package.add_argument("--production-integration-commit") package.add_argument("--source-manifest-sha256") package.add_argument("--td-receipt-sha256") package.add_argument( "--package-class", choices=("UNVERIFIED", "UNVERIFIED_EARLY_BUILD", "UNVERIFIED_FINAL_CANDIDATE"), default="UNVERIFIED", ) package.add_argument( "--receipt", action="append", default=[], metavar="NAME=PATH", help="bind an additional receipt under evidence (NAME: python-unit, icarus, verilator, cocotb, formal, td-confirmation)", ) args = parser.parse_args() if args.command == "run-id": print(new_run_id()) elif args.command == "init": print(init_run(args.run_id, args.root)) elif args.command == "manifest": print(json.dumps(build_source_manifest(args.root), indent=2, sort_keys=True)) else: receipt_map: dict[str, Path] = {} for item in args.receipt: name, separator, raw_path = item.partition("=") if not separator or not name or not raw_path: raise SystemExit(f"invalid --receipt value: {item!r}; expected NAME=PATH") receipt_map[name] = Path(raw_path) print(create_unverified_package( bitstream=args.bitstream, project=args.project, commit=args.commit, run_id=args.run_id, output_root=args.output_root, td_receipt=args.td_receipt, verification_receipts=receipt_map, production_integration_commit=args.production_integration_commit, source_manifest_sha256=args.source_manifest_sha256, td_receipt_sha256=args.td_receipt_sha256, package_class=args.package_class, )) return 0 if __name__ == "__main__": raise SystemExit(main())