#!/usr/bin/env python3 """Create a comprehensive, sanitized CPLD workspace handoff archive.""" from __future__ import annotations import argparse import gzip import hashlib import importlib.util import io import json import os import re import shutil import stat import subprocess import sys import tarfile import tempfile import tomllib import unicodedata import uuid import zipfile from collections import Counter from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path from typing import BinaryIO, Callable, Iterable, Iterator, cast ROOT = Path(__file__).resolve().parents[1] ARCHIVE_ROOT = "CPLD" METADATA_ROOT = f"{ARCHIVE_ROOT}/HANDOFF-METADATA" SECRET_SCAN_OVERLAP = 512 MAX_ARCHIVE_DEPTH = 3 MAX_ARCHIVE_MEMBERS = 100_000 MAX_ARCHIVE_UNCOMPRESSED_BYTES = 8 * 1024 * 1024 * 1024 SECRET_PATTERNS = ( ( "private key", re.compile( rb"-----BEGIN " + rb"(?:ENCRYPTED |RSA |DSA |EC |OPENSSH )?" + rb"PRIVATE KEY-----" + rb"|-----BEGIN PGP " + rb"PRIVATE KEY BLOCK-----" ), ), ( "GitHub token", re.compile( rb"(?:"/\\|?*') class PackagingError(RuntimeError): """Raised when a handoff archive cannot be produced safely.""" @dataclass(frozen=True) class Candidate: absolute: Path relative: str size: int mtime_ns: int device: int inode: int mode: int @dataclass class CandidateSnapshot: stream: BinaryIO inventory: dict[str, object] @dataclass class ArchiveScanBudget: member_count: int = 0 uncompressed_bytes: int = 0 @dataclass(frozen=True) class ScanContext: changxin_version: str | None profile: str = "full" def utc_now() -> str: return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") def find_7z() -> Path | None: discovered = shutil.which("7z") or shutil.which("7zz") candidates = [ Path(discovered) if discovered else None, Path(r"C:\Program Files\7-Zip\7z.exe"), Path(r"C:\Program Files (x86)\7-Zip\7z.exe"), ] for candidate in candidates: if candidate is not None and candidate.is_file(): return candidate.resolve(strict=True) return None def build_7zip_create_command(archive_path: Path, staging_root: Path) -> list[str]: del staging_root return [ "a", "-tzip", "-mm=Deflate", "-mx=9", "-mmt", "-y", "-r", str(archive_path), "CPLD\\*", ] def run_7zip(seven_zip: Path, arguments: list[str], *, cwd: Path) -> str: try: completed = subprocess.run( [str(seven_zip), *arguments], cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace", timeout=300, check=False, ) except (OSError, subprocess.TimeoutExpired) as exc: raise PackagingError("unable to run 7-Zip") from exc if completed.returncode != 0: detail = completed.stdout.strip().splitlines() suffix = f": {detail[-1]}" if detail else "" raise PackagingError(f"7-Zip failed{suffix}") return completed.stdout def rename_archive_entries( seven_zip: Path, archive_path: Path, renames: list[tuple[str, str]], ) -> None: for offset in range(0, len(renames), 64): batch = renames[offset : offset + 64] arguments = ["rn", "-y", str(archive_path)] for old_name, new_name in batch: arguments.extend((old_name, new_name)) run_7zip(seven_zip, arguments, cwd=archive_path.parent) def validate_windows_component(component: str, relative: str) -> str: if component.endswith((" ", ".")): raise PackagingError(f"path component has a Windows-unsafe trailing character: {relative}") if any(ord(character) < 32 or character in WINDOWS_INVALID_FILENAME_CHARS for character in component): raise PackagingError(f"path component contains a Windows-invalid character: {relative}") normalized = component.casefold() if normalized.split(".", 1)[0] in WINDOWS_RESERVED_NAMES: raise PackagingError(f"Windows reserved device name is not portable: {relative}") return normalized def normalize_relative(parts: Iterable[str]) -> str: try: relative = unicodedata.normalize("NFC", "/".join(parts)) relative.encode("utf-8", errors="strict") except UnicodeError as exc: raise PackagingError("path is not valid UTF-8") from exc components = relative.split("/") if not relative or relative.startswith("/") or any(part in {"", ".", ".."} for part in components): raise PackagingError(f"unsafe relative path: {relative!r}") for component in components: validate_windows_component(component, relative) return relative def windows_collision_key(relative: str) -> str: components = [] for component in unicodedata.normalize("NFC", relative).split("/"): if not component: raise PackagingError(f"path component is empty after Windows normalization: {relative}") normalized = validate_windows_component(component, relative) components.append(normalized) return "/".join(components) def is_under(relative: str, prefix: str) -> bool: return relative == prefix or relative.startswith(prefix + "/") def load_scan_context(root: Path, *, profile: str = "full") -> ScanContext: pyproject = root / "tools" / "changxin-temp-uart" / "pyproject.toml" version: str | None = None try: raw_payload = read_stable_regular_bytes( pyproject, "Changxin pyproject", max_bytes=1024 * 1024, ) payload = tomllib.loads(raw_payload.decode("utf-8-sig", errors="strict")) value = payload.get("project", {}).get("version") if isinstance(value, str) and value.strip(): version = value.strip() except (PackagingError, UnicodeError, tomllib.TOMLDecodeError): version = None return ScanContext(version, profile=profile) def secret_path_reason(relative: str, *, is_dir: bool) -> str | None: if is_dir: return None name = relative.rsplit("/", 1)[-1].casefold() parts = relative.casefold().split("/") suffix = Path(name).suffix.casefold() if name == ".env" or ( name.startswith(".env.") and not name.endswith((".example", ".sample", ".template", ".dist")) ): return "secret_environment_file" if name in {"id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"} or name.startswith("id_rsa."): return "private_key_file" if name in {".netrc", "_netrc", ".pypirc", ".npmrc", ".git-credentials"}: return "credential_configuration_file" if len(parts) >= 2 and parts[-2:] == [".aws", "credentials"]: return "cloud_credential_file" if len(parts) >= 2 and parts[-2:] == [".docker", "config.json"]: return "container_registry_credential_file" if len(parts) >= 2 and parts[-2:] == ["gcloud", "application_default_credentials.json"]: return "cloud_credential_file" if suffix in {".key", ".pfx", ".p12", ".lic"}: return "credential_or_license_file" return None def common_file_exclusion_reason(relative: str) -> str | None: lower = relative.casefold() name = lower.rsplit("/", 1)[-1] suffix = Path(name).suffix.casefold() if suffix in {".pyc", ".pyo"}: return "python_bytecode" if suffix in {".tmp", ".partial", ".part", ".swp", ".swo"} or name.endswith("~"): return "atomic_or_editor_temporary_file" if suffix == ".dmp" or name.startswith("minidump-"): return "crash_dump" if name == "a.out" or (name.startswith("tmp_last_pkg") and name.endswith(".txt")): return "temporary_build_artifact" if name in {".ds_store", "thumbs.db", "desktop.ini"}: return "os_metadata_cache" if name in {".coverage", "coverage.xml"}: return "coverage_cache" if name.startswith(".coverage."): return "coverage_cache" if lower.startswith("td/td_") and suffix in {".log", ".logw"}: return "td_root_runtime_log" if "/" not in lower and lower.startswith("td_") and suffix in {".log", ".logw"}: return "td_root_runtime_log" generated_binary_suffixes = { ".bit", ".bid", ".data", ".db", ".sqlite", ".timing", ".rpt", ".area", ".qor", ".vvp", } if name in {"status.sqlite", "logfile.txt"} and "/tests/formal/" in f"/{lower}/": return "formal_workdir_artifact" if suffix in generated_binary_suffixes: if suffix == ".bit" and lower.startswith("evidence/bitstream/"): return None return "generated_binary_artifact" if suffix == ".exe": return "vendor_executable" # Vendor tool installers / release archives must never enter analysis packages. # Covers root OSS CAD suite .tgz, Anlogic TD/BW release zips, and similar. if name.startswith(("bw_release_", "td_release_", "oss-cad-suite")) and ( suffix in {".zip", ".tgz", ".tar", ".gz", ".7z", ".rar"} or name.endswith((".tar.gz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz")) ): return "vendor_toolchain_archive" if "license" in name and suffix in {".zip", ".tgz", ".7z", ".rar"}: return "license_archive" if name.endswith((".lic",)) or name in {"anlogic.lic"}: return "credential_or_license_file" return None def exclusion_reason(relative: str, *, is_dir: bool, context: ScanContext) -> str | None: lower = relative.casefold() parts = lower.split("/") raw_parts = relative.split("/") name = parts[-1] if parts[0] == "handoff-metadata": raise PackagingError(f"source uses reserved package path: {relative}") secret_reason = secret_path_reason(relative, is_dir=is_dir) if secret_reason: return secret_reason explicit_roots = { ".git": "raw_git_metadata", ".codegraph": "external_codegraph_cache", ".omo": "agent_session_runtime", ".hypothesis": "hypothesis_cache", ".pytest_cache": "pytest_cache", ".chatgpt-handoff": "chatgpt_handoff_runtime_not_in_compact", ".playwright-upload-cache": "playwright_upload_cache", "workspace": "deprecated_workspace", "_archive": "deprecated_archive", "unused": "unused_workspace_area", "log": "runtime_log_directory", "dist": "generated_handoff_output", "anlogic_cd": "vendor_installer_payload", "receipts/local": "local_runtime_receipt", "j6-binary921-deliverables": "generated_delivery_package", "j6tmp-v2-tailfix-package": "generated_delivery_package", "cpld-deliverables": "generated_delivery_package", "runs": "run_state_directory", } for prefix, reason in explicit_roots.items(): if is_under(lower, prefix): return reason if lower in {"td/project/.lock.f", "td/project/.recent_user_depot.ini"}: return "td_gui_runtime_state" if is_under(lower, "td/project/log"): return "td_gui_runtime_log" if is_under(lower, "td/project") and len(parts) >= 3 and parts[2].endswith("_runs"): return "td_gui_runtime_run" if any(component.endswith("_Runs") for component in raw_parts): return "generated_run_directory" if lower == "tests/cocotb/results.xml": return "cocotb_transient_result" if not is_dir: common_reason = common_file_exclusion_reason(relative) if common_reason: return common_reason cache_components = { ".git": "raw_git_metadata", ".codegraph": "external_codegraph_cache", ".codex": "codex_local_runtime", "__pycache__": "python_bytecode_cache", ".pytest_cache": "pytest_cache", ".hypothesis": "hypothesis_cache", ".mypy_cache": "mypy_cache", ".ruff_cache": "ruff_cache", ".tox": "tox_environment", ".nox": "nox_environment", ".venv": "virtual_environment", "venv": "virtual_environment", "htmlcov": "coverage_report", "sim_build": "simulation_build", "obj_dir": "verilator_build", "node_modules": "node_modules_runtime", ".playwright-browsers": "browser_runtime_cache", "build": "build_output", "runs": "run_state_directory", } for component in parts: if component in cache_components: return cache_components[component] if component.endswith(".egg-info"): return "python_package_metadata" if component == "dist": return "generated_delivery_output" if component == ".logs": return "td_generated_run_directory" if is_under(lower, ".codex"): return "codex_local_runtime" if is_under(lower, "tools/changxin-temp-uart/build"): return "python_package_build_copy" if is_under(lower, "tools/changxin-temp-uart/pyinstaller-build"): return "pyinstaller_build_cache" if is_under(lower, "tools/changxin-temp-uart/pyinstaller-spec"): return "pyinstaller_spec_cache" if lower in { "tools/changxin-temp-uart/pyinstaller-entry.py", "tools/changxin-temp-uart/linux-onefile-build.json", "tools/changxin-temp-uart/changxin-temp-uart-static", }: return "pyinstaller_generated_output" if lower == "tools/changxin-temp-uart/dist": return None if is_under(lower, "tools/changxin-temp-uart/dist"): return None if is_under(lower, "td/build"): return "td_build_output" if lower == "tmp": return None if is_under(lower, "tmp"): transient_tmp_roots = { "tmp/rtl_sim": "compiled_rtl_simulation", "tmp/cocotb": "cocotb_runtime", "tmp/detector_selftest": "detector_selftest_runtime", "tmp/toolchain_probe": "toolchain_probe_runtime", "tmp/edge-headless-profile": "browser_runtime_profile", "tmp/td": "td_runtime_snapshot", "tmp/refactor": "compiled_refactor_probe", } for prefix, reason in transient_tmp_roots.items(): if is_under(lower, prefix): return reason for evidence_prefix in ( "tmp/resource_audit", "tmp/pwm_executor_probe", ): if is_under(lower, evidence_prefix): evidence_parts = parts[len(evidence_prefix.split("/")) :] if "td_user_env" in evidence_parts: return "td_staged_source_or_runtime_copy" return None if len(parts) == 2 and parts[1].startswith("pytest-"): return "temporary_test_runtime" return None return None def code_only_exclusion_reason(relative: str, *, is_dir: bool) -> str | None: lower = relative.casefold() name = lower.rsplit("/", 1)[-1] for prefix, reason in CODE_ONLY_ROOT_EXCLUSIONS.items(): if is_under(lower, prefix): return reason if not is_dir and is_under(lower, "tools/board-viewer/generated"): if name in CODE_ONLY_GENERATED_VISUAL_ASSETS: return "generated_board_viewer_visual_asset" return None def is_board_viewer_fixture_path(relative: str) -> bool: return is_under(relative.casefold(), "tests/board_viewer/fixtures") def is_review_profile(profile: str) -> bool: return profile in REVIEW_PROFILES def uses_unified_layout(profile: str) -> bool: return profile in UNIFIED_LAYOUT_PROFILES def delivery_policy_for_profile(profile: str) -> str: if profile == "code-only": return "code-only" if profile in REVIEW_PROFILES: return profile return "inclusion-first" def review_exclusion_reason(relative: str, *, is_dir: bool, profile: str) -> str | None: """Extra exclusions for review-* / archive-local unified packages.""" lower = relative.casefold() name = lower.rsplit("/", 1)[-1] if name.startswith(".run_id"): return "run_id_marker" if name in {"evidence-batch-summary.txt"}: return "stale_run_summary" # Adversarial payload blobs are generated in temp during tests; never ship them # long-term inside review-compact / review-debug volumes. if is_under(lower, "tests/fixtures/package_adversarial/payloads"): if profile in {"review-compact", "review-debug"}: return "adversarial_fixture_payload" for prefix, reason in REVIEW_ORIGINAL_ROOT_EXCLUSIONS.items(): if is_under(lower, prefix): return reason if is_board_viewer_fixture_path(relative): return None if not is_dir: suffix = Path(name).suffix.casefold() if suffix in REVIEW_HEAVY_ORIGINAL_SUFFIXES: return "heavy_design_original_not_packaged" if name.endswith((".lic",)) or name in {"anlogic.lic"}: return "credential_or_license_file" if "license" in name and suffix in {".zip", ".tgz", ".7z", ".rar", ".txt", ".pdf"}: return "license_material" # review-compact / review-debug: never ship vendor toolchain installers. # archive-local leaves this to shared common_file_exclusion_reason (may still # exclude; do not broaden compact policy by skipping here). if profile in {"review-compact", "review-debug"}: common_reason = common_file_exclusion_reason(relative) if common_reason in { "vendor_toolchain_archive", "vendor_executable", "license_archive", }: return common_reason return None def make_exclusion_resolver(profile: str) -> Callable[..., str | None]: if profile not in HANDOFF_PROFILES: raise PackagingError(f"unsupported handoff profile: {profile}") def resolve(relative: str, *, is_dir: bool, context: ScanContext) -> str | None: if profile == "code-only": code_only_reason = code_only_exclusion_reason(relative, is_dir=is_dir) if code_only_reason: return code_only_reason base = exclusion_reason(relative, is_dir=is_dir, context=context) if base: return base if is_review_profile(profile): return review_exclusion_reason(relative, is_dir=is_dir, profile=profile) return None return resolve def stat_is_reparse_point(file_stat: os.stat_result) -> bool: attributes = int(getattr(file_stat, "st_file_attributes", 0)) reparse_flag = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0)) return stat.S_ISLNK(file_stat.st_mode) or bool(reparse_flag and attributes & reparse_flag) def is_reparse_point(entry: os.DirEntry[str], file_stat: os.stat_result) -> bool: return entry.is_symlink() or stat_is_reparse_point(file_stat) def invalid_receipt_reason(path: Path, relative: str, size: int) -> str | None: if not relative.casefold().startswith("receipts/") or not relative.casefold().endswith(".json"): return None if size == 0: return "empty_receipt" if size <= 32: try: if path.read_bytes().strip().lower() == b"null": return "null_receipt" except OSError as exc: raise PackagingError(f"unable to inspect receipt {relative}: {exc}") from exc return None def scan_tree( root: Path, *, exclusion_resolver: Callable[..., str | None] | None = None, profile: str = "full", ) -> tuple[list[Candidate], list[dict[str, str]], ScanContext]: context = load_scan_context(root, profile=profile) resolve_exclusion = exclusion_resolver or exclusion_reason included: list[Candidate] = [] excluded: list[dict[str, str]] = [] collision_paths: dict[str, str] = {} def record_exclusion(relative: str, reason: str) -> None: excluded.append({"path": relative, "rule": reason}) def walk(directory: Path, relative_parts: tuple[str, ...]) -> None: try: with os.scandir(directory) as iterator: entries = sorted( list(iterator), key=lambda item: unicodedata.normalize("NFC", item.name).casefold(), ) except OSError as exc: relative = "/".join(relative_parts) or "." raise PackagingError(f"unable to enumerate {relative}: {exc}") from exc for entry in entries: relative = normalize_relative((*relative_parts, entry.name)) scan_secret_markers(relative.encode("utf-8"), b"", "[source path]") try: file_stat = os.lstat(entry.path) except OSError as exc: raise PackagingError(f"unable to inspect {relative}: {exc}") from exc is_directory = stat.S_ISDIR(file_stat.st_mode) reason = resolve_exclusion(relative, is_dir=is_directory, context=context) if is_reparse_point(entry, file_stat): if reason: record_exclusion(relative, reason) continue raise PackagingError(f"undeclared reparse point refuses packaging: {relative}") if reason: record_exclusion(relative, reason) continue if is_directory: walk(Path(entry.path), (*relative_parts, entry.name)) continue if not stat.S_ISREG(file_stat.st_mode): raise PackagingError(f"unsupported non-regular file: {relative}") receipt_reason = invalid_receipt_reason(Path(entry.path), relative, file_stat.st_size) if receipt_reason: record_exclusion(relative, receipt_reason) continue key = windows_collision_key(relative) previous = collision_paths.get(key) if previous is not None: raise PackagingError(f"Windows ZIP path collision: {previous} and {relative}") collision_paths[key] = relative if int(file_stat.st_dev) == 0 or int(file_stat.st_ino) == 0: raise PackagingError(f"filesystem does not expose a stable file identity: {relative}") included.append( Candidate( Path(entry.path), relative, file_stat.st_size, file_stat.st_mtime_ns, int(file_stat.st_dev), int(file_stat.st_ino), int(file_stat.st_mode), ) ) walk(root, ()) included.sort(key=lambda item: windows_collision_key(item.relative)) excluded.sort(key=lambda item: (windows_collision_key(item["path"]), item["rule"])) return included, excluded, context def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def scan_secret_markers(chunk: bytes, tail: bytes, relative: str) -> bytes: combined = tail + chunk for label, pattern in SECRET_PATTERNS: if pattern.search(combined): raise PackagingError(f"high-confidence {label} secret found in {relative}") return combined[-SECRET_SCAN_OVERLAP:] def candidate_stat_matches(file_stat: os.stat_result, candidate: Candidate) -> bool: return ( stat.S_ISREG(file_stat.st_mode) and not stat_is_reparse_point(file_stat) and int(file_stat.st_dev) == candidate.device and int(file_stat.st_ino) == candidate.inode and (os.name == "nt" or int(file_stat.st_mode) == candidate.mode) and file_stat.st_size == candidate.size and file_stat.st_mtime_ns == candidate.mtime_ns ) @contextmanager def open_candidate(candidate: Candidate) -> Iterator[BinaryIO]: try: before = os.lstat(candidate.absolute) except OSError as exc: raise PackagingError(f"unable to inspect {candidate.relative} before packaging: {exc}") from exc if not candidate_stat_matches(before, candidate): raise PackagingError(f"source changed after enumeration: {candidate.relative}") flags = os.O_RDONLY flags |= int(getattr(os, "O_BINARY", 0)) flags |= int(getattr(os, "O_NOINHERIT", 0)) flags |= int(getattr(os, "O_NOFOLLOW", 0)) try: file_descriptor = os.open(candidate.absolute, flags) except OSError as exc: raise PackagingError(f"unable to open {candidate.relative} without following links: {exc}") from exc source: BinaryIO | None = None try: try: opened = os.fstat(file_descriptor) except OSError as exc: raise PackagingError(f"unable to inspect opened source {candidate.relative}: {exc}") from exc if not candidate_stat_matches(opened, candidate): raise PackagingError(f"source identity changed while opening: {candidate.relative}") source = os.fdopen(file_descriptor, "rb", closefd=True) file_descriptor = -1 try: yield source try: opened_after = os.fstat(source.fileno()) except OSError as exc: raise PackagingError(f"unable to inspect opened source {candidate.relative} after reading: {exc}") from exc finally: source.close() if not candidate_stat_matches(opened_after, candidate): raise PackagingError(f"source changed while reading: {candidate.relative}") finally: if file_descriptor >= 0: os.close(file_descriptor) try: after = os.lstat(candidate.absolute) except OSError as exc: raise PackagingError(f"unable to inspect {candidate.relative} after packaging: {exc}") from exc if not candidate_stat_matches(after, candidate): raise PackagingError(f"source changed during packaging: {candidate.relative}") @contextmanager def snapshot_candidate( candidate: Candidate, *, allow_disk: bool, ) -> Iterator[CandidateSnapshot]: snapshot = cast(BinaryIO, tempfile.TemporaryFile()) if allow_disk else cast(BinaryIO, io.BytesIO()) try: digest = hashlib.sha256() total = 0 secret_tail = b"" with open_candidate(candidate) as source: while True: chunk = source.read(1024 * 1024) if not chunk: break secret_tail = scan_secret_markers(chunk, secret_tail, candidate.relative) snapshot.write(chunk) digest.update(chunk) total += len(chunk) if total != candidate.size: raise PackagingError(f"source size changed during packaging: {candidate.relative}") snapshot.seek(0) yield CandidateSnapshot( stream=snapshot, inventory={"path": candidate.relative, "size": total, "sha256": digest.hexdigest()}, ) except MemoryError as exc: raise PackagingError(f"insufficient memory to audit source file: {candidate.relative}") from exc finally: snapshot.close() def archive_kind(name: str) -> str | None: lower = name.casefold() if lower.endswith((".zip", ".whl", ".jar", ".apk", ".nupkg")): return "zip" if lower.endswith((".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".tar")): return "tar" if lower.endswith(".gz"): return "gzip" if lower.endswith((".rar", ".7z")): return "unsupported" return None def detect_archive_kind(source: BinaryIO, name: str) -> str | None: position = source.tell() try: source.seek(0) prefix = source.read(512) source.seek(0) if zipfile.is_zipfile(source): return "zip" hint = archive_kind(name) if prefix.startswith((b"7z\xbc\xaf'\x1c", b"Rar!\x1a\x07", b"(\xb5/\xfd", b"\x04\x22\x4d\x18")): return "unsupported" if prefix.startswith((b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08")): return "zip" if prefix.startswith(b"\x1f\x8b"): return "tar" if hint == "tar" else "gzip" if prefix.startswith((b"BZh", b"\xfd7zXZ\x00")): return "tar" if len(prefix) >= 262 and prefix[257:262] == b"ustar": return "tar" if prefix.startswith((b"!\n", b"MSCF", b"xar!")): return "unsupported" return hint finally: source.seek(position) def archive_member_label(archive_label: str, member_name: str) -> str: normalized = unicodedata.normalize("NFC", member_name) if ( "\\" in normalized or "\x00" in normalized or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized) ): raise PackagingError(f"unsafe archive member path in {archive_label}") normalized = normalized.removesuffix("/") if not normalized: raise PackagingError(f"unsafe archive member path in {archive_label}") parts = normalized.split("/") if any(part in {"", ".", ".."} for part in parts): raise PackagingError(f"unsafe archive member path in {archive_label}") scan_secret_markers(normalized.encode("utf-8"), b"", f"{archive_label} member path") return f"{archive_label}!/{normalized}" def scan_archive_metadata(value: str | bytes, label: str) -> None: try: payload = value if isinstance(value, bytes) else value.encode("utf-8", errors="strict") except UnicodeError as exc: raise PackagingError(f"archive metadata is not valid UTF-8 in {label}") from exc scan_secret_markers(payload, b"", label) def account_archive_member(budget: ArchiveScanBudget, label: str) -> None: budget.member_count += 1 if budget.member_count > MAX_ARCHIVE_MEMBERS: raise PackagingError(f"archive scan resource limit exceeded in {label}") def ensure_archive_bytes_available(budget: ArchiveScanBudget, size: int, label: str) -> None: if size < 0 or budget.uncompressed_bytes + size > MAX_ARCHIVE_UNCOMPRESSED_BYTES: raise PackagingError(f"archive scan resource limit exceeded in {label}") def scan_archive_member_stream( source: BinaryIO, *, member_name: str, label: str, depth: int, budget: ArchiveScanBudget, allow_disk: bool, ) -> None: sensitive_reason = secret_path_reason(member_name.removesuffix("/"), is_dir=False) if sensitive_reason is not None: raise PackagingError( f"credential or license path found in archive member: {label} ({sensitive_reason})" ) nested = cast(BinaryIO, tempfile.TemporaryFile()) if allow_disk else cast(BinaryIO, io.BytesIO()) try: secret_tail = b"" while True: chunk = source.read(1024 * 1024) if not chunk: break ensure_archive_bytes_available(budget, len(chunk), label) budget.uncompressed_bytes += len(chunk) secret_tail = scan_secret_markers(chunk, secret_tail, label) nested.write(chunk) nested.seek(0) if detect_archive_kind(nested, member_name) is not None: scan_archive_stream( nested, name=member_name, label=label, depth=depth + 1, budget=budget, allow_disk=allow_disk, ) except MemoryError as exc: raise PackagingError(f"insufficient memory to audit archive member: {label}") from exc finally: nested.close() def scan_archive_stream( source: BinaryIO, *, name: str, label: str, depth: int, budget: ArchiveScanBudget, allow_disk: bool, ) -> None: kind = detect_archive_kind(source, name) if kind is None: return if kind == "unsupported": raise PackagingError(f"unsupported archive format cannot be secret-scanned: {label}") if depth > MAX_ARCHIVE_DEPTH: raise PackagingError(f"archive scan resource limit exceeded in {label}") try: if kind == "zip": with zipfile.ZipFile(source) as archive: scan_archive_metadata(archive.comment, f"{label} archive comment") for zip_member in archive.infolist(): account_archive_member(budget, label) member_label = archive_member_label(label, zip_member.filename) member_mode = (zip_member.external_attr >> 16) & 0xFFFF member_type = stat.S_IFMT(member_mode) scan_archive_metadata(zip_member.comment, f"{member_label} comment") scan_archive_metadata(zip_member.extra, f"{member_label} extra metadata") if zip_member.flag_bits & 0x1: raise PackagingError(f"unsafe archive member type in {member_label}") if zip_member.is_dir(): if ( zip_member.file_size != 0 or zip_member.compress_size != 0 or member_type not in {0, stat.S_IFDIR} ): raise PackagingError(f"unsafe archive member type in {member_label}") continue if member_type not in {0, stat.S_IFREG}: raise PackagingError(f"unsafe archive member type in {member_label}") ensure_archive_bytes_available(budget, zip_member.file_size, member_label) with archive.open(zip_member, "r") as zip_member_source: scan_archive_member_stream( cast(BinaryIO, zip_member_source), member_name=zip_member.filename, label=member_label, depth=depth, budget=budget, allow_disk=allow_disk, ) return if kind == "tar": with tarfile.open(fileobj=source, mode="r:*") as archive: for key, value in archive.pax_headers.items(): scan_archive_metadata(key, f"{label} global pax key") scan_archive_metadata(value, f"{label} global pax value") for tar_member in archive: account_archive_member(budget, label) member_label = archive_member_label(label, tar_member.name) for field_name, value in ( ("linkname", tar_member.linkname), ("uname", tar_member.uname), ("gname", tar_member.gname), ): scan_archive_metadata(value, f"{member_label} {field_name}") for key, value in tar_member.pax_headers.items(): scan_archive_metadata(key, f"{member_label} pax key") scan_archive_metadata(value, f"{member_label} pax value") if tar_member.isdir(): if tar_member.size != 0: raise PackagingError(f"unsafe archive member type in {member_label}") continue if not tar_member.isfile(): raise PackagingError(f"unsafe archive member type in {member_label}") ensure_archive_bytes_available(budget, tar_member.size, member_label) tar_member_source = archive.extractfile(tar_member) if tar_member_source is None: raise PackagingError(f"unable to inspect archive member in {member_label}") with tar_member_source: scan_archive_member_stream( cast(BinaryIO, tar_member_source), member_name=tar_member.name, label=member_label, depth=depth, budget=budget, allow_disk=allow_disk, ) return with gzip.GzipFile(fileobj=source, mode="rb") as gzip_member_source: scan_archive_member_stream( cast(BinaryIO, gzip_member_source), member_name=name.removesuffix(".gz"), label=f"{label}!/", depth=depth, budget=budget, allow_disk=allow_disk, ) except PackagingError: raise except (OSError, EOFError, RuntimeError, tarfile.TarError, zipfile.BadZipFile) as exc: raise PackagingError(f"unable to inspect archive safely: {label} ({type(exc).__name__})") from exc def scan_candidate_archive(candidate: Candidate) -> None: with snapshot_candidate(candidate, allow_disk=True) as snapshot: scan_archive_stream( snapshot.stream, name=candidate.relative, label=candidate.relative, depth=0, budget=ArchiveScanBudget(), allow_disk=True, ) def audit_candidates(candidates: Iterable[Candidate]) -> list[dict[str, object]]: inventory = [] for candidate in candidates: inventory.append(stream_candidate(candidate)) return inventory def zip_info(name: str, mode: int = stat.S_IFREG | 0o644) -> zipfile.ZipInfo: info = zipfile.ZipInfo(name, date_time=(1980, 1, 1, 0, 0, 0)) info.compress_type = zipfile.ZIP_DEFLATED info.create_system = 3 info.flag_bits |= 0x800 # UTF-8 filenames info.external_attr = ((stat.S_IFREG | (mode & 0o777)) & 0xFFFF) << 16 return info def stream_candidate( candidate: Candidate, target: BinaryIO | None = None, *, allow_disk: bool = True, ) -> dict[str, object]: with snapshot_candidate(candidate, allow_disk=allow_disk) as snapshot: scan_archive_stream( snapshot.stream, name=candidate.relative, label=candidate.relative, depth=0, budget=ArchiveScanBudget(), allow_disk=allow_disk, ) if target is not None: snapshot.stream.seek(0) shutil.copyfileobj(snapshot.stream, target, length=1024 * 1024) return snapshot.inventory def hash_candidate(candidate: Candidate) -> dict[str, object]: digest = hashlib.sha256() total = 0 secret_tail = b"" with open_candidate(candidate) as source: for chunk in iter(lambda: source.read(1024 * 1024), b""): secret_tail = scan_secret_markers(chunk, secret_tail, candidate.relative) digest.update(chunk) total += len(chunk) if total != candidate.size: raise PackagingError(f"source size changed during packaging: {candidate.relative}") return {"path": candidate.relative, "size": total, "sha256": digest.hexdigest()} def write_candidate(archive: zipfile.ZipFile, candidate: Candidate) -> dict[str, object]: entry_name = f"{ARCHIVE_ROOT}/{candidate.relative}" try: with archive.open(zip_info(entry_name, candidate.mode), "w", force_zip64=True) as target: return stream_candidate(candidate, target) except OSError as exc: raise PackagingError(f"unable to package {candidate.relative}: {exc}") from exc def stage_candidate( staging_root: Path, candidate: Candidate, staging_name: str | None = None, ) -> dict[str, object]: target = staging_root / ARCHIVE_ROOT / ( staging_name if staging_name is not None else Path(*candidate.relative.split("/")) ) target.parent.mkdir(parents=True, exist_ok=True) try: with target.open("wb") as destination: return stream_candidate(candidate, target=destination) except OSError as exc: raise PackagingError(f"unable to stage {candidate.relative}: {exc}") from exc def write_bytes_entry(archive: zipfile.ZipFile, name: str, payload: bytes) -> None: scan_secret_markers(payload, b"", name) with archive.open(zip_info(name), "w", force_zip64=True) as handle: handle.write(payload) def json_bytes(payload: object) -> bytes: return (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8") def path_contains_reparse_point(root: Path, candidate: Path) -> bool: root_absolute = Path(os.path.abspath(root)) candidate_absolute = Path(os.path.abspath(candidate)) try: relative = candidate_absolute.relative_to(root_absolute) except ValueError: return True current = root_absolute for component in relative.parts: current /= component try: file_stat = os.lstat(current) except OSError: return True if stat_is_reparse_point(file_stat): return True return False def resolve_git_dir(root: Path) -> Path | None: marker = root / ".git" try: marker_stat = os.lstat(marker) except OSError: return None if stat_is_reparse_point(marker_stat): return None root_resolved = root.resolve(strict=True) if stat.S_ISDIR(marker_stat.st_mode): try: candidate = marker.resolve(strict=True) candidate.relative_to(root_resolved) except (OSError, RuntimeError, ValueError): return None return candidate if stat.S_ISREG(marker_stat.st_mode): try: text = read_stable_regular_bytes(marker, ".git marker", max_bytes=4096).decode( "utf-8", errors="strict", ).strip() except (PackagingError, UnicodeError): return None if text.startswith("gitdir:"): raw_candidate = root / text.split(":", 1)[1].strip() try: candidate = raw_candidate.resolve(strict=True) candidate.relative_to(root_resolved) except (OSError, RuntimeError, ValueError): return None if path_contains_reparse_point(root_resolved, raw_candidate): return None try: candidate_stat = os.lstat(candidate) except OSError: return None return candidate if stat.S_ISDIR(candidate_stat.st_mode) and not stat_is_reparse_point(candidate_stat) else None return None def read_head_metadata(git_dir: Path) -> tuple[str | None, str | None]: try: head = read_stable_regular_bytes(git_dir / "HEAD", "Git HEAD", max_bytes=4096).decode( "ascii", errors="strict", ).strip() except (PackagingError, UnicodeError): return None, None if not head.startswith("ref: "): return None, head if re.fullmatch(r"[0-9a-fA-F]{40}", head) else None ref = head[5:].strip() ref_parts = ref.split("/") if ( not ref.startswith("refs/") or "\\" in ref or any(part in {"", ".", ".."} for part in ref_parts) or ".." in ref or "@{" in ref or ref.endswith((".", "/", ".lock")) or re.fullmatch(r"[A-Za-z0-9._/-]+", ref) is None ): return None, None branch = ref.removeprefix("refs/heads/") if ref.startswith("refs/heads/") else ref ref_file = git_dir.joinpath(*ref_parts) commit: str | None = None if os.path.lexists(ref_file): if path_contains_reparse_point(git_dir, ref_file): return branch, None try: commit = read_stable_regular_bytes(ref_file, f"Git ref {ref}", max_bytes=4096).decode( "ascii", errors="strict", ).strip() except (PackagingError, UnicodeError): return branch, None if commit is None: commit = None packed_refs = git_dir / "packed-refs" if os.path.lexists(packed_refs) and not path_contains_reparse_point(git_dir, packed_refs): try: packed_text = read_stable_regular_bytes( packed_refs, "Git packed-refs", max_bytes=16 * 1024 * 1024, ).decode("ascii", errors="strict") except (PackagingError, UnicodeError): packed_text = "" for line in packed_text.splitlines(): if not line or line.startswith(("#", "^")): continue sha, _, packed_ref = line.partition(" ") if packed_ref == ref: commit = sha break if commit and not re.fullmatch(r"[0-9a-fA-F]{40}", commit): commit = None return branch, commit def run_capture(command: list[str], *, cwd: Path, timeout: int = 60) -> tuple[int, bytes]: try: completed = subprocess.run( command, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, check=False, ) except (OSError, subprocess.TimeoutExpired): return 1, b"" return completed.returncode, completed.stdout def collect_git_provenance(root: Path) -> tuple[dict[str, object], dict[str, bytes]]: git_dir = resolve_git_dir(root) if git_dir is None: return {"status": "not_a_git_worktree", "branch": None, "head": None, "tool": None}, {} branch, head = read_head_metadata(git_dir) tool: str | None = None status_command: list[str] | None = None git = shutil.which("git") if git: tool = "git" status_command = [ git, "--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false", "status", "--short", "--branch", "--untracked-files=all", ] elif importlib.util.find_spec("dulwich") is not None: tool = "dulwich" status_command = [sys.executable, "-I", "-m", "dulwich", "status"] if status_command is None: return {"status": "blocked_missing_git_tool", "branch": branch, "head": head, "tool": None}, {} status_code, status_payload = run_capture(status_command, cwd=root) artifacts: dict[str, bytes] = {} if status_code == 0: artifacts[f"{METADATA_ROOT}/git-status.txt"] = status_payload capture_status = "pass" if status_code == 0 else "partial" return { "status": capture_status, "branch": branch, "head": head, "tool": tool, "status_captured": status_code == 0, }, artifacts def _git_bytes(git: str, args: list[str], *, cwd: Path) -> bytes | None: code, payload = run_capture([git, *args], cwd=cwd) if code != 0: return None return payload SHA256_HEX_RE = re.compile(r"^[0-9a-f]{64}$") COMMIT_FULL_RE = re.compile(r"^[0-9a-f]{40}$") def _resolve_commit_full(root: Path, commit: str | None = None) -> str | None: if commit and COMMIT_FULL_RE.fullmatch(commit.strip().casefold()): return commit.strip().casefold() git = shutil.which("git") if git is None: return None code, payload = run_capture([git, "rev-parse", "HEAD"], cwd=root) if code != 0: return None text = payload.decode("ascii", errors="replace").strip().casefold() return text if COMMIT_FULL_RE.fullmatch(text) else None def _collect_td_report_bindings( report_paths: Iterable[Path], ) -> list[dict[str, object]]: rows: list[dict[str, object]] = [] for path in report_paths: resolved = path.expanduser().resolve(strict=False) if not resolved.is_file(): rows.append( { "path": str(path), "status": "missing", "sha256": None, "bytes": None, } ) continue rows.append( { "path": str(resolved), "status": "present", "sha256": sha256_file(resolved), "bytes": resolved.stat().st_size, "name": resolved.name, } ) rows.sort(key=lambda row: str(row.get("path", "")).casefold()) return rows def discover_bitstream_candidates( root: Path, *, evidence_root: Path | None = None, ) -> list[Path]: """Locate candidate bitstreams for optional binding (does not require TD rebuild).""" candidates: list[Path] = [] search_roots = [] if evidence_root is not None: search_roots.append(evidence_root.expanduser().resolve(strict=False)) search_roots.extend( [ root / "evidence" / "bitstream", root / "td" / "build", ] ) env_bit = os.environ.get("PRODU2_BITSTREAM_PATH", "").strip() if env_bit: candidates.append(Path(env_bit).expanduser()) for base in search_roots: if not base.is_dir(): continue candidates.extend(sorted(base.rglob("*.bit"))) named = base / "prod2u_p4_normal_v3.bit" if named.is_file(): candidates.append(named) fw = base / "fw.bit" if fw.is_file(): candidates.append(fw) # Deduplicate while preserving order. seen: set[str] = set() unique: list[Path] = [] for path in candidates: key = str(path.resolve(strict=False)) if key in seen: continue seen.add(key) if path.is_file(): unique.append(path) return unique def build_td_source_closure_binding( root: Path, *, bitstream_path: Path | None = None, td_report_paths: Iterable[Path] | None = None, evidence_root: Path | None = None, commit: str | None = None, require_bitstream: bool = False, ) -> dict[str, object]: """Build TD source-closure binding; bind real bitstream when supplied. Without a bitstream the status remains ``hook_ready`` (or ``hook_partial``). When a bitstream (+ optional TD reports) is provided, status becomes ``bound`` with full commit SHA, source-manifest SHA, project SHA, and bitstream SHA-256. Integrators supply the real tip bitstream later; this path must not stay forever deferred once artifacts exist. """ root = root.expanduser().resolve(strict=True) manifest = root / "src" / "generated" / "td-source-manifest.json" project = root / "projects" / "prod2u-door-temp" / "project.json" commit_full = _resolve_commit_full(root, commit) binding: dict[str, object] = { "schema": "cpld-td-source-closure-binding-v1", "status": "hook_ready", "note": ( "Binding path accepts a real bitstream + full commit + source-manifest + " "TD reports. When those artifacts are absent, status stays hook_ready; " "it must not remain deferred once the integrator supplies them." ), "commit_full": commit_full, "commit_short": commit_full[:8] if commit_full else None, "td_source_manifest_path": "src/generated/td-source-manifest.json", "td_source_manifest_sha256": None, "project_config_path": "projects/prod2u-door-temp/project.json", "project_config_sha256": None, "bitstream": None, "td_reports": [], "bitstream_binding": "deferred_to_evidence_receipt", # Legacy alias kept for older consumers still looking for the hook schema. "legacy_schema_alias": "cpld-td-source-closure-binding-hook-v1", } if manifest.is_file(): binding["td_source_manifest_sha256"] = sha256_file(manifest) else: binding["status"] = "hook_partial" if project.is_file(): binding["project_config_sha256"] = sha256_file(project) else: binding["status"] = "hook_partial" resolved_bit = bitstream_path if resolved_bit is None: discovered = discover_bitstream_candidates(root, evidence_root=evidence_root) if len(discovered) == 1: resolved_bit = discovered[0] elif len(discovered) > 1 and evidence_root is not None: # Prefer evidence_root hits when multiple exist. evidence_hits = [ path for path in discovered if str(path.resolve(strict=False)).startswith( str(evidence_root.expanduser().resolve(strict=False)) ) ] if len(evidence_hits) == 1: resolved_bit = evidence_hits[0] report_list = list(td_report_paths or []) if not report_list and evidence_root is not None: evidence = evidence_root.expanduser().resolve(strict=False) for pattern in ( "**/td-primary-receipt.json", "**/final_td_report.json", "**/original-final_td_report.json", "**/TD-PROVENANCE.json", ): report_list.extend(sorted(evidence.glob(pattern))) binding["td_reports"] = _collect_td_report_bindings(report_list) if resolved_bit is None: if require_bitstream: binding["status"] = "bind_failed" binding["bitstream_binding"] = "missing_bitstream" binding["note"] = "require_bitstream=true but no bitstream was provided or discovered" return binding bit_path = resolved_bit.expanduser().resolve(strict=False) if not bit_path.is_file(): binding["status"] = "bind_failed" binding["bitstream_binding"] = "missing_bitstream" binding["bitstream"] = {"path": str(resolved_bit), "status": "missing"} return binding digest = sha256_file(bit_path) if not SHA256_HEX_RE.fullmatch(digest): binding["status"] = "bind_failed" binding["bitstream_binding"] = "invalid_bitstream_sha256" return binding binding["bitstream"] = { "path": str(bit_path), "name": bit_path.name, "sha256": digest, "bytes": bit_path.stat().st_size, "status": "present", } if ( commit_full and binding.get("td_source_manifest_sha256") and binding.get("project_config_sha256") ): binding["status"] = "bound" binding["bitstream_binding"] = "bound" binding["note"] = ( "Bound to real bitstream SHA-256, full commit, project config, " "td-source-manifest, and any supplied TD reports." ) else: binding["status"] = "bind_partial" binding["bitstream_binding"] = "partial" binding["note"] = ( "Bitstream hashed but commit/manifest/project identity incomplete; " "not a final closure binding." ) return binding def build_td_source_closure_binding_hook( root: Path, *, bitstream_path: Path | None = None, td_report_paths: Iterable[Path] | None = None, evidence_root: Path | None = None, commit: str | None = None, require_bitstream: bool = False, ) -> dict[str, object]: """Compatibility wrapper: bind when artifacts exist, else hook_ready.""" return build_td_source_closure_binding( root, bitstream_path=bitstream_path, td_report_paths=td_report_paths, evidence_root=evidence_root, commit=commit, require_bitstream=require_bitstream, ) def run_post_staging_reference_inventory_hook( repo_root: Path, *, staging_complete: bool, enabled: bool = True, ) -> dict[str, object]: """Refresh REFERENCE-INVENTORY only after staging completes (packager order). Lane E owns inventory generator honesty / evidence-grade docs. Lane D only enforces call order: inventory refresh must not run before staging finishes. """ repo_root = repo_root.expanduser().resolve(strict=True) report: dict[str, object] = { "schema": "cpld-reference-inventory-post-staging-hook-v1", "staging_complete": staging_complete, "enabled": enabled, "status": "not_run", "command": None, "note": ( "Packager order: finish reference staging, then refresh inventory, " "then finalize the reference volume." ), } if not enabled: report["status"] = "skipped_disabled" return report if not staging_complete: report["status"] = "blocked_staging_incomplete" report["note"] = "Refusing inventory refresh before staging_complete=true" return report refresh_py = repo_root / "tools" / "board-viewer" / "refresh_reference_inventory.py" if not refresh_py.is_file(): report["status"] = "blocked_missing_refresher" return report command = [sys.executable, "-B", str(refresh_py), "--root", str(repo_root)] report["command"] = command code, payload = run_capture(command, cwd=repo_root, timeout=300) report["returncode"] = code report["output_tail"] = payload.decode("utf-8", errors="replace")[-2000:] report["status"] = "pass" if code == 0 else "fail" return report _SANITIZED_SNAPSHOT_SKIP_PREFIXES = ( "reference/original/", "node_modules/", ".venv/", "venv/", "__pycache__/", ".git/", "tmp/", "tools/board-viewer/node_modules/", ) _SANITIZED_SNAPSHOT_SKIP_SUFFIXES = ( ".pdf", ".brd", ".dsn", ".zip", ".7z", ".rar", ".bundle", ) _SANITIZED_SNAPSHOT_FIXTURE_KEEP = "tests/board_viewer/fixtures/" def allow_sanitized_snapshot_path(relative: str) -> bool: """Filter tracked paths for the optional synthetic single-commit snapshot.""" rel = relative.replace("\\", "/").lstrip("./") lower = rel.casefold() if any(lower.startswith(prefix) for prefix in _SANITIZED_SNAPSHOT_SKIP_PREFIXES): return False if lower.startswith(_SANITIZED_SNAPSHOT_FIXTURE_KEEP.casefold()): return True if any(lower.endswith(suffix) for suffix in _SANITIZED_SNAPSHOT_SKIP_SUFFIXES): return False name = lower.rsplit("/", 1)[-1] if name.startswith(".run_id"): return False return True def create_sanitized_git_snapshot( root: Path, *, git: str, original_head: str | None, temp_root: Path, meta_prefix: str = "meta/git", file_rels: Iterable[str] | None = None, ) -> tuple[dict[str, object], dict[str, bytes]]: """Build a synthetic single-commit git bundle with synthetic→original mapping. The synthetic commit must never be presented as the original tip. """ work = temp_root / "sanitized-git-snapshot-work" if work.exists(): shutil.rmtree(work) work.mkdir(parents=True, exist_ok=True) code, _ = run_capture([git, "init", "-q"], cwd=work) if code != 0: status = { "requested": True, "status": "fail_git_init", "original_commit": original_head, "impersonates_original_tip": False, } return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)} for cfg_key, cfg_val in ( ("user.name", "Prod2U Sanitized Snapshot"), ("user.email", "sanitized-snapshot@invalid.local"), ): run_capture([git, "config", cfg_key, cfg_val], cwd=work) selected: list[str] = [] if file_rels is None: ls_files = _git_bytes(git, ["ls-files", "-z"], cwd=root) if ls_files is None: status = { "requested": True, "status": "fail_ls_files", "original_commit": original_head, "impersonates_original_tip": False, } return status, { f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status) } file_rels = [ raw.decode("utf-8", errors="surrogateescape") for raw in ls_files.split(b"\0") if raw ] for rel in file_rels: if not allow_sanitized_snapshot_path(rel): continue src = root / Path(*rel.split("/")) if not src.is_file(): continue dest = work / Path(*rel.split("/")) dest.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(src, dest) selected.append(rel.replace("\\", "/")) selected.sort() if not selected: status = { "requested": True, "status": "fail_empty_snapshot", "original_commit": original_head, "impersonates_original_tip": False, "file_count": 0, } return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)} code, _ = run_capture([git, "add", "-A"], cwd=work) if code != 0: status = { "requested": True, "status": "fail_git_add", "original_commit": original_head, "impersonates_original_tip": False, } return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)} message = ( f"synthetic sanitized snapshot of {original_head or 'unknown'}\n\n" "This is a synthetic single-commit snapshot for detached review.\n" "It does NOT impersonate the original tip commit.\n" ) code, _ = run_capture([git, "commit", "-q", "-m", message], cwd=work) if code != 0: status = { "requested": True, "status": "fail_git_commit", "original_commit": original_head, "impersonates_original_tip": False, } return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)} synthetic_raw = _git_bytes(git, ["rev-parse", "HEAD"], cwd=work) synthetic = ( synthetic_raw.decode("utf-8", errors="replace").strip() if synthetic_raw is not None else None ) if not synthetic or synthetic == original_head: status = { "requested": True, "status": "fail_synthetic_identity", "original_commit": original_head, "synthetic_commit": synthetic, "impersonates_original_tip": False, "note": "Synthetic commit must be distinct from original tip.", } return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)} bundle_path = temp_root / "sanitized-snapshot.bundle" code, verify = run_capture( [git, "bundle", "create", str(bundle_path), "HEAD"], cwd=work, ) if code != 0 or not bundle_path.is_file(): status = { "requested": True, "status": "fail_bundle_create", "original_commit": original_head, "synthetic_commit": synthetic, "impersonates_original_tip": False, "detail": verify.decode("utf-8", errors="replace")[:500], } return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)} mapping = { "schema": "cpld-sanitized-git-snapshot-mapping-v1", "synthetic_commit": synthetic, "original_commit": original_head, "impersonates_original_tip": False, "file_count": len(selected), "files": selected, "note": ( "Synthetic→original mapping only. Consumers must treat synthetic_commit " "as a packaging artifact, never as the repository tip." ), } status = { "requested": True, "status": "pass", "synthetic_commit": synthetic, "original_commit": original_head, "impersonates_original_tip": False, "bundle_path": f"{meta_prefix}/sanitized-snapshot.bundle", "mapping_path": f"{meta_prefix}/sanitized-snapshot-mapping.json", "file_count": len(selected), "note": ( "Optional sanitized synthetic single-commit snapshot. " "Records synthetic→original mapping and must not impersonate the original tip." ), } artifacts = { f"{meta_prefix}/sanitized-snapshot.bundle": bundle_path.read_bytes(), f"{meta_prefix}/sanitized-snapshot-mapping.json": json_bytes(mapping), f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status), } return status, artifacts def live_git_cli_usable(root: Path) -> bool: """True when ``git -C root`` reports an inside-work-tree checkout. Unlike ``resolve_git_dir``, this accepts linked worktrees whose ``gitdir:`` points outside the worktree root (required for clean DELIVERY worktrees). """ git = shutil.which("git") if not git: return False code, payload = run_capture( [git, "rev-parse", "--is-inside-work-tree"], cwd=root, ) return code == 0 and payload.decode("ascii", errors="replace").strip() == "true" def _hash_exact_commit_tree( git: str, root: Path, commit: str, *, temp_root: Path, ) -> tuple[list[dict[str, object]], dict[str, str], list[str]]: """SHA-256 tracked files from exact commit via ``git archive`` (not dirty WT).""" work = temp_root / f"commit-tree-{commit[:12]}" if work.exists(): shutil.rmtree(work) work.mkdir(parents=True, exist_ok=True) tar_path = temp_root / f"commit-tree-{commit[:12]}.tar" code, err = run_capture( [git, "archive", "--format=tar", "-o", str(tar_path), commit], cwd=root, timeout=600, ) if code != 0 or not tar_path.is_file(): detail = err.decode("utf-8", errors="replace")[:500] raise PackagingError( f"git archive {commit} failed for review provenance: {detail}" ) with tarfile.open(tar_path, "r:") as archive: # filter='data' avoids 3.14 deprecation and blocks unsafe paths. try: archive.extractall(work, filter="data") except TypeError: archive.extractall(work) tree_rows: list[dict[str, object]] = [] file_hashes: dict[str, str] = {} file_rels: list[str] = [] for path in sorted(work.rglob("*")): if not path.is_file(): continue rel = path.relative_to(work).as_posix() digest = sha256_file(path) file_rels.append(rel) file_hashes[rel] = digest tree_rows.append({"path": rel, "sha256": digest, "size": path.stat().st_size}) return tree_rows, file_hashes, file_rels def validate_review_git_provenance_artifacts( artifacts: dict[str, bytes], *, meta_prefix: str = "meta/git", expected_head: str | None = None, ) -> list[str]: """Fail-closed checks for review-compact Git provenance members.""" failures: list[str] = [] required = ( f"{meta_prefix}/HEAD.txt", f"{meta_prefix}/branch.txt", f"{meta_prefix}/status.txt", f"{meta_prefix}/log-20.txt", f"{meta_prefix}/tree-manifest.json", f"{meta_prefix}/source-file-sha256.json", ) for key in required: if key not in artifacts: failures.append(f"missing_{key.replace('/', '_')}") head_raw = artifacts.get(f"{meta_prefix}/HEAD.txt", b"").decode("utf-8", errors="replace").strip() if not COMMIT_FULL_RE.fullmatch(head_raw.casefold()): failures.append("invalid_HEAD") if expected_head and head_raw.casefold() != expected_head.casefold(): failures.append("HEAD_mismatch_expected") try: tree = json.loads(artifacts.get(f"{meta_prefix}/tree-manifest.json", b"{}")) files = json.loads( artifacts.get( f"{meta_prefix}/source-file-sha256.json", artifacts.get(f"{meta_prefix}/file-sha256.json", b"{}"), ) ) except (TypeError, json.JSONDecodeError): failures.append("invalid_tree_or_file_sha_json") return failures tree_head = str(tree.get("head") or "") files_head = str(files.get("head") or "") if tree_head.casefold() != head_raw.casefold() or files_head.casefold() != head_raw.casefold(): failures.append("HEAD_tree_file_sha_inconsistent") tree_files = tree.get("files") if isinstance(tree.get("files"), list) else [] hash_map = files.get("files") if isinstance(files.get("files"), dict) else {} if int(tree.get("file_count") or 0) != len(tree_files): failures.append("tree_manifest_count_mismatch") if len(tree_files) == 0: failures.append("tree_manifest_empty") tree_paths = {str(row.get("path")) for row in tree_files if isinstance(row, dict)} if tree_paths != set(hash_map): failures.append("tree_manifest_hash_map_path_mismatch") for row in tree_files: if not isinstance(row, dict): continue path = str(row.get("path") or "") digest = str(row.get("sha256") or "") if path and hash_map.get(path) != digest: failures.append(f"file_hash_mismatch:{path}") break return failures def collect_review_git_provenance( root: Path, *, include_sanitized_git_snapshot: bool = False, meta_prefix: str = "meta/git", temp_root: Path | None = None, require_clean: bool = False, require_clean_untracked: bool = False, commit: str | None = None, ) -> tuple[dict[str, object], dict[str, bytes]]: """Git provenance for review-* packages: no full bundle; commit/status/log/tree/hashes. Uses the live ``git`` CLI so linked DELIVERY worktrees work even when ``resolve_git_dir`` rejects an external ``gitdir:``. Tree/file SHA-256 are taken from the exact commit via ``git archive``, never from a dirty WT scan. """ artifacts: dict[str, bytes] = {} git = shutil.which("git") if not git or not live_git_cli_usable(root): metadata: dict[str, object] = { "status": "not_a_git_worktree", "branch": None, "head": None, "tool": None if not git else "git", "full_bundle": False, "sanitized_git_snapshot": { "requested": include_sanitized_git_snapshot, "status": "not_applicable", }, } artifacts[f"{meta_prefix}/sanitized-snapshot-status.json"] = json_bytes( metadata["sanitized_git_snapshot"] ) return metadata, artifacts if not git: return { "status": "blocked_missing_git_tool", "branch": None, "head": None, "tool": None, "full_bundle": False, "sanitized_git_snapshot": { "requested": include_sanitized_git_snapshot, "status": "blocked_missing_git_tool", }, }, { f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes( { "requested": include_sanitized_git_snapshot, "status": "blocked_missing_git_tool", } ) } rev_parse = _git_bytes(git, ["rev-parse", "HEAD"], cwd=root) head = ( rev_parse.decode("utf-8", errors="replace").strip() if rev_parse is not None else None ) if commit: # Format-check alone is insufficient — commit must exist in this repo. verified = _git_bytes( git, ["rev-parse", "--verify", f"{commit}^{{commit}}"], cwd=root, ) if verified is None: return { "status": "fail_invalid_commit", "branch": None, "head": head, "tool": "git", "full_bundle": False, "sanitized_git_snapshot": { "requested": include_sanitized_git_snapshot, "status": "not_applicable", }, }, { f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes( { "requested": include_sanitized_git_snapshot, "status": "not_applicable", } ) } head = verified.decode("utf-8", errors="replace").strip().casefold() if not head or not COMMIT_FULL_RE.fullmatch(head.casefold()): return { "status": "fail_missing_HEAD", "branch": None, "head": head, "tool": "git", "full_bundle": False, "sanitized_git_snapshot": { "requested": include_sanitized_git_snapshot, "status": "not_applicable", }, }, { f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes( { "requested": include_sanitized_git_snapshot, "status": "not_applicable", } ) } head = head.casefold() branch_raw = _git_bytes(git, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root) branch = ( branch_raw.decode("utf-8", errors="replace").strip() if branch_raw is not None else None ) if branch == "HEAD": # Detached HEAD at exact DELIVERY — record detached + commit, not fake branch. branch = f"detached:{head}" # Prefer embedded .git metadata when packager-safe; CLI remains authority. git_dir = resolve_git_dir(root) if git_dir is not None: meta_branch, meta_head = read_head_metadata(git_dir) if meta_branch and not str(branch).startswith("detached:"): branch = meta_branch if meta_head and COMMIT_FULL_RE.fullmatch(meta_head.casefold()) and not commit: # Keep CLI HEAD (exact tip) as authority when packing current tip. pass status_payload = _git_bytes( git, [ "--no-optional-locks", "-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false", "status", "--short", "--branch", "--untracked-files=all", ], cwd=root, ) # Dirty gate: require_clean fails on tracked dirt. Final-review also requires # untracked-files=all empty (package from a dedicated clean worktree). porcelain = _git_bytes( git, [ "--no-optional-locks", "-c", "core.fsmonitor=false", "status", "--porcelain=v1", "--untracked-files=all" if (require_clean and require_clean_untracked) else "--untracked-files=no", ], cwd=root, ) dirty = bool(porcelain and porcelain.strip()) if require_clean and dirty: return { "status": "fail_dirty_worktree", "branch": branch, "head": head, "tool": "git", "full_bundle": False, "dirty": True, "sanitized_git_snapshot": { "requested": include_sanitized_git_snapshot, "status": "not_applicable", }, }, { f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes( { "requested": include_sanitized_git_snapshot, "status": "not_applicable", } ) } log_payload = _git_bytes( git, ["log", "-20", "--format=%H %ad %s", "--date=iso-strict", head], cwd=root, ) snap_temp = temp_root if temp_root is not None else Path( tempfile.mkdtemp(prefix="prod2u-review-git-", dir=os.environ.get("TMPDIR", "/tmp")) ) snap_temp.mkdir(parents=True, exist_ok=True) try: tree_rows, file_hashes, file_rels = _hash_exact_commit_tree( git, root, head, temp_root=snap_temp ) except PackagingError: return { "status": "fail_commit_tree_archive", "branch": branch, "head": head, "tool": "git", "full_bundle": False, "sanitized_git_snapshot": { "requested": include_sanitized_git_snapshot, "status": "not_applicable", }, }, { f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes( { "requested": include_sanitized_git_snapshot, "status": "not_applicable", } ) } artifacts[f"{meta_prefix}/HEAD.txt"] = f"{head}\n".encode("utf-8") if branch: artifacts[f"{meta_prefix}/branch.txt"] = f"{branch}\n".encode("utf-8") if status_payload is not None: artifacts[f"{meta_prefix}/status.txt"] = status_payload if log_payload is not None: artifacts[f"{meta_prefix}/log-20.txt"] = log_payload artifacts[f"{meta_prefix}/tree-manifest.json"] = json_bytes( { "schema": "cpld-review-git-tree-manifest-v1", "head": head, "file_count": len(tree_rows), "source": "git_archive_exact_commit", "files": tree_rows, } ) file_sha_payload = json_bytes( { "schema": "cpld-review-git-file-sha256-v1", "head": head, "source": "git_archive_exact_commit", "files": file_hashes, } ) # Canonical name per finalize layout; keep legacy alias for older consumers. artifacts[f"{meta_prefix}/source-file-sha256.json"] = file_sha_payload artifacts[f"{meta_prefix}/file-sha256.json"] = file_sha_payload if include_sanitized_git_snapshot: snapshot_status, snap_artifacts = create_sanitized_git_snapshot( root, git=git, original_head=head, temp_root=snap_temp, meta_prefix=meta_prefix, file_rels=file_rels, ) artifacts.update(snap_artifacts) else: snapshot_status = { "requested": False, "status": "not_requested", "impersonates_original_tip": False, "note": ( "Optional sanitized synthetic single-commit snapshot via " "--include-sanitized-git-snapshot. When present it records " "synthetic→original mapping and must not impersonate the original tip. " "It cannot replace HEAD/tree/per-file SHA-256 live provenance." ), } artifacts[f"{meta_prefix}/sanitized-snapshot-status.json"] = json_bytes( snapshot_status ) validation_failures = validate_review_git_provenance_artifacts( artifacts, meta_prefix=meta_prefix, expected_head=head ) capture_status = "pass" if status_payload is None or log_payload is None or validation_failures: capture_status = "partial" if not validation_failures else "fail_provenance_incomplete" if validation_failures: capture_status = "fail_provenance_incomplete" return { "status": capture_status, "branch": branch, "head": head, "tool": "git", "full_bundle": False, "dirty": dirty, "status_captured": status_payload is not None, "log20_captured": log_payload is not None, "tree_manifest_files": len(tree_rows), "tree_source": "git_archive_exact_commit", "validation_failures": validation_failures, "sanitized_git_snapshot": snapshot_status, }, artifacts def build_size_budget( inventory: list[dict[str, object]], *, zip_total_bytes: int | None = None, ) -> dict[str, object]: """Members ≥256KiB or >1% of ZIP (when known) enter the size-budget table.""" total = int(zip_total_bytes) if zip_total_bytes is not None else sum( int(item.get("size", 0)) for item in inventory ) rows: list[dict[str, object]] = [] for item in inventory: size = int(item.get("size", 0)) share = (size / total) if total > 0 else 0.0 if size >= SIZE_BUDGET_MIN_BYTES or share > SIZE_BUDGET_MIN_SHARE: rows.append( { "path": str(item.get("path", "")), "size": size, "share_of_total": round(share, 6), "reason": ( "gte_256kiB" if size >= SIZE_BUDGET_MIN_BYTES else "gt_1pct_of_package" ), } ) rows.sort(key=lambda row: (-int(row["size"]), str(row["path"]).casefold())) return { "schema": "cpld-review-size-budget-v1", "total_bytes_basis": total, "threshold_bytes": SIZE_BUDGET_MIN_BYTES, "threshold_share": SIZE_BUDGET_MIN_SHARE, "members": rows, } def package_purpose_text( profile: str, *, package_name: str, package_stage: str = "final-review", ) -> str: stage = str(package_stage or "final-review").strip().casefold().replace("_", "-") if stage in {"intermediate", "non-final"}: stage = "intermediate-review" lines = [ f"PACKAGE-PURPOSE: {package_name}", f"profile: {profile}", f"package_stage: {stage}", f"delivery_policy: {delivery_policy_for_profile(profile)}", "", ] if stage == "intermediate-review": lines.extend( [ "INTERMEDIATE / NON-FINAL review package (MSE A1 verification closure).", "P0/P1 RTL fixes may be present; fresh TD/bitstream closure is NOT claimed.", "Do not treat this ZIP as a final release set.", "", ] ) if profile == "review-compact": lines.extend( [ "Default remote-agent upload package.", "Layout: source/ (active code+tests) + evidence/ (canonical final receipts, derived board-viewer) + meta/.", "Does NOT include a full Git bundle, PDF/BRD/DSN originals, vendor installer zips, or license material.", "Git provenance is commit/status/log-20/tree manifest/per-file SHA-256 plus TD source-closure binding.", "meta/td-source-closure-binding.json binds real bitstream SHA-256 + full commit + source-manifest + TD reports when supplied; otherwise hook_ready until the integrator provides the tip bit.", "Evidence is physically deduplicated; process lane receipts / matrix reruns require review-debug or --include-process-evidence.", "Result-sensitive logs: PASS/not_run keep summaries; FAIL/BLOCKED/TIMEOUT/CRASH keep full evidence.", "Hardware validation remains not_run unless a future task authorizes it.", ] ) elif profile == "review-debug": lines.extend( [ "Debug-oriented review package (unified layout).", "Same heavy-original exclusions as review-compact; includes process evidence by default.", "Still omits full Git history bundles by default.", ] ) elif profile == "archive-local": lines.extend( [ "Local archival package (not the default upload).", "May include a full Git bundle / --include-full-history for offline restore.", "Still uses unified source/evidence/meta layout.", ] ) else: lines.append("Legacy inclusion-first or code-only analysis handoff.") lines.append("") return "\n".join(lines) def build_metadata( *, package_name: str, profile: str, inventory: list[dict[str, object]], excluded: list[dict[str, str]], context: ScanContext, provenance: dict[str, object], ) -> dict[str, bytes]: rule_counts = Counter(item["rule"] for item in excluded) derived_evidence = [] for item in inventory: path = str(item["path"]) name = path.casefold().rsplit("/", 1)[-1] if name not in CODE_ONLY_GENERATED_VISUAL_ASSETS and name not in { "board-data.json", "build-info.json", "import-report.json", }: continue if "tools/board-viewer/generated/" not in path.casefold(): continue role = ( "derived_from_brd_visual" if name in CODE_ONLY_GENERATED_VISUAL_ASSETS else "derived_from_brd_parsed" ) derived_evidence.append( { "path": path, "asset": name, "role": role, "authority": "analysis_evidence_not_source_closure", "note": "Derived from the original Allegro BRD for remote analysis; not RTL/TD source closure.", } ) authority_boundary = ( "Inclusion-first analysis handoff of source, requirements, tests, original references, " "board-viewer derived evidence (JSON/SVG labeled not source closure), and retained evidence. " "It excludes credentials, license archives, vendor installers, caches, node_modules, venvs, " "raw Git objects, and declared reconstructable runtime outputs." ) if profile == "code-only": authority_boundary = ( "This archive is a code-and-tests-only analysis handoff. It excludes reference materials, " "generated board-viewer visual assets, credentials, private archives, raw Git objects, " "and declared reconstructable runtime outputs." ) derived_evidence = [] elif is_review_profile(profile): authority_boundary = ( "Unified review package (source/evidence/meta). Keeps board-viewer derived assets and " "small test fixtures; excludes PDF/BRD/DSN originals, vendor installers, license material, " "caches, venvs, node_modules, and full Git bundles unless archive-local/--include-full-history." ) manifest = { "schema": "cpld-agent-handoff-v1", "status": "pass", "created_at": utc_now(), "package_name": package_name, "profile": profile, "delivery_policy": delivery_policy_for_profile(profile), "archive_root": ARCHIVE_ROOT, "source_name": ARCHIVE_ROOT, "included_file_count": len(inventory), "included_bytes": sum(int(item["size"]) for item in inventory), "excluded_entry_count": len(excluded), "exclusion_rule_counts": dict(sorted(rule_counts.items())), "derived_evidence": derived_evidence, "changxin_temp_uart_version": context.changxin_version, "git_provenance": provenance, "archive_scan_limits": { "max_depth": MAX_ARCHIVE_DEPTH, "max_members": MAX_ARCHIVE_MEMBERS, "max_uncompressed_bytes": MAX_ARCHIVE_UNCOMPRESSED_BYTES, "source_file_size_limit": None, }, "privacy": { "manifest_contains_absolute_source_path": False, "note": "Repository files are preserved byte-for-byte; review document and receipt contents before crossing a trust boundary.", }, "authority_boundary": authority_boundary, } exclusions_payload = { "schema": "cpld-agent-handoff-exclusions-v1", "excluded": excluded, "rule_counts": dict(sorted(rule_counts.items())), } inventory_payload = { "schema": "cpld-agent-handoff-sha256-inventory-v1", "inventory": inventory, } return { f"{METADATA_ROOT}/manifest.json": json_bytes(manifest), f"{METADATA_ROOT}/exclusions.json": json_bytes(exclusions_payload), f"{METADATA_ROOT}/sha256-inventory.json": json_bytes(inventory_payload), } def validate_zip_entry(name: str) -> str: if not name.startswith(ARCHIVE_ROOT + "/") or "\\" in name or name.startswith("/"): raise PackagingError(f"unsafe ZIP entry: {name}") relative = name[len(ARCHIVE_ROOT) + 1 :] normalize_relative(relative.split("/")) return windows_collision_key(name) def verify_archive( path: Path | BinaryIO, *, expected_names: set[str], inventory: list[dict[str, object]], expected_payloads: dict[str, bytes] | None = None, ) -> None: try: with zipfile.ZipFile(path, "r", allowZip64=True) as archive: names = archive.namelist() if len(names) != len(set(names)): raise PackagingError("ZIP contains duplicate entry names") file_names = [name for name in names if not name.endswith("/")] collision_keys: dict[str, str] = {} for name in names: if name.endswith("/"): if name == ARCHIVE_ROOT + "/": continue if not name.startswith(ARCHIVE_ROOT + "/"): raise PackagingError(f"unsafe ZIP directory entry: {name}") relative_directory = name[len(ARCHIVE_ROOT) + 1 :].removesuffix("/") normalize_relative(relative_directory.split("/")) continue key = validate_zip_entry(name) previous = collision_keys.get(key) if previous is not None and previous != name: raise PackagingError(f"ZIP contains a Windows path collision: {previous} and {name}") collision_keys[key] = name if set(file_names) != expected_names: missing = sorted(expected_names - set(file_names)) unexpected = sorted(set(file_names) - expected_names) raise PackagingError(f"ZIP entry verification failed; missing={missing}, unexpected={unexpected}") bad = archive.testzip() if bad is not None: raise PackagingError(f"ZIP CRC verification failed for {bad}") for item in inventory: entry_name = f"{ARCHIVE_ROOT}/{item['path']}" digest = hashlib.sha256() total = 0 with archive.open(entry_name, "r") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) total += len(chunk) if total != item["size"] or digest.hexdigest() != item["sha256"]: raise PackagingError(f"ZIP SHA256 verification failed for {item['path']}") for name, expected_payload in (expected_payloads or {}).items(): if archive.read(name) != expected_payload: raise PackagingError(f"ZIP generated metadata verification failed for {name}") except (OSError, zipfile.BadZipFile) as exc: raise PackagingError(f"unable to verify ZIP archive: {exc}") from exc def publish_target_identity(file_stat: os.stat_result) -> tuple[int, int, int, int, int]: return ( int(file_stat.st_dev), int(file_stat.st_ino), int(file_stat.st_mode), int(file_stat.st_size), int(file_stat.st_mtime_ns), ) def stat_is_windows_read_only(file_stat: os.stat_result) -> bool: attributes = int(getattr(file_stat, "st_file_attributes", 0)) read_only_flag = int(getattr(stat, "FILE_ATTRIBUTE_READONLY", 0)) return bool(read_only_flag and attributes & read_only_flag) def stat_is_read_only(file_stat: os.stat_result) -> bool: return stat_is_windows_read_only(file_stat) or (int(file_stat.st_mode) & 0o222) == 0 def validate_publish_targets(paths: Iterable[Path], *, force: bool) -> dict[Path, tuple[int, int, int, int, int]]: existing: dict[Path, tuple[int, int, int, int, int]] = {} for path in paths: if not os.path.lexists(path): continue if not force: raise PackagingError(f"package artifact already exists: {path.name}") try: file_stat = os.lstat(path) except OSError as exc: raise PackagingError(f"unable to inspect existing package artifact {path.name}: {exc}") from exc if not stat.S_ISREG(file_stat.st_mode) or stat_is_reparse_point(file_stat): raise PackagingError(f"existing package artifact is not a regular file: {path.name}") if stat_is_read_only(file_stat): raise PackagingError(f"existing package artifact is read-only: {path.name}") existing[path] = publish_target_identity(file_stat) return existing def publish_artifacts_atomically( artifacts: list[tuple[Path, Path]], *, force: bool, verify_published: Callable[[], None] | None = None, ) -> list[str]: backups: dict[Path, Path] = {} published: list[Path] = [] final_paths = [final_path for _, final_path in artifacts] existing = validate_publish_targets(final_paths, force=force) try: for _, final_path in artifacts: expected_identity = existing.get(final_path) if expected_identity is not None: try: current = os.lstat(final_path) except OSError as exc: raise PackagingError(f"existing package artifact changed before publication: {final_path.name}") from exc if ( not stat.S_ISREG(current.st_mode) or stat_is_reparse_point(current) or stat_is_read_only(current) or publish_target_identity(current) != expected_identity ): raise PackagingError(f"existing package artifact changed before publication: {final_path.name}") backup = final_path.with_name(f".{final_path.name}.{uuid.uuid4().hex}.backup") os.replace(final_path, backup) backups[final_path] = backup elif os.path.lexists(final_path): raise PackagingError(f"package artifact appeared during publication: {final_path.name}") for temp_path, final_path in artifacts: os.link(temp_path, final_path) published.append(final_path) if verify_published is not None: verify_published() except BaseException as exc: rollback_errors: list[str] = [] for final_path in reversed(published): if final_path in backups: continue try: final_path.unlink(missing_ok=True) except OSError as rollback_exc: rollback_errors.append( f"remove {final_path.name} ({type(rollback_exc).__name__})" ) for final_path, backup in backups.items(): if os.path.lexists(backup): try: os.replace(backup, final_path) except OSError as rollback_exc: rollback_errors.append( f"restore {final_path.name} from {backup.name} ({type(rollback_exc).__name__})" ) if rollback_errors: recovery_paths = sorted( str(path) for path in (*backups.values(), *published) if os.path.lexists(path) ) recovery = ", ".join(recovery_paths) if recovery_paths else "none" details = "; ".join(rollback_errors) raise PackagingError( f"package publication failed and rollback was incomplete: {details}; " f"manual recovery paths: {recovery}" ) from exc if isinstance(exc, PackagingError): raise if isinstance(exc, OSError): raise PackagingError(f"unable to publish package artifacts atomically: {exc}") from exc raise cleanup_warnings: list[str] = [] for temp_path, _ in artifacts: try: temp_path.unlink(missing_ok=True) except OSError as exc: cleanup_warnings.append( f"published temporary artifact could not be removed: {temp_path.name} ({type(exc).__name__})" ) for backup in backups.values(): try: backup.unlink(missing_ok=True) except OSError as exc: cleanup_warnings.append( f"published artifact backup could not be removed: {backup.name} ({type(exc).__name__})" ) return cleanup_warnings def remove_partial_artifacts(paths: Iterable[Path]) -> None: failures: list[str] = [] for path in paths: try: path.unlink(missing_ok=True) except OSError: failures.append(path.name) if failures: names = ", ".join(sorted(failures)) raise PackagingError(f"unable to remove partial package artifacts: {names}") @contextmanager def open_stable_regular_file(path: Path, label: str) -> Iterator[BinaryIO]: try: before = os.lstat(path) except OSError as exc: raise PackagingError(f"unable to inspect {label}: {exc}") from exc if not stat.S_ISREG(before.st_mode) or stat_is_reparse_point(before): raise PackagingError(f"published artifact is not a regular file: {label}") flags = os.O_RDONLY flags |= int(getattr(os, "O_BINARY", 0)) flags |= int(getattr(os, "O_NOINHERIT", 0)) flags |= int(getattr(os, "O_NOFOLLOW", 0)) try: descriptor = os.open(path, flags) except OSError as exc: raise PackagingError(f"unable to open {label} without following links: {exc}") from exc handle: BinaryIO | None = None try: opened = os.fstat(descriptor) if publish_target_identity(opened) != publish_target_identity(before): raise PackagingError(f"published artifact changed while opening: {label}") handle = os.fdopen(descriptor, "rb", closefd=True) descriptor = -1 yield handle opened_after = os.fstat(handle.fileno()) if publish_target_identity(opened_after) != publish_target_identity(opened): raise PackagingError(f"published artifact changed while reading: {label}") finally: if handle is not None: handle.close() if descriptor >= 0: os.close(descriptor) try: after = os.lstat(path) except OSError as exc: raise PackagingError(f"unable to re-inspect {label}: {exc}") from exc if publish_target_identity(after) != publish_target_identity(before): raise PackagingError(f"published artifact changed during verification: {label}") def read_stable_regular_bytes(path: Path, label: str, *, max_bytes: int) -> bytes: with open_stable_regular_file(path, label) as handle: payload = handle.read(max_bytes + 1) if len(payload) > max_bytes: raise PackagingError(f"regular file exceeds safe metadata read limit: {label}") return payload def verify_published_artifacts( final_zip: Path, final_sidecar: Path, *, expected_zip_sha256: str, expected_sidecar: bytes, expected_names: set[str], inventory: list[dict[str, object]], expected_payloads: dict[str, bytes], ) -> None: digest = hashlib.sha256() with open_stable_regular_file(final_zip, final_zip.name) as handle: verify_archive( handle, expected_names=expected_names, inventory=inventory, expected_payloads=expected_payloads, ) handle.seek(0) for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) if digest.hexdigest() != expected_zip_sha256: raise PackagingError("published ZIP SHA256 does not match the verified package") with open_stable_regular_file(final_sidecar, final_sidecar.name) as handle: actual_sidecar = handle.read() if actual_sidecar != expected_sidecar: raise PackagingError("published SHA256 sidecar does not match the verified package") def scan_snapshot( candidates: Iterable[Candidate], excluded: Iterable[dict[str, str]], context: ScanContext, ) -> tuple[tuple[tuple[object, ...], ...], tuple[tuple[str, str], ...], ScanContext]: candidate_state = tuple( ( item.relative, item.size, item.mtime_ns, item.device, item.inode, item.mode, ) for item in candidates ) excluded_state = tuple((item["path"], item["rule"]) for item in excluded) return candidate_state, excluded_state, context def assert_source_tree_unchanged( root: Path, candidates: list[Candidate], excluded: list[dict[str, str]], context: ScanContext, inventory: list[dict[str, object]], *, exclusion_resolver: Callable[..., str | None] | None = None, ) -> None: current_candidates, current_excluded, current_context = scan_tree( root, exclusion_resolver=exclusion_resolver, profile=context.profile, ) if scan_snapshot(candidates, excluded, context) != scan_snapshot( current_candidates, current_excluded, current_context, ): raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot") expected_by_path = {str(item["path"]): item for item in inventory} if len(expected_by_path) != len(current_candidates): raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot") for candidate in current_candidates: current = hash_candidate(candidate) expected = expected_by_path.get(candidate.relative) if ( expected is None or current["size"] != expected["size"] or current["sha256"] != expected["sha256"] ): raise PackagingError("source tree changed during packaging; retry from a stable workspace snapshot") def _build_package_with_zipfile( temp_zip: Path, *, root: Path, package_name: str, profile: str, candidates: list[Candidate], excluded: list[dict[str, str]], context: ScanContext, provenance: dict[str, object], provenance_artifacts: dict[str, bytes], ) -> tuple[list[dict[str, object]], dict[str, bytes], dict[str, bytes]]: """Fallback ZIP writer when 7-Zip is not available.""" inventory: list[dict[str, object]] = [] with zipfile.ZipFile( temp_zip, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9, allowZip64=True, ) as archive: for candidate in candidates: inventory.append(write_candidate(archive, candidate)) metadata_artifacts = build_metadata( package_name=package_name, profile=profile, inventory=inventory, excluded=excluded, context=context, provenance=provenance, ) for name, payload in sorted({**metadata_artifacts, **provenance_artifacts}.items()): write_bytes_entry(archive, name, payload) return inventory, metadata_artifacts, provenance_artifacts def _build_package_with_7z( seven_zip: Path, temp_zip: Path, *, root: Path, package_name: str, profile: str, token: str, output_dir: Path, candidates: list[Candidate], excluded: list[dict[str, str]], context: ScanContext, provenance: dict[str, object], provenance_artifacts: dict[str, bytes], ) -> tuple[list[dict[str, object]], dict[str, bytes], dict[str, bytes], Path]: inventory: list[dict[str, object]] = [] archive_renames: list[tuple[str, str]] = [] staging_root = Path(tempfile.mkdtemp(prefix=f".{package_name}.{token}.stage.", dir=output_dir)) try: for number, candidate in enumerate(candidates): staging_name = f"candidate-{number:08d}" inventory.append(stage_candidate(staging_root, candidate, staging_name)) archive_renames.append( ( f"{ARCHIVE_ROOT}/{staging_name}", f"{ARCHIVE_ROOT}/{candidate.relative}", ) ) metadata_artifacts = build_metadata( package_name=package_name, profile=profile, inventory=inventory, excluded=excluded, context=context, provenance=provenance, ) for name, payload in sorted({**metadata_artifacts, **provenance_artifacts}.items()): target = staging_root / Path(*name.split("/")) target.parent.mkdir(parents=True, exist_ok=True) scan_secret_markers(payload, b"", name) target.write_bytes(payload) run_7zip( seven_zip, build_7zip_create_command(temp_zip, staging_root), cwd=staging_root, ) rename_archive_entries(seven_zip, temp_zip, archive_renames) except BaseException: shutil.rmtree(staging_root, ignore_errors=True) raise return inventory, metadata_artifacts, provenance_artifacts, staging_root def create_package( *, root: Path, output_dir: Path, package_name: str, force: bool, candidates: list[Candidate], excluded: list[dict[str, str]], context: ScanContext, profile: str = "full", exclusion_resolver: Callable[..., str | None] | None = None, ) -> dict[str, object]: # Prefer Python zipfile so UTF-8 arcnames stay consistent on Linux/Windows. # 7-Zip remains available as an optional verifier, not the primary writer. seven_zip = None output_dir.mkdir(parents=True, exist_ok=True) final_zip = output_dir / f"{package_name}.zip" final_sidecar = output_dir / f"{package_name}.zip.sha256.txt" validate_publish_targets((final_zip, final_sidecar), force=force) token = f"{os.getpid()}.{uuid.uuid4().hex}" temp_zip = output_dir / f".{package_name}.{token}.partial" temp_sidecar = output_dir / f".{package_name}.{token}.sha256.partial" inventory: list[dict[str, object]] = [] provenance, provenance_artifacts = collect_git_provenance(root) metadata_artifacts: dict[str, bytes] = {} staging_root: Path | None = None try: if seven_zip is None: inventory, metadata_artifacts, provenance_artifacts = _build_package_with_zipfile( temp_zip, root=root, package_name=package_name, profile=profile, candidates=candidates, excluded=excluded, context=context, provenance=provenance, provenance_artifacts=provenance_artifacts, ) else: inventory, metadata_artifacts, provenance_artifacts, staging_root = _build_package_with_7z( seven_zip, temp_zip, root=root, package_name=package_name, profile=profile, token=token, output_dir=output_dir, candidates=candidates, excluded=excluded, context=context, provenance=provenance, provenance_artifacts=provenance_artifacts, ) expected_names = {f"{ARCHIVE_ROOT}/{item['path']}" for item in inventory} expected_names.update(metadata_artifacts) expected_names.update(provenance_artifacts) expected_payloads = {**metadata_artifacts, **provenance_artifacts} try: with open_stable_regular_file(temp_zip, temp_zip.name) as verified_zip: verify_archive( verified_zip, expected_names=expected_names, inventory=inventory, expected_payloads=expected_payloads, ) verified_zip.seek(0) zip_digest = hashlib.sha256() for chunk in iter(lambda: verified_zip.read(1024 * 1024), b""): zip_digest.update(chunk) zip_sha256 = zip_digest.hexdigest() except OSError as exc: raise PackagingError("temporary ZIP changed during stable verification") from exc assert_source_tree_unchanged( root, candidates, excluded, context, inventory, exclusion_resolver=exclusion_resolver, ) sidecar_payload = f"{zip_sha256} {final_zip.name}\n".encode("ascii") temp_sidecar.write_bytes(sidecar_payload) def verify_publication() -> None: verify_published_artifacts( final_zip, final_sidecar, expected_zip_sha256=zip_sha256, expected_sidecar=sidecar_payload, expected_names=expected_names, inventory=inventory, expected_payloads=expected_payloads, ) assert_source_tree_unchanged( root, candidates, excluded, context, inventory, exclusion_resolver=exclusion_resolver, ) cleanup_warnings = publish_artifacts_atomically( [(temp_zip, final_zip), (temp_sidecar, final_sidecar)], force=force, verify_published=verify_publication, ) except BaseException as exc: try: remove_partial_artifacts((temp_zip, temp_sidecar)) except PackagingError as cleanup_exc: raise PackagingError(f"{exc}; additionally, {cleanup_exc}") from exc raise finally: if staging_root is not None: shutil.rmtree(staging_root, ignore_errors=True) return { "status": "pass", "mode": "package", "profile": profile, "package_name": package_name, "package_zip": str(final_zip), "package_zip_sha256": zip_sha256, "sha256_sidecar": str(final_sidecar), "included_file_count": len(inventory), "included_bytes": sum(int(item["size"]) for item in inventory), "excluded_entry_count": len(excluded), "warnings": cleanup_warnings, } def validate_paths(source_root: Path, output_dir: Path) -> tuple[Path, Path]: try: source = source_root.expanduser().resolve(strict=True) except OSError as exc: raise PackagingError(f"SourceRoot is unavailable: {source_root}") from exc if not source.is_dir(): raise PackagingError(f"SourceRoot is not a directory: {source_root}") output = output_dir.expanduser().resolve(strict=False) try: output.relative_to(source) except ValueError: pass else: raise PackagingError("OutputDir must be outside SourceRoot to prevent recursive packaging") return source, output def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source-root", type=Path, default=ROOT) parser.add_argument( "--output-dir", type=Path, default=Path(os.environ.get("TMPDIR", "/tmp")) / "prod2u-handoff", ) parser.add_argument("--package-name") parser.add_argument("--force-overwrite", action="store_true") parser.add_argument("--audit-only", action="store_true") parser.add_argument( "--profile", choices=sorted(HANDOFF_PROFILES), default=DEFAULT_HANDOFF_PROFILE, help=( "review-compact (default upload, unified source/evidence/meta, no full git bundle); " "review-debug; archive-local; legacy full/code-only" ), ) parser.add_argument( "--reference-archive", action="append", default=[], type=Path, help="Additional reference ZIP/tar to ingest (repeatable)", ) parser.add_argument( "--reference-root", action="append", default=[], type=Path, help="Additional reference directory to ingest (repeatable)", ) return parser def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) package_name = args.package_name or datetime.now(timezone.utc).strftime("cpld-agent-handoff-%Y%m%dT%H%M%SZ") try: portable_package_name = windows_collision_key(package_name) except PackagingError: portable_package_name = "" if ( not SAFE_PACKAGE_NAME.fullmatch(package_name) or package_name in {".", ".."} or not portable_package_name ): print( "error: PackageName must be a portable ASCII file name without path separators or Windows-reserved forms", file=sys.stderr, ) return 1 try: source, output = validate_paths(args.source_root, args.output_dir) exclusion_resolver = make_exclusion_resolver(args.profile) candidates, excluded, context = scan_tree( source, exclusion_resolver=exclusion_resolver, profile=args.profile, ) if args.audit_only: audit_inventory = audit_candidates(candidates) assert_source_tree_unchanged( source, candidates, excluded, context, audit_inventory, exclusion_resolver=exclusion_resolver, ) rule_counts = Counter(item["rule"] for item in excluded) payload = { "status": "pass", "mode": "audit_only", "profile": args.profile, "package_name": package_name, "included_file_count": len(candidates), "included_bytes": sum(item.size for item in candidates), "excluded_entry_count": len(excluded), "exclusion_rule_counts": dict(sorted(rule_counts.items())), "changxin_temp_uart_version": context.changxin_version, } else: payload = create_package( root=source, output_dir=output, package_name=package_name, profile=args.profile, force=args.force_overwrite, candidates=candidates, excluded=excluded, context=context, exclusion_resolver=exclusion_resolver, ) except (PackagingError, OSError) as exc: print(f"error: {exc}", file=sys.stderr) return 1 print(json.dumps(payload, ensure_ascii=False, indent=2)) return 0 if __name__ == "__main__": raise SystemExit(main())