#!/usr/bin/env python3 """Deterministic exclusion-based packaging engine for Prod2U canonical packaging. Enforces: - Candidates = Included ∪ Excluded (strictly disjoint partition) - Every excluded file records path, type, reason, and size - Unknown files default to included or explicit alert (never silently dropped) - DEFLATE level 9 """ from __future__ import annotations import fnmatch import hashlib import json from pathlib import Path, PurePosixPath from typing import Callable, Iterable def sha256_bytes(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def sha256_file(path: Path) -> str: h = hashlib.sha256() with path.open("rb") as f: for chunk in iter(lambda: f.read(1024 * 1024), b""): h.update(chunk) return h.hexdigest() def scan_candidate_universe( root: Path, extra_files: dict[str, Path] | None = None, ) -> dict[str, dict]: """Scan all candidate files in the workspace (excluding .git internal database). Returns a dict mapping relative POSIX path to metadata: {"path": rel, "size": size, "abs_path": Path} """ root = Path(root).resolve() universe: dict[str, dict] = {} for p in sorted(root.rglob("*")): if p.is_file(): parts = p.relative_to(root).parts # Exclude git internal database from candidate scan if any(part == ".git" for part in parts): continue rel = p.relative_to(root).as_posix() universe[rel] = { "path": rel, "size": p.stat().st_size, "abs_path": p, } if extra_files: for rel_name, abs_path in sorted(extra_files.items()): if abs_path.is_file(): universe[rel_name] = { "path": rel_name, "size": abs_path.stat().st_size, "abs_path": abs_path, } return universe def classify_files( universe: dict[str, dict], rules: list[tuple[Callable[[str, dict], bool], str, str]], force_include: set[str] | None = None, ) -> tuple[dict[str, dict], list[dict]]: """Partition candidate universe into included files and excluded records. Each rule is a tuple: (predicate_fn, type_str, reason_str). Unknown files not matching any rule default to INCLUDED. """ force_include = force_include or set() included: dict[str, dict] = {} exclusions: list[dict] = [] for rel_path, item in sorted(universe.items()): if rel_path in force_include: included[rel_path] = item continue matched = False for predicate, type_str, reason_str in rules: if predicate(rel_path, item): exclusions.append({ "path": rel_path, "type": type_str, "reason": reason_str, "size": item["size"], }) matched = True break if not matched: # Unknown files default to included (never silently dropped) included[rel_path] = item verify_partition(universe, included, exclusions) return included, exclusions def verify_partition( universe: dict[str, dict], included: dict[str, dict], exclusions: list[dict], ) -> None: """Mechanically verify that Candidates = Included ∪ Excluded and Included ∩ Excluded = ∅.""" universe_set = set(universe.keys()) included_set = set(included.keys()) excluded_set = {x["path"] for x in exclusions} overlap = included_set.intersection(excluded_set) if overlap: sample = sorted(overlap)[:5] raise ValueError(f"EXCLUSION_INCLUSION_OVERLAP: files present in both: {sample}") union = included_set.union(excluded_set) if union != universe_set: missing = universe_set - union extra = union - universe_set raise ValueError(f"EXCLUSION_PARTITION_MISMATCH: missing={sorted(missing)[:5]}, extra={sorted(extra)[:5]}") if len(included) + len(exclusions) != len(universe): raise ValueError("EXCLUSION_COUNT_MISMATCH") def create_exclusions_payload( universe: dict[str, dict], included: dict[str, dict], exclusions: list[dict], scope: str, ) -> dict: """Create EXCLUSIONS.json payload adhering to prod2u-package-exclusions-v2.""" return { "schema": "prod2u-package-exclusions-v2", "scope": scope, "total_candidates": len(universe), "included_count": len(included), "excluded_count": len(exclusions), "exclusions": sorted(exclusions, key=lambda x: x["path"]), } def make_prefix_matcher(prefix: str) -> Callable[[str, dict], bool]: prefix = prefix.rstrip("/") + "/" return lambda rel, _item: rel.startswith(prefix) def make_pattern_matcher(pattern: str) -> Callable[[str, dict], bool]: return lambda rel, _item: fnmatch.fnmatch(rel, pattern) or fnmatch.fnmatch(PurePosixPath(rel).name, pattern) def get_standard_system_exclusion_rules() -> list[tuple[Callable[[str, dict], bool], str, str]]: """Common rules for caches, temporary outputs, editor state, and raw reference stores.""" rules: list[tuple[Callable[[str, dict], bool], str, str]] = [ # Python and pytest caches (lambda r, _: "__pycache__" in PurePosixPath(r).parts or r.endswith((".pyc", ".pyo")), "cache", "Python compiled bytecode"), (lambda r, _: ".pytest_cache" in PurePosixPath(r).parts, "cache", "pytest temporary runtime cache"), # Dist directory (make_prefix_matcher("dist"), "build-artifact", "Pre-existing built package archive in dist/"), # Editor / IDE metadata (lambda r, _: any(part in (".codebuddy", ".omo", ".vscode", ".idea") for part in PurePosixPath(r).parts) or r.endswith((".swp", "*~")), "editor-cache", "Local IDE or editor runtime state"), # Transient root logs (lambda r, _: PurePosixPath(r).parent == PurePosixPath(".") and (r.startswith("td_") and r.endswith((".log", ".logw"))), "tool-log", "Transient toolchain execution log in repo root"), # Heavy external reference assets (make_prefix_matcher("reference/original/board"), "raw-reference", "Binary PCB board database files stored in external reference repository"), (make_prefix_matcher("reference/original/schematics"), "raw-reference", "Raw schematic PDFs stored in external reference repository"), (make_prefix_matcher("reference/original/local_archives"), "raw-reference", "Raw local archive dump stored in external reference repository"), ] return rules def get_6400_v2_exclusion_rules(kind: str) -> list[tuple[Callable[[str, dict], bool], str, str]]: """Exclusion rules for 6400-v2 product packaging.""" rules = get_standard_system_exclusion_rules() # Exclude other product (MRDIMM) files from 6400-v2 packages rules.extend([ (lambda r, _: "identification" in PurePosixPath(r).parts or "identification" in PurePosixPath(r).name, "historical", "Retired 6400-identification profile artifact"), (lambda r, _: "sim-debug" in PurePosixPath(r).parts or "sim-debug" in PurePosixPath(r).name, "historical", "Retired 6400-sim-debug profile artifact"), (make_prefix_matcher("products/mrdimm-chamber"), "other-product", "MRDIMM chamber project definition"), (make_prefix_matcher("projects/mrdimm-chamber"), "other-product", "MRDIMM chamber project docs/specs"), (lambda r, _: "mrdimm" in PurePosixPath(r).name and not r.startswith("tests/unit/test_mrdimm_"), "other-product", "MRDIMM-specific tool or artifact"), (make_prefix_matcher("td/bitgen/prod2u_mrdimm"), "other-product", "MRDIMM bitgen tcl"), (make_prefix_matcher("td/phy/prod2u_mrdimm"), "other-product", "MRDIMM phy tcl"), (make_prefix_matcher("td/syn/prod2u_mrdimm"), "other-product", "MRDIMM syn tcl"), (make_prefix_matcher("constraints/prod2u_mrdimm"), "other-product", "MRDIMM constraints"), (make_prefix_matcher("generated/mrdimm"), "other-product", "MRDIMM generated contracts"), # Retired / superseded legacy directories (make_prefix_matcher("src/legacy"), "historical", "Retired legacy CPLD implementations"), (make_prefix_matcher("docs/historical"), "historical", "Superseded historical documentation"), ]) if kind in ("firmware", "delivery"): # Firmware/Delivery release package excludes developer test suites, scripts, and documentation rules.extend([ (make_prefix_matcher("tests"), "source-test", "Automated test suites excluded from binary firmware release"), (make_prefix_matcher("tools"), "source-tool", "Engineering tools excluded from binary firmware release"), (make_prefix_matcher("docs"), "documentation", "Developer documentation excluded from binary firmware release"), (make_prefix_matcher("containers"), "container", "Container environment recipes excluded from binary firmware release"), (make_prefix_matcher("reference"), "reference", "Reference files excluded from binary firmware release"), (lambda r, _: r in ("pyproject.toml", "RECOVERY_STATE.md", "TASK_PLAN.json", "RESULTS.json", ".gitattributes", ".gitignore"), "metadata", "Repo build metadata excluded from firmware release"), ]) return rules