#!/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" PACKAGE_HASH_EXCLUSIONS = frozenset( { "package-info.json", "package_manifest.json", "evidence/package-selftest-result.json", } ) PACKAGE_RECEIPT_PATHS = ( "evidence/td-primary-receipt.json", "evidence/td-confirmation-receipt.json", "evidence/python-unit-receipt.json", "evidence/icarus-receipt.json", "evidence/verilator-receipt.json", "evidence/cocotb-receipt.json", "evidence/formal-receipt.json", ) def _receipt_payload( *, name: str, run_id: str, commit: str, bitstream_sha256: str, project_config_sha256: str, td_source_manifest_sha256: str | None = None, ) -> 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, "td_source_manifest_sha256": td_source_manifest_sha256, "command": None, "tool_version": None, "placeholder": True, "authoritative": False, "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, td_source_manifest_sha256: str | None = None, receipt_role: str | None = None, 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, } if td_source_manifest_sha256 is not None: bindings["td_source_manifest_sha256"] = td_source_manifest_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 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 if receipt_role is not None: value["receipt_role"] = receipt_role # Authoritative receipts must have every binding field already present and # non-empty. Package processing may only verify and copy; it must not invent # command, tool_version, or other provenance fields and then promote the # receipt to authoritative. required_authoritative_fields = [ "verification_run_id", "commit", "project_config_sha256", "command", "tool_version", "status", ] if td_source_manifest_sha256 is not None: required_authoritative_fields.append("td_source_manifest_sha256") missing = [field for field in required_authoritative_fields if not value.get(field)] if require_bitstream_sha256 and not SHA256_RE.fullmatch(str(value.get("bitstream_sha256", ""))): missing.append("bitstream_sha256") if preserve_bitstream_sha256 and not SHA256_RE.fullmatch(str(value.get("bitstream_sha256", ""))): missing.append("bitstream_sha256") was_pass = value.get("status") == "pass" if was_pass and not missing: value["authoritative"] = True value["placeholder"] = False else: if was_pass and missing: value["status"] = "blocked" value["authoritative"] = False value["placeholder"] = True value["source_receipt_sha256"] = sha256_file(source) _write_json(destination, value) return value def _package_file_hashes(package: Path) -> dict[str, str]: 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 PACKAGE_HASH_EXCLUSIONS } def _package_selftest_script() -> str: return """$ErrorActionPreference = 'Stop' $excluded = @( 'package-info.json', 'package_manifest.json', 'evidence/package-selftest-result.json' ) function Require-File([string]$Relative) { $path = Join-Path $PSScriptRoot $Relative if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "missing file: $Relative" } return $path } function Read-Json([string]$Relative) { $path = Require-File $Relative try { return (Get-Content -LiteralPath $path -Raw | ConvertFrom-Json) } catch { throw "invalid JSON: $Relative" } } function Get-Value($Object, [string]$Name) { if ($null -eq $Object) { return $null } $property = $Object.PSObject.Properties[$Name] if ($null -eq $property) { return $null } return $property.Value } function Has-Value($Object, [string]$Name) { if ($null -eq $Object) { return $false } return $null -ne $Object.PSObject.Properties[$Name] } function Assert-Equal([string]$Name, $Actual, $Expected) { if ($Actual -ne $Expected) { throw "$Name mismatch" } } function Assert-HashMap([string]$Name, $Actual, $Expected) { $actualProperties = @($Actual.PSObject.Properties | Sort-Object Name) $expectedProperties = @($Expected.PSObject.Properties | Sort-Object Name) if ($actualProperties.Count -ne $expectedProperties.Count) { throw "$Name key count mismatch" } for ($index = 0; $index -lt $actualProperties.Count; $index++) { if ($actualProperties[$index].Name -ne $expectedProperties[$index].Name -or $actualProperties[$index].Value -ne $expectedProperties[$index].Value) { throw "$Name mismatch" } } } function Assert-Safety([string]$Name, $Object) { Assert-Equal "$Name.verification_scope" (Get-Value $Object 'verification_scope') 'offline' Assert-Equal "$Name.hardware_validation" (Get-Value $Object 'hardware_validation') 'not_run' Assert-Equal "$Name.board_validation" (Get-Value $Object 'board_validation') 'not_run' Assert-Equal "$Name.programming_validation" (Get-Value $Object 'programming_validation') 'not_run' Assert-Equal "$Name.COM" (Get-Value $Object 'COM') $false Assert-Equal "$Name.JTAG" (Get-Value $Object 'JTAG') $false } $info = Read-Json 'package-info.json' $manifest = Read-Json 'package_manifest.json' $sourceManifest = Read-Json 'source_manifest.json' $validation = Read-Json 'evidence/validation-summary.json' $selftestResult = Read-Json 'evidence/package-selftest-result.json' $projectHash = (Get-FileHash (Require-File 'project.json') -Algorithm SHA256).Hash.ToLowerInvariant() $bitstreamHash = (Get-FileHash (Require-File 'fw.bit') -Algorithm SHA256).Hash.ToLowerInvariant() $sourceManifestHash = (Get-FileHash (Require-File 'source_manifest.json') -Algorithm SHA256).Hash.ToLowerInvariant() $validationHash = (Get-FileHash (Require-File 'evidence/validation-summary.json') -Algorithm SHA256).Hash.ToLowerInvariant() $selftestHash = (Get-FileHash (Require-File 'evidence/package-selftest-result.json') -Algorithm SHA256).Hash.ToLowerInvariant() $runId = [string](Get-Value $info 'verification_run_id') $commit = [string](Get-Value $info 'commit') $commitFull = [string](Get-Value $info 'commit_full') $tdSourceManifestHash = [string](Get-Value $info 'td_source_manifest_sha256') if ($commitFull -notmatch '^[0-9a-f]{40}$') { throw 'invalid exact commit' } if ($runId -notmatch '^[0-9a-f]{32}$') { throw 'invalid exact run id' } if ($tdSourceManifestHash -notmatch '^[0-9a-f]{64}$') { throw 'invalid TD source manifest hash' } Assert-Equal 'package-info.schema' (Get-Value $info 'schema') 'prod2u-p4-normal-v3-folder-package-info-v3' Assert-Equal 'package-info.profile' (Get-Value $info 'profile') 'prod2u-door-temp-115200-v1' Assert-Equal 'package-info.project_id' (Get-Value $info 'project_id') 'prod2u-door-temp' Assert-Equal 'package-info.verification_run_id' (Get-Value $info 'verification_run_id') $runId Assert-Equal 'package-info.commit_full' (Get-Value $info 'commit_full') $commitFull Assert-Equal 'package-info.bitstream_sha256' (Get-Value $info 'bitstream_sha256') $bitstreamHash Assert-Equal 'package-info.project_sha256' (Get-Value $info 'project_sha256') $projectHash Assert-Equal 'package-info.project_config_sha256' (Get-Value $info 'project_config_sha256') $projectHash Assert-Equal 'package-info.source_manifest_sha256' (Get-Value $info 'source_manifest_sha256') $sourceManifestHash Assert-Equal 'package-info.td_source_manifest_sha256' (Get-Value $info 'td_source_manifest_sha256') $tdSourceManifestHash Assert-Equal 'package-info.validation_summary_sha256' (Get-Value $info 'validation_summary_sha256') $validationHash Assert-Equal 'package-info.package_selftest_result_sha256' (Get-Value $info 'package_selftest_result_sha256') $selftestHash Assert-Equal 'package-info.formal_trace_manifest_sha256' (Get-Value $info 'formal_trace_manifest_sha256') ((Get-FileHash (Require-File 'evidence/formal-trace-manifest.json') -Algorithm SHA256).Hash.ToLowerInvariant()) Assert-Safety 'package-info' $info Assert-Equal 'package_manifest.schema' (Get-Value $manifest 'schema') 'prod2u-simple-package-manifest-v2' if (@('UNVERIFIED', 'VERIFIED_OFFLINE') -notcontains [string](Get-Value $manifest 'status')) { throw "unsupported package status: $((Get-Value $manifest 'status'))" } Assert-Equal 'package_manifest.run_id' (Get-Value $manifest 'run_id') $runId Assert-Equal 'package_manifest.commit_full' (Get-Value $manifest 'commit_full') $commitFull Assert-Equal 'package_manifest.bitstream_sha256' (Get-Value $manifest 'bitstream_sha256') $bitstreamHash Assert-Equal 'package_manifest.project_sha256' (Get-Value $manifest 'project_sha256') $projectHash Assert-Equal 'package_manifest.source_manifest_sha256' (Get-Value $manifest 'source_manifest_sha256') $sourceManifestHash Assert-Equal 'package_manifest.td_source_manifest_sha256' (Get-Value $manifest 'td_source_manifest_sha256') $tdSourceManifestHash Assert-Equal 'package_manifest.package_info_sha256' (Get-Value $manifest 'package_info_sha256') ((Get-FileHash (Require-File 'package-info.json') -Algorithm SHA256).Hash.ToLowerInvariant()) Assert-Safety 'package_manifest' $manifest Assert-Equal 'source_manifest.project_id' (Get-Value $sourceManifest 'project_id') 'prod2u-door-temp' Assert-Equal 'source_manifest.project_sha256' (Get-Value $sourceManifest 'project_sha256') $projectHash Assert-Equal 'source_manifest.generated_source_manifest_sha256' (Get-Value $sourceManifest 'generated_source_manifest_sha256') $tdSourceManifestHash Assert-Equal 'project_config_sha256.txt' ((Get-Content (Require-File 'project_config_sha256.txt') -Raw).Trim()) $projectHash Assert-Equal 'bitstream_sha256.txt' ((Get-Content (Require-File 'bitstream_sha256.txt') -Raw).Trim()) $bitstreamHash Assert-Equal 'validation.verification_run_id' (Get-Value $validation 'verification_run_id') $runId Assert-Equal 'validation.commit' (Get-Value $validation 'commit') $commit Assert-Equal 'validation.commit_full' (Get-Value $validation 'commit_full') $commitFull Assert-Equal 'validation.bitstream_sha256' (Get-Value $validation 'bitstream_sha256') $bitstreamHash Assert-Equal 'validation.project_config_sha256' (Get-Value $validation 'project_config_sha256') $projectHash Assert-Equal 'validation.td_source_manifest_sha256' (Get-Value $validation 'td_source_manifest_sha256') $tdSourceManifestHash Assert-Safety 'validation' $validation Assert-Equal 'package-selftest-result.verification_run_id' (Get-Value $selftestResult 'verification_run_id') $runId Assert-Equal 'package-selftest-result.commit_full' (Get-Value $selftestResult 'commit_full') $commitFull Assert-Equal 'package-selftest-result.bitstream_sha256' (Get-Value $selftestResult 'bitstream_sha256') $bitstreamHash Assert-Equal 'package-selftest-result.project_config_sha256' (Get-Value $selftestResult 'project_config_sha256') $projectHash Assert-Equal 'package-selftest-result.td_source_manifest_sha256' (Get-Value $selftestResult 'td_source_manifest_sha256') $tdSourceManifestHash Assert-Equal 'package-selftest-result.returncode' (Get-Value $selftestResult 'returncode') 0 if ((Has-Value $selftestResult 'package_info_sha256') -or (Has-Value $selftestResult 'package_selftest_result_sha256')) { throw 'package-selftest-result contains self-referential hashes' } $observedExclusions = @((Get-Value $info 'hash_exclusions') | ForEach-Object { [string]$_ } | Sort-Object) $expectedExclusions = @($excluded | Sort-Object) if (($observedExclusions -join '|') -ne ($expectedExclusions -join '|')) { throw 'package-info hash exclusions mismatch' } Assert-Equal 'package_manifest.hash_exclusions' (((Get-Value $manifest 'hash_exclusions') | ForEach-Object { [string]$_ } | Sort-Object) -join '|') ($expectedExclusions -join '|') Assert-Equal 'package-selftest-result.hash_exclusions' (((Get-Value $selftestResult 'hash_exclusions') | ForEach-Object { [string]$_ } | Sort-Object) -join '|') ($expectedExclusions -join '|') $actualFiles = [ordered]@{} Get-ChildItem -LiteralPath $PSScriptRoot -Recurse -File | ForEach-Object { $relative = $_.FullName.Substring($PSScriptRoot.Length + 1).Replace([char]92, [char]47) if ($excluded -notcontains $relative) { $actualFiles[$relative] = (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash.ToLowerInvariant() } } $actualFileMap = $actualFiles | ConvertTo-Json -Depth 100 | ConvertFrom-Json Assert-HashMap 'package-info.file_sha256' (Get-Value $info 'file_sha256') $actualFileMap Assert-HashMap 'package_manifest.file_sha256' (Get-Value $manifest 'file_sha256') $actualFileMap $selftestFileMap = Get-Value $selftestResult 'file_sha256' if ($null -eq $selftestFileMap) { $selftestFileMap = Get-Value $selftestResult 'package_file_sha256' } Assert-HashMap 'package-selftest-result.file_sha256' $selftestFileMap $actualFileMap $receiptFiles = @(Get-ChildItem -LiteralPath (Join-Path $PSScriptRoot 'evidence') -Filter '*-receipt.json' -File) if ($receiptFiles.Count -lt 7) { throw 'receipt set is incomplete' } $receiptHashes = [ordered]@{} foreach ($receiptFile in $receiptFiles) { $receiptRelative = 'evidence/' + $receiptFile.Name $receiptHashes[$receiptRelative] = (Get-FileHash -LiteralPath $receiptFile.FullName -Algorithm SHA256).Hash.ToLowerInvariant() $receipt = Read-Json $receiptRelative Assert-Equal "$($receiptFile.Name).verification_run_id" (Get-Value $receipt 'verification_run_id') $runId $receiptCommit = [string](Get-Value $receipt 'commit_full') if (-not $receiptCommit) { $receiptCommit = [string](Get-Value $receipt 'commit') } Assert-Equal "$($receiptFile.Name).commit" $receiptCommit $commitFull Assert-Equal "$($receiptFile.Name).project_config_sha256" (Get-Value $receipt 'project_config_sha256') $projectHash Assert-Equal "$($receiptFile.Name).td_source_manifest_sha256" (Get-Value $receipt 'td_source_manifest_sha256') $tdSourceManifestHash if (Has-Value $receipt 'verification_scope') { Assert-Safety $receiptFile.Name $receipt } } $receiptHashObject = $receiptHashes | ConvertTo-Json -Depth 100 | ConvertFrom-Json Assert-HashMap 'package-info.receipt_sha256' (Get-Value $info 'receipt_sha256') $receiptHashObject Assert-HashMap 'package-manifest.receipt_sha256' (Get-Value $manifest 'receipt_sha256') $receiptHashObject $formalReceipt = Read-Json 'evidence/formal-receipt.json' $traceManifest = Read-Json 'evidence/formal-trace-manifest.json' Assert-Equal 'formal-trace-manifest.formal_receipt_sha256' (Get-Value $traceManifest 'formal_receipt_sha256') ((Get-FileHash (Require-File 'evidence/formal-receipt.json') -Algorithm SHA256).Hash.ToLowerInvariant()) $declaredTraces = @() foreach ($trace in @((Get-Value $formalReceipt 'trace_files'))) { if ($trace -and $declaredTraces -notcontains [string]$trace) { $declaredTraces += [string]$trace } } foreach ($target in @((Get-Value $formalReceipt 'targets'))) { foreach ($trace in @((Get-Value $target 'trace_files'))) { if ($trace -and $declaredTraces -notcontains [string]$trace) { $declaredTraces += [string]$trace } } foreach ($task in @((Get-Value $target 'task_results'))) { foreach ($trace in @((Get-Value $task 'trace_files'))) { if ($trace -and $declaredTraces -notcontains [string]$trace) { $declaredTraces += [string]$trace } } } } $traceEntries = @((Get-Value $traceManifest 'files')) if ($declaredTraces.Count -ne $traceEntries.Count) { throw 'formal trace count mismatch' } $traceHashes = [ordered]@{} foreach ($entry in $traceEntries) { $tracePath = [string](Get-Value $entry 'path') $traceHash = [string](Get-Value $entry 'sha256') if (-not $tracePath -or -not $traceHash) { throw 'formal trace manifest entry is incomplete' } $traceHashes[$tracePath] = (Get-FileHash (Require-File $tracePath) -Algorithm SHA256).Hash.ToLowerInvariant() Assert-Equal "formal-trace.$tracePath" $traceHashes[$tracePath] $traceHash } $traceHashObject = $traceHashes | ConvertTo-Json -Depth 100 | ConvertFrom-Json Assert-HashMap 'formal-trace-manifest.file_sha256' (Get-Value $traceManifest 'file_sha256') $traceHashObject "package provenance selftest passed" """.replace("\n", "\r\n") 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 _copy_formal_traces( *, source_receipt: Path, formal_receipt: Mapping[str, Any], package: Path, repo: Path, ) -> dict[str, Any]: raw_trace_files: list[Any] = [] top_level_traces = formal_receipt.get("trace_files", []) if isinstance(top_level_traces, list): raw_trace_files.extend(top_level_traces) elif isinstance(top_level_traces, str) and top_level_traces.strip(): raw_trace_files.append(top_level_traces) targets = formal_receipt.get("targets", []) if isinstance(targets, list): for target in targets: if not isinstance(target, Mapping): continue traces = target.get("trace_files", []) if isinstance(traces, list): raw_trace_files.extend(traces) elif isinstance(traces, str) and traces.strip(): raw_trace_files.append(traces) task_results = target.get("task_results", []) if isinstance(task_results, list): for task in task_results: if not isinstance(task, Mapping): continue task_traces = task.get("trace_files", []) if isinstance(task_traces, list): raw_trace_files.extend(task_traces) elif isinstance(task_traces, str) and task_traces.strip(): raw_trace_files.append(task_traces) if raw_trace_files is None or raw_trace_files == "": trace_files: list[Any] = [] elif isinstance(raw_trace_files, str): trace_files = [raw_trace_files] elif isinstance(raw_trace_files, list): trace_files = raw_trace_files else: raise ValueError("formal receipt trace_files must be a list") unique_trace_files: list[Any] = [] seen_trace_files: set[str] = set() for raw_trace in trace_files: key = raw_trace if isinstance(raw_trace, str) else repr(raw_trace) if key not in seen_trace_files: seen_trace_files.add(key) unique_trace_files.append(raw_trace) trace_files = unique_trace_files trace_root = package / "evidence" / "formal-traces" trace_root.mkdir(parents=True, exist_ok=True) entries: list[dict[str, str]] = [] file_sha256: dict[str, str] = {} used_names: set[str] = set() for index, raw_trace in enumerate(trace_files): if not isinstance(raw_trace, str) or not raw_trace.strip(): raise ValueError("formal receipt contains an invalid trace path") trace_value = Path(raw_trace) candidates = ( [trace_value] if trace_value.is_absolute() else [source_receipt.parent / trace_value, repo / trace_value, Path.cwd() / trace_value] ) source_path = next((candidate.resolve() for candidate in candidates if candidate.is_file()), None) if source_path is None: raise FileNotFoundError(f"formal trace is missing: {raw_trace}") name = source_path.name if name in used_names: name = f"{index:02d}-{name}" while name in used_names: name = f"{index:02d}-{name}" used_names.add(name) destination = trace_root / name shutil.copy2(source_path, destination) relative = destination.relative_to(package).as_posix() digest = sha256_file(destination) file_sha256[relative] = digest entries.append( { "source": raw_trace, "path": relative, "sha256": digest, } ) manifest = { "schema": "prod2u-p4-normal-v3-formal-trace-manifest-v1", "formal_receipt": "evidence/formal-receipt.json", "formal_receipt_sha256": sha256_file(package / "evidence" / "formal-receipt.json"), "files": entries, "file_sha256": file_sha256, } _write_json(package / "evidence" / "formal-trace-manifest.json", manifest) return manifest 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, offline_receipt: Path | 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 if package_class == "UNVERIFIED_FINAL_CANDIDATE" and offline_receipt is not None: identity = _git_identity(repo) if identity["head"] != commit_full: raise ValueError("final package commit does not match current HEAD") clean = _run_git(repo, ["status", "--porcelain"]).stdout.decode("utf-8", "replace") if clean: raise ValueError("final package requires a clean worktree") 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( _package_selftest_script(), 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") td_source_manifest_sha256 = sha256_file(repo / SOURCE_MANIFEST_PATH) if source_manifest_sha256 is not None and source_manifest_sha256 != observed_source_manifest_sha256: raise ValueError("source manifest hash mismatch") offline_payload: dict[str, Any] | None = None if offline_receipt is not None: try: loaded = json.loads(Path(offline_receipt).read_text(encoding="utf-8-sig")) except (OSError, UnicodeError, json.JSONDecodeError) as exc: raise ValueError(f"offline receipt is not readable JSON: {offline_receipt}") from exc if not isinstance(loaded, dict): raise ValueError("offline receipt root must be an object") expected_bindings = { "verification_run_id": run_id, "commit_full": commit_full, "project_config_sha256": project_config_sha256, "td_source_manifest_sha256": td_source_manifest_sha256, } for field, expected in expected_bindings.items(): if loaded.get(field) != expected: raise ValueError(f"offline receipt binding mismatch for {field}") if loaded.get("status") != "pass": raise ValueError("offline receipt must have status=pass") offline_payload = loaded shutil.copy2(Path(offline_receipt), evidence / "software-offline-receipt.json") receipt_sources = dict(verification_receipts or {}) formal_receipt_source: Path | None = None formal_receipt_value: Mapping[str, Any] | None = None 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, td_source_manifest_sha256=td_source_manifest_sha256, receipt_role="td-primary", require_bitstream_sha256=True, ) 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, td_source_manifest_sha256=td_source_manifest_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}") copied_receipt = _copy_bound_receipt( source_path, evidence / filename, run_id=run_id, commit=commit_full, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256, td_source_manifest_sha256=td_source_manifest_sha256, receipt_role=name, preserve_bitstream_sha256=name == "td-confirmation", require_bitstream_sha256=name == "td-primary", ) if name == "formal": formal_receipt_source = source_path formal_receipt_value = copied_receipt else: placeholder = _receipt_payload( name=name, run_id=run_id, commit=commit_full, bitstream_sha256=bitstream_sha256, project_config_sha256=project_config_sha256, td_source_manifest_sha256=td_source_manifest_sha256, ) _write_json( evidence / filename, placeholder, ) if name == "formal": formal_receipt_source = repo formal_receipt_value = placeholder if formal_receipt_value is None: raise ValueError("formal receipt was not generated") _copy_formal_traces( source_receipt=formal_receipt_source or repo, formal_receipt=formal_receipt_value, package=package, repo=repo, ) (package / "project_config_sha256.txt").write_text( project_config_sha256 + "\n", encoding="ascii", newline="\n" ) (package / "bitstream_sha256.txt").write_text( bitstream_sha256 + "\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), "td_source_manifest_sha256": td_source_manifest_sha256, "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) _write_json( evidence / "package-selftest-result.json", { "schema": "prod2u-p4-normal-v3-package-selftest-result-v1", "status": "not_run", "returncode": 0, "verification_run_id": run_id, "commit": commit_full, "commit_full": commit_full, "bitstream_sha256": bitstream_sha256, "project_config_sha256": project_config_sha256, "td_source_manifest_sha256": td_source_manifest_sha256, "verification_scope": "offline", "hardware_validation": "not_run", "board_validation": "not_run", "programming_validation": "not_run", "COM": False, "JTAG": False, "hash_exclusions": sorted(PACKAGE_HASH_EXCLUSIONS), "file_sha256": _package_file_hashes(package), "package_file_sha256": _package_file_hashes(package), }, ) receipt_paths = { relative: sha256_file(package / relative) for relative in PACKAGE_RECEIPT_PATHS } if offline_payload is not None: receipt_paths["evidence/software-offline-receipt.json"] = sha256_file( evidence / "software-offline-receipt.json" ) formal_trace_manifest_path = evidence / "formal-trace-manifest.json" 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": td_source_manifest_sha256, "software_offline_receipt": "evidence/software-offline-receipt.json" if offline_payload is not None else None, "receipt_sha256": receipt_paths, "formal_trace_manifest": "evidence/formal-trace-manifest.json", "formal_trace_manifest_sha256": sha256_file(formal_trace_manifest_path), "hash_exclusions": sorted(PACKAGE_HASH_EXCLUSIONS), "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": td_source_manifest_sha256, "software_offline_receipt": "evidence/software-offline-receipt.json" if offline_payload is not None else None, "receipt_sha256": receipt_paths, "validation_summary": "evidence/validation-summary.json", "validation_summary_sha256": sha256_file(evidence / "validation-summary.json"), "formal_trace_manifest": "evidence/formal-trace-manifest.json", "formal_trace_manifest_sha256": sha256_file(formal_trace_manifest_path), "package_selftest_result": "evidence/package-selftest-result.json", "hash_exclusions": sorted(PACKAGE_HASH_EXCLUSIONS), "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("--offline-receipt", type=Path) 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, offline_receipt=args.offline_receipt, package_class=args.package_class, )) return 0 if __name__ == "__main__": raise SystemExit(main())