| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535 |
- #!/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 hashlib
- import importlib.util
- import json
- import os
- import subprocess
- import sys
- import uuid
- import zipfile
- 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"
- REPLAY_SIDECAR_SCHEMA = "cpld-review-compact-four-state-replay-v1"
- PACKAGE_STAGE = "final-review"
- def _sha256_file(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as fh:
- for chunk in iter(lambda: fh.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def _review_zip_in_package_dir(package_dir: Path) -> Path | None:
- """Prefer SHA256SUMS review-compact ZIP; never treat a sidecar JSON as the package."""
- names: list[str] = []
- sums = package_dir / "SHA256SUMS.txt"
- if sums.is_file():
- for line in sums.read_text(encoding="ascii").splitlines():
- line = line.strip()
- if not line or line.startswith("#"):
- continue
- _, _, name = line.partition(" ")
- name = name.strip()
- if name.casefold().endswith(".zip"):
- names.append(name)
- preferred = [n for n in names if "review-compact" in n.casefold()]
- for name in preferred or names:
- cand = package_dir / name
- if cand.is_file():
- return cand
- zips = sorted(
- p
- for p in package_dir.iterdir()
- if p.is_file() and p.suffix.casefold() == ".zip"
- )
- if not zips:
- return None
- preferred_files = [p for p in zips if "review-compact" in p.name.casefold()]
- return (preferred_files or zips)[0]
- def _read_zip_release_identity(path: Path) -> dict[str, Any]:
- try:
- with zipfile.ZipFile(path) as zf:
- for name in zf.namelist():
- n = name.replace("\\", "/")
- if n.endswith("meta/release-set-identity.json"):
- blob = json.loads(zf.read(name).decode("utf-8"))
- return blob if isinstance(blob, dict) else {}
- except Exception: # noqa: BLE001
- return {}
- return {}
- def stamp_replay_sidecar_identity(
- report: dict[str, Any],
- package_dir: Path,
- ) -> dict[str, Any]:
- """Stamp actual review-ZIP identity onto the four-state sidecar (sidecar stays outside ZIP)."""
- zip_path = _review_zip_in_package_dir(package_dir)
- if zip_path is None:
- return report
- report["actual_zip_basename"] = zip_path.name
- report["package_sha256"] = _sha256_file(zip_path)
- report["package_size"] = zip_path.stat().st_size
- report["package_stage"] = PACKAGE_STAGE
- identity = _read_zip_release_identity(zip_path)
- delivery = str(identity.get("delivery_commit") or "").strip()
- release_set_id = str(identity.get("release_set_id") or "").strip()
- if delivery:
- report["delivery_commit"] = delivery
- if release_set_id:
- report["release_set_id"] = release_set_id
- if identity:
- try:
- from package_provenance import attach_shared_identity_fields
- except ImportError:
- from tools.package_provenance import attach_shared_identity_fields
- attach_shared_identity_fields(report, identity)
- return report
- from tool_env import ensure_safe_sys_executable, safe_python as _safe_python # noqa: E402
- ensure_safe_sys_executable()
- 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():
- overall = "fail"
- results.append(
- {
- "module": module,
- "status": "fail_missing",
- "returncode": None,
- "path": str(candidate),
- }
- )
- continue
- completed = subprocess.run(
- [_safe_python(), "-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.values()) 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": "fail",
- "mode": "missing_board_assets",
- "returncode": None,
- "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
- "regeneration_claim": "none",
- }
- # 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",
- "board-copper-back.svg",
- "board-silkscreen-back.svg",
- "board-mask-edge-back.svg",
- )
- missing = [name for name in required if not (generated / name).is_file()]
- return {
- "status": "fail",
- "mode": "asset_presence",
- "returncode": None,
- "generated_dir": str(generated),
- "missing": missing,
- "reason": "final-review forbids asset_presence fallback",
- "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
- "regeneration_claim": "none",
- }
- completed = subprocess.run(
- [
- _safe_python(),
- "-B",
- str(validator),
- "--generated",
- 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)
- # Keep in sync with tools/test_profiles.DETACHED_REPLAY_UNIT_MODULES.
- # Do not pull live-repo git/history/reference tests into compact replay.
- try:
- from test_profiles import detached_replay_unit_modules
- unit_modules = list(detached_replay_unit_modules())
- except Exception: # noqa: BLE001
- 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"
- 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 = (
- (meta_git / "sanitized-snapshot-status.json").is_file()
- if meta_git.is_dir()
- else False
- )
- provenance = {
- "status": "pass"
- if (meta_git.is_dir() and head_txt and tree_manifest and sanitized)
- else "fail",
- "head_txt": head_txt,
- "tree_manifest": tree_manifest,
- "sanitized_snapshot_status": sanitized,
- "raw_git_required": False,
- }
- observed = [str(row.get("module") or "") for row in unit.get("modules", [])]
- unit_exact = sorted(observed) == sorted(unit_modules) and unit["status"] == "pass"
- try:
- board_rc = int(board.get("returncode"))
- except (TypeError, ValueError):
- board_rc = None
- board_ok = (
- board.get("status") == "pass"
- and str(board.get("mode") or "") == "validate_detached_derived"
- and board_rc == 0
- )
- if layout["status"] != "pass" or provenance["status"] != "pass":
- overall = "fail"
- elif unit["status"] == "fail" or not unit_exact:
- overall = "fail"
- unit["status"] = "fail"
- elif not board_ok:
- overall = "fail"
- if board.get("status") == "pass":
- board["status"] = "fail"
- else:
- overall = "pass"
- parts = {
- "layout": layout["status"],
- "provenance": provenance["status"],
- "unit": unit["status"],
- "board": board["status"],
- }
- 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,
- "unit_exact_set": unit_exact,
- "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:
- # Must NOT pre-create the directory: replay_analysis_package refuses
- # extract roots that already exist (exist_ok=False).
- extract_root = Path(os.environ.get("TMPDIR", "/tmp")) / (
- "prod2u-review-compact-replay-" + uuid.uuid4().hex
- )
- 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")
- zip_path = _review_zip_in_package_dir(package_dir)
- if isinstance(content, dict) and zip_path is not None:
- try:
- from replay_semantic import align_checked_files_to_manifest
- except ImportError:
- from tools.replay_semantic import align_checked_files_to_manifest
- align_checked_files_to_manifest(content, zip_path)
- overall = "pass"
- if package_content_status != "pass":
- overall = "fail"
- elif detached_status not in {"pass", "not_run"}:
- overall = "fail"
- report = {
- "schema": REPLAY_SIDECAR_SCHEMA,
- "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,
- },
- }
- stamp_replay_sidecar_identity(report, package_dir)
- try:
- from replay_semantic import stamp_replay_semantic
- except ImportError:
- from tools.replay_semantic import stamp_replay_semantic
- stamp_replay_semantic(report, zip_path=zip_path)
- return report
- 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())
|