#!/usr/bin/env python3 """Four-state replay for review-compact packages. Statuses (distinct): - package_content_replay: SHA256SUMS + inventory extract/hash verify - detached_software_replay: Git-optional software checks on extracted source/ - reference_regeneration_replay: always ``not_packaged_by_policy`` - hardware_validation: always ``not_run`` """ from __future__ import annotations import argparse import importlib.util import json import os import subprocess import sys import tempfile from datetime import datetime, timezone from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parents[1] TOOLS = ROOT / "tools" if str(TOOLS) not in sys.path: sys.path.insert(0, str(TOOLS)) from git_worktree_mode import ( # noqa: E402 DETACHED, LIVE_GIT, SNAPSHOT, describe_git_mode, detect_git_mode, ) REFERENCE_REGENERATION_REPLAY = "not_packaged_by_policy" HARDWARE_VALIDATION = "not_run" class ReplayError(RuntimeError): """Replay orchestration failure.""" def _load_analyzer(): path = ROOT / "package_for_agent_analysis.py" spec = importlib.util.spec_from_file_location("package_for_agent_analysis", path) if spec is None or spec.loader is None: raise ReplayError(f"unable to load packager module: {path}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module def resolve_cpld_root(extract_or_cpld: Path) -> Path: """Accept extract root, from-zip, or CPLD directory.""" path = extract_or_cpld.expanduser().resolve(strict=True) candidates = ( path, path / "CPLD", path / "from-zip" / "CPLD", ) for candidate in candidates: if (candidate / "source").is_dir() or (candidate / "meta").is_dir(): return candidate if candidate.name == "CPLD" and candidate.is_dir(): return candidate raise ReplayError(f"unable to locate CPLD root under {path}") def extract_review_compact_package( package_dir: Path, *, extract_root: Path, ) -> dict[str, Any]: """Package-content replay via packager API.""" analyzer = _load_analyzer() return analyzer.replay_analysis_package(package_dir, extract_root=extract_root) def _run_unittest_modules(software_root: Path, modules: list[str]) -> dict[str, Any]: """Run selected unittest modules with cwd/software_root; Git-optional.""" env = os.environ.copy() env.setdefault("PRODU2_GIT_MODE", DETACHED) # Prefer the extracted source tree on sys.path for imports that use relative roots. pythonpath = str(software_root) if env.get("PYTHONPATH"): pythonpath = pythonpath + os.pathsep + env["PYTHONPATH"] env["PYTHONPATH"] = pythonpath results: list[dict[str, Any]] = [] overall = "pass" for module in modules: # Only run modules that exist under the extracted source tree. rel = Path(*module.split(".")) candidate = software_root / rel.with_suffix(".py") if not candidate.is_file(): results.append( { "module": module, "status": "skipped_missing", "path": str(candidate), } ) continue completed = subprocess.run( [sys.executable, "-B", "-m", "unittest", module, "-q"], cwd=str(software_root), env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False, ) status = "pass" if completed.returncode == 0 else "fail" if status == "fail": overall = "fail" results.append( { "module": module, "status": status, "returncode": completed.returncode, "output_tail": completed.stdout[-2000:], } ) return {"status": overall, "modules": results} def _check_layout(cpld_root: Path) -> dict[str, Any]: source = cpld_root / "source" evidence = cpld_root / "evidence" meta = cpld_root / "meta" checks = { "source_dir": source.is_dir(), "meta_dir": meta.is_dir(), "evidence_dir": evidence.is_dir(), "meta_git_dir": (meta / "git").is_dir(), "no_raw_git_under_source": not (source / ".git").exists(), "no_raw_git_under_cpld": not (cpld_root / ".git").exists(), } # Prefer package contract markers when present. project = source / "projects" / "prod2u-door-temp" / "project.json" checks["project_contract_present"] = project.is_file() status = "pass" if all( checks[key] for key in ( "source_dir", "meta_dir", "no_raw_git_under_source", "no_raw_git_under_cpld", ) ) else "fail" return {"status": status, "checks": checks} def _board_detached_check(cpld_root: Path) -> dict[str, Any]: """Run board-viewer detached validation when P5 assets/API are available.""" generated_candidates = ( cpld_root / "evidence" / "board-viewer", cpld_root / "source" / "tools" / "board-viewer" / "generated", ) generated = next((path for path in generated_candidates if path.is_dir()), None) if generated is None: return { "status": "skipped_no_board_assets", "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY, } # Prefer extracted source validator; fall back to live repo tools. validator_candidates = ( cpld_root / "source" / "tools" / "board-viewer" / "validate_detached_derived.py", ROOT / "tools" / "board-viewer" / "validate_detached_derived.py", ) validator = next((path for path in validator_candidates if path.is_file()), None) if validator is None: # Lightweight local checks without P5 module. required = ( "board-data.json", "build-info.json", "import-report.json", "board-copper.svg", "board-silkscreen.svg", "board-mask-edge.svg", ) missing = [name for name in required if not (generated / name).is_file()] return { "status": "pass" if not missing else "fail", "mode": "asset_presence", "generated_dir": str(generated), "missing": missing, "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY, "regeneration_claim": "none", } completed = subprocess.run( [ sys.executable, "-B", str(validator), "--generated-dir", str(generated), ], cwd=str(validator.parent), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, check=False, ) return { "status": "pass" if completed.returncode == 0 else "fail", "mode": "validate_detached_derived", "generated_dir": str(generated), "returncode": completed.returncode, "output_tail": completed.stdout[-2000:], "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY, "regeneration_claim": "none", } def run_detached_software_replay(cpld_root: Path) -> dict[str, Any]: """Git-optional software replay against extracted CPLD tree.""" cpld_root = resolve_cpld_root(cpld_root) source_root = cpld_root / "source" git_mode = detect_git_mode(cpld_root) if git_mode == LIVE_GIT: # Extracted compact trees must not expose raw .git; live_git here is unexpected. git_info = describe_git_mode(cpld_root) else: git_info = describe_git_mode(cpld_root) layout = _check_layout(cpld_root) board = _board_detached_check(cpld_root) unit_modules = [ "tests.unit.test_protocol", "tests.unit.test_project_config", "tests.unit.test_product_contract_coverage", ] unit = ( _run_unittest_modules(source_root, unit_modules) if source_root.is_dir() else {"status": "fail", "modules": [], "reason": "missing source/"} ) # Meta git provenance must be usable without raw .git. meta_git = cpld_root / "meta" / "git" provenance = { "status": "pass" if meta_git.is_dir() else "fail", "head_txt": (meta_git / "HEAD.txt").is_file() if meta_git.is_dir() else False, "tree_manifest": (meta_git / "tree-manifest.json").is_file() if meta_git.is_dir() else False, "sanitized_snapshot_status": ( meta_git / "sanitized-snapshot-status.json" ).is_file() if meta_git.is_dir() else False, "raw_git_required": False, } parts = { "layout": layout["status"], "provenance": provenance["status"], "unit": unit["status"], "board": board["status"], } # skipped_* board does not fail the lane; fail/skip-missing unit modules are soft # unless layout/provenance fail. soft_board = board["status"].startswith("skipped_") soft_unit_skip_only = unit["status"] == "pass" or ( unit["status"] != "fail" and all( row.get("status") in {"pass", "skipped_missing"} for row in unit.get("modules", []) ) ) if layout["status"] != "pass" or provenance["status"] != "pass": overall = "fail" elif unit["status"] == "fail": overall = "fail" elif not soft_board and board["status"] == "fail": overall = "fail" else: overall = "pass" return { "status": overall, "git_mode": git_mode, "git_mode_info": git_info, "software_root": str(source_root), "layout": layout, "provenance": provenance, "unit": unit, "board": board, "part_statuses": parts, "soft_unit_skip_only": soft_unit_skip_only, "note": ( "Detached software replay does not require raw .git; " "live_git commit-compare paths remain strict elsewhere." ), } def replay_review_compact( package_dir: Path, *, extract_root: Path | None = None, skip_software: bool = False, ) -> dict[str, Any]: """Run the four-state review-compact replay.""" package_dir = package_dir.expanduser().resolve(strict=True) if extract_root is None: extract_root = Path( tempfile.mkdtemp( prefix="prod2u-review-compact-replay-", dir=os.environ.get("TMPDIR", "/tmp"), ) ) else: extract_root = extract_root.expanduser().resolve(strict=False) content = extract_review_compact_package(package_dir, extract_root=extract_root) package_content_status = str(content.get("package_content_replay") or content.get("status") or "fail") cpld_root_raw = content.get("cpld_root") if not cpld_root_raw: cpld_root = resolve_cpld_root(extract_root) else: cpld_root = Path(str(cpld_root_raw)) if skip_software: software: dict[str, Any] = { "status": "not_run", "note": "skipped by --skip-software", } detached_status = "not_run" else: software = run_detached_software_replay(cpld_root) detached_status = str(software.get("status") or "fail") overall = "pass" if package_content_status != "pass": overall = "fail" elif detached_status not in {"pass", "not_run"}: overall = "fail" return { "schema": "cpld-review-compact-four-state-replay-v1", "generated_at_utc": datetime.now(timezone.utc).isoformat(), "status": overall, "package_dir": str(package_dir), "extract_root": str(extract_root), "cpld_root": str(cpld_root), "package_content_replay": package_content_status, "detached_software_replay": detached_status, "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY, "hardware_validation": HARDWARE_VALIDATION, "package_content": content, "detached_software": software, "git_modes": { "LIVE_GIT": LIVE_GIT, "SNAPSHOT": SNAPSHOT, "DETACHED": DETACHED, }, } def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--package-dir", type=Path, required=True, help="published package directory (HANDOFF-INDEX.json + ZIP)", ) parser.add_argument( "--extract-dir", type=Path, help="extract target (must not already exist)", ) parser.add_argument( "--skip-software", action="store_true", help="only run package_content_replay", ) parser.add_argument( "--json-out", type=Path, help="write full four-state report JSON", ) return parser def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) try: report = replay_review_compact( args.package_dir, extract_root=args.extract_dir, skip_software=args.skip_software, ) except Exception as exc: # noqa: BLE001 - CLI boundary print(f"error: {exc}", file=sys.stderr) return 1 text = json.dumps(report, ensure_ascii=False, indent=2) print(text) if args.json_out is not None: args.json_out.parent.mkdir(parents=True, exist_ok=True) args.json_out.write_text(text + "\n", encoding="utf-8") return 0 if report.get("status") == "pass" else 2 if __name__ == "__main__": raise SystemExit(main())