| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828 |
- #!/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,
- ) -> 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,
- "bitstream_sha256": bitstream_sha256,
- "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
- 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"}:
- 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,
- )
- 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": "urgent_single_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",
- }
- _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": "urgent_single_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_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",
- }
- _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,
- "file_sha256": _package_file_hashes(package),
- "hardware_validation": "not_run",
- }
- _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"),
- 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())
|