replay_review_compact.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. #!/usr/bin/env python3
  2. """Four-state replay for review-compact packages.
  3. Statuses (distinct):
  4. - package_content_replay: SHA256SUMS + inventory extract/hash verify
  5. - detached_software_replay: Git-optional software checks on extracted source/
  6. - reference_regeneration_replay: always ``not_packaged_by_policy``
  7. - hardware_validation: always ``not_run``
  8. """
  9. from __future__ import annotations
  10. import argparse
  11. import hashlib
  12. import importlib.util
  13. import json
  14. import os
  15. import subprocess
  16. import sys
  17. import uuid
  18. import zipfile
  19. from datetime import datetime, timezone
  20. from pathlib import Path
  21. from typing import Any
  22. ROOT = Path(__file__).resolve().parents[1]
  23. TOOLS = ROOT / "tools"
  24. if str(TOOLS) not in sys.path:
  25. sys.path.insert(0, str(TOOLS))
  26. from git_worktree_mode import ( # noqa: E402
  27. DETACHED,
  28. LIVE_GIT,
  29. SNAPSHOT,
  30. describe_git_mode,
  31. detect_git_mode,
  32. )
  33. REFERENCE_REGENERATION_REPLAY = "not_packaged_by_policy"
  34. HARDWARE_VALIDATION = "not_run"
  35. REPLAY_SIDECAR_SCHEMA = "cpld-review-compact-four-state-replay-v1"
  36. PACKAGE_STAGE = "final-review"
  37. def _sha256_file(path: Path) -> str:
  38. digest = hashlib.sha256()
  39. with path.open("rb") as fh:
  40. for chunk in iter(lambda: fh.read(1024 * 1024), b""):
  41. digest.update(chunk)
  42. return digest.hexdigest()
  43. def _review_zip_in_package_dir(package_dir: Path) -> Path | None:
  44. """Prefer SHA256SUMS review-compact ZIP; never treat a sidecar JSON as the package."""
  45. names: list[str] = []
  46. sums = package_dir / "SHA256SUMS.txt"
  47. if sums.is_file():
  48. for line in sums.read_text(encoding="ascii").splitlines():
  49. line = line.strip()
  50. if not line or line.startswith("#"):
  51. continue
  52. _, _, name = line.partition(" ")
  53. name = name.strip()
  54. if name.casefold().endswith(".zip"):
  55. names.append(name)
  56. preferred = [n for n in names if "review-compact" in n.casefold()]
  57. for name in preferred or names:
  58. cand = package_dir / name
  59. if cand.is_file():
  60. return cand
  61. zips = sorted(
  62. p
  63. for p in package_dir.iterdir()
  64. if p.is_file() and p.suffix.casefold() == ".zip"
  65. )
  66. if not zips:
  67. return None
  68. preferred_files = [p for p in zips if "review-compact" in p.name.casefold()]
  69. return (preferred_files or zips)[0]
  70. def _read_zip_release_identity(path: Path) -> dict[str, Any]:
  71. try:
  72. with zipfile.ZipFile(path) as zf:
  73. for name in zf.namelist():
  74. n = name.replace("\\", "/")
  75. if n.endswith("meta/release-set-identity.json"):
  76. blob = json.loads(zf.read(name).decode("utf-8"))
  77. return blob if isinstance(blob, dict) else {}
  78. except Exception: # noqa: BLE001
  79. return {}
  80. return {}
  81. def stamp_replay_sidecar_identity(
  82. report: dict[str, Any],
  83. package_dir: Path,
  84. ) -> dict[str, Any]:
  85. """Stamp actual review-ZIP identity onto the four-state sidecar (sidecar stays outside ZIP)."""
  86. zip_path = _review_zip_in_package_dir(package_dir)
  87. if zip_path is None:
  88. return report
  89. report["actual_zip_basename"] = zip_path.name
  90. report["package_sha256"] = _sha256_file(zip_path)
  91. report["package_size"] = zip_path.stat().st_size
  92. report["package_stage"] = PACKAGE_STAGE
  93. identity = _read_zip_release_identity(zip_path)
  94. delivery = str(identity.get("delivery_commit") or "").strip()
  95. release_set_id = str(identity.get("release_set_id") or "").strip()
  96. if delivery:
  97. report["delivery_commit"] = delivery
  98. if release_set_id:
  99. report["release_set_id"] = release_set_id
  100. if identity:
  101. try:
  102. from package_provenance import attach_shared_identity_fields
  103. except ImportError:
  104. from tools.package_provenance import attach_shared_identity_fields
  105. attach_shared_identity_fields(report, identity)
  106. return report
  107. from tool_env import ensure_safe_sys_executable, safe_python as _safe_python # noqa: E402
  108. ensure_safe_sys_executable()
  109. class ReplayError(RuntimeError):
  110. """Replay orchestration failure."""
  111. def _load_analyzer():
  112. path = ROOT / "package_for_agent_analysis.py"
  113. spec = importlib.util.spec_from_file_location("package_for_agent_analysis", path)
  114. if spec is None or spec.loader is None:
  115. raise ReplayError(f"unable to load packager module: {path}")
  116. module = importlib.util.module_from_spec(spec)
  117. spec.loader.exec_module(module)
  118. return module
  119. def resolve_cpld_root(extract_or_cpld: Path) -> Path:
  120. """Accept extract root, from-zip, or CPLD directory."""
  121. path = extract_or_cpld.expanduser().resolve(strict=True)
  122. candidates = (
  123. path,
  124. path / "CPLD",
  125. path / "from-zip" / "CPLD",
  126. )
  127. for candidate in candidates:
  128. if (candidate / "source").is_dir() or (candidate / "meta").is_dir():
  129. return candidate
  130. if candidate.name == "CPLD" and candidate.is_dir():
  131. return candidate
  132. raise ReplayError(f"unable to locate CPLD root under {path}")
  133. def extract_review_compact_package(
  134. package_dir: Path,
  135. *,
  136. extract_root: Path,
  137. ) -> dict[str, Any]:
  138. """Package-content replay via packager API."""
  139. analyzer = _load_analyzer()
  140. return analyzer.replay_analysis_package(package_dir, extract_root=extract_root)
  141. def _run_unittest_modules(software_root: Path, modules: list[str]) -> dict[str, Any]:
  142. """Run selected unittest modules with cwd/software_root; Git-optional."""
  143. env = os.environ.copy()
  144. env.setdefault("PRODU2_GIT_MODE", DETACHED)
  145. # Prefer the extracted source tree on sys.path for imports that use relative roots.
  146. pythonpath = str(software_root)
  147. if env.get("PYTHONPATH"):
  148. pythonpath = pythonpath + os.pathsep + env["PYTHONPATH"]
  149. env["PYTHONPATH"] = pythonpath
  150. results: list[dict[str, Any]] = []
  151. overall = "pass"
  152. for module in modules:
  153. # Only run modules that exist under the extracted source tree.
  154. rel = Path(*module.split("."))
  155. candidate = software_root / rel.with_suffix(".py")
  156. if not candidate.is_file():
  157. overall = "fail"
  158. results.append(
  159. {
  160. "module": module,
  161. "status": "fail_missing",
  162. "returncode": None,
  163. "path": str(candidate),
  164. }
  165. )
  166. continue
  167. completed = subprocess.run(
  168. [_safe_python(), "-B", "-m", "unittest", module, "-q"],
  169. cwd=str(software_root),
  170. env=env,
  171. stdout=subprocess.PIPE,
  172. stderr=subprocess.STDOUT,
  173. text=True,
  174. check=False,
  175. )
  176. status = "pass" if completed.returncode == 0 else "fail"
  177. if status == "fail":
  178. overall = "fail"
  179. results.append(
  180. {
  181. "module": module,
  182. "status": status,
  183. "returncode": completed.returncode,
  184. "output_tail": completed.stdout[-2000:],
  185. }
  186. )
  187. return {"status": overall, "modules": results}
  188. def _check_layout(cpld_root: Path) -> dict[str, Any]:
  189. source = cpld_root / "source"
  190. evidence = cpld_root / "evidence"
  191. meta = cpld_root / "meta"
  192. checks = {
  193. "source_dir": source.is_dir(),
  194. "meta_dir": meta.is_dir(),
  195. "evidence_dir": evidence.is_dir(),
  196. "meta_git_dir": (meta / "git").is_dir(),
  197. "no_raw_git_under_source": not (source / ".git").exists(),
  198. "no_raw_git_under_cpld": not (cpld_root / ".git").exists(),
  199. }
  200. # Prefer package contract markers when present.
  201. project = source / "projects" / "prod2u-door-temp" / "project.json"
  202. checks["project_contract_present"] = project.is_file()
  203. status = "pass" if all(checks.values()) else "fail"
  204. return {"status": status, "checks": checks}
  205. def _board_detached_check(cpld_root: Path) -> dict[str, Any]:
  206. """Run board-viewer detached validation when P5 assets/API are available."""
  207. generated_candidates = (
  208. cpld_root / "evidence" / "board-viewer",
  209. cpld_root / "source" / "tools" / "board-viewer" / "generated",
  210. )
  211. generated = next((path for path in generated_candidates if path.is_dir()), None)
  212. if generated is None:
  213. return {
  214. "status": "fail",
  215. "mode": "missing_board_assets",
  216. "returncode": None,
  217. "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
  218. "regeneration_claim": "none",
  219. }
  220. # Prefer extracted source validator; fall back to live repo tools.
  221. validator_candidates = (
  222. cpld_root / "source" / "tools" / "board-viewer" / "validate_detached_derived.py",
  223. ROOT / "tools" / "board-viewer" / "validate_detached_derived.py",
  224. )
  225. validator = next((path for path in validator_candidates if path.is_file()), None)
  226. if validator is None:
  227. # Lightweight local checks without P5 module.
  228. required = (
  229. "board-data.json",
  230. "build-info.json",
  231. "import-report.json",
  232. "board-copper.svg",
  233. "board-silkscreen.svg",
  234. "board-mask-edge.svg",
  235. "board-copper-back.svg",
  236. "board-silkscreen-back.svg",
  237. "board-mask-edge-back.svg",
  238. )
  239. missing = [name for name in required if not (generated / name).is_file()]
  240. return {
  241. "status": "fail",
  242. "mode": "asset_presence",
  243. "returncode": None,
  244. "generated_dir": str(generated),
  245. "missing": missing,
  246. "reason": "final-review forbids asset_presence fallback",
  247. "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
  248. "regeneration_claim": "none",
  249. }
  250. completed = subprocess.run(
  251. [
  252. _safe_python(),
  253. "-B",
  254. str(validator),
  255. "--generated",
  256. str(generated),
  257. ],
  258. cwd=str(validator.parent),
  259. stdout=subprocess.PIPE,
  260. stderr=subprocess.STDOUT,
  261. text=True,
  262. check=False,
  263. )
  264. return {
  265. "status": "pass" if completed.returncode == 0 else "fail",
  266. "mode": "validate_detached_derived",
  267. "generated_dir": str(generated),
  268. "returncode": completed.returncode,
  269. "output_tail": completed.stdout[-2000:],
  270. "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
  271. "regeneration_claim": "none",
  272. }
  273. def run_detached_software_replay(cpld_root: Path) -> dict[str, Any]:
  274. """Git-optional software replay against extracted CPLD tree."""
  275. cpld_root = resolve_cpld_root(cpld_root)
  276. source_root = cpld_root / "source"
  277. git_mode = detect_git_mode(cpld_root)
  278. if git_mode == LIVE_GIT:
  279. # Extracted compact trees must not expose raw .git; live_git here is unexpected.
  280. git_info = describe_git_mode(cpld_root)
  281. else:
  282. git_info = describe_git_mode(cpld_root)
  283. layout = _check_layout(cpld_root)
  284. board = _board_detached_check(cpld_root)
  285. # Keep in sync with tools/test_profiles.DETACHED_REPLAY_UNIT_MODULES.
  286. # Do not pull live-repo git/history/reference tests into compact replay.
  287. try:
  288. from test_profiles import detached_replay_unit_modules
  289. unit_modules = list(detached_replay_unit_modules())
  290. except Exception: # noqa: BLE001
  291. unit_modules = [
  292. "tests.unit.test_protocol",
  293. "tests.unit.test_project_config",
  294. "tests.unit.test_product_contract_coverage",
  295. ]
  296. unit = (
  297. _run_unittest_modules(source_root, unit_modules)
  298. if source_root.is_dir()
  299. else {"status": "fail", "modules": [], "reason": "missing source/"}
  300. )
  301. # Meta git provenance must be usable without raw .git.
  302. meta_git = cpld_root / "meta" / "git"
  303. head_txt = (meta_git / "HEAD.txt").is_file() if meta_git.is_dir() else False
  304. tree_manifest = (
  305. (meta_git / "tree-manifest.json").is_file() if meta_git.is_dir() else False
  306. )
  307. sanitized = (
  308. (meta_git / "sanitized-snapshot-status.json").is_file()
  309. if meta_git.is_dir()
  310. else False
  311. )
  312. provenance = {
  313. "status": "pass"
  314. if (meta_git.is_dir() and head_txt and tree_manifest and sanitized)
  315. else "fail",
  316. "head_txt": head_txt,
  317. "tree_manifest": tree_manifest,
  318. "sanitized_snapshot_status": sanitized,
  319. "raw_git_required": False,
  320. }
  321. observed = [str(row.get("module") or "") for row in unit.get("modules", [])]
  322. unit_exact = sorted(observed) == sorted(unit_modules) and unit["status"] == "pass"
  323. try:
  324. board_rc = int(board.get("returncode"))
  325. except (TypeError, ValueError):
  326. board_rc = None
  327. board_ok = (
  328. board.get("status") == "pass"
  329. and str(board.get("mode") or "") == "validate_detached_derived"
  330. and board_rc == 0
  331. )
  332. if layout["status"] != "pass" or provenance["status"] != "pass":
  333. overall = "fail"
  334. elif unit["status"] == "fail" or not unit_exact:
  335. overall = "fail"
  336. unit["status"] = "fail"
  337. elif not board_ok:
  338. overall = "fail"
  339. if board.get("status") == "pass":
  340. board["status"] = "fail"
  341. else:
  342. overall = "pass"
  343. parts = {
  344. "layout": layout["status"],
  345. "provenance": provenance["status"],
  346. "unit": unit["status"],
  347. "board": board["status"],
  348. }
  349. return {
  350. "status": overall,
  351. "git_mode": git_mode,
  352. "git_mode_info": git_info,
  353. "software_root": str(source_root),
  354. "layout": layout,
  355. "provenance": provenance,
  356. "unit": unit,
  357. "board": board,
  358. "part_statuses": parts,
  359. "unit_exact_set": unit_exact,
  360. "note": (
  361. "Detached software replay does not require raw .git; "
  362. "live_git commit-compare paths remain strict elsewhere."
  363. ),
  364. }
  365. def replay_review_compact(
  366. package_dir: Path,
  367. *,
  368. extract_root: Path | None = None,
  369. skip_software: bool = False,
  370. ) -> dict[str, Any]:
  371. """Run the four-state review-compact replay."""
  372. package_dir = package_dir.expanduser().resolve(strict=True)
  373. if extract_root is None:
  374. # Must NOT pre-create the directory: replay_analysis_package refuses
  375. # extract roots that already exist (exist_ok=False).
  376. extract_root = Path(os.environ.get("TMPDIR", "/tmp")) / (
  377. "prod2u-review-compact-replay-" + uuid.uuid4().hex
  378. )
  379. else:
  380. extract_root = extract_root.expanduser().resolve(strict=False)
  381. content = extract_review_compact_package(package_dir, extract_root=extract_root)
  382. package_content_status = str(content.get("package_content_replay") or content.get("status") or "fail")
  383. cpld_root_raw = content.get("cpld_root")
  384. if not cpld_root_raw:
  385. cpld_root = resolve_cpld_root(extract_root)
  386. else:
  387. cpld_root = Path(str(cpld_root_raw))
  388. if skip_software:
  389. software: dict[str, Any] = {
  390. "status": "not_run",
  391. "note": "skipped by --skip-software",
  392. }
  393. detached_status = "not_run"
  394. else:
  395. software = run_detached_software_replay(cpld_root)
  396. detached_status = str(software.get("status") or "fail")
  397. zip_path = _review_zip_in_package_dir(package_dir)
  398. if isinstance(content, dict) and zip_path is not None:
  399. try:
  400. from replay_semantic import align_checked_files_to_manifest
  401. except ImportError:
  402. from tools.replay_semantic import align_checked_files_to_manifest
  403. align_checked_files_to_manifest(content, zip_path)
  404. overall = "pass"
  405. if package_content_status != "pass":
  406. overall = "fail"
  407. elif detached_status not in {"pass", "not_run"}:
  408. overall = "fail"
  409. report = {
  410. "schema": REPLAY_SIDECAR_SCHEMA,
  411. "generated_at_utc": datetime.now(timezone.utc).isoformat(),
  412. "status": overall,
  413. "package_dir": str(package_dir),
  414. "extract_root": str(extract_root),
  415. "cpld_root": str(cpld_root),
  416. "package_content_replay": package_content_status,
  417. "detached_software_replay": detached_status,
  418. "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
  419. "hardware_validation": HARDWARE_VALIDATION,
  420. "package_content": content,
  421. "detached_software": software,
  422. "git_modes": {
  423. "LIVE_GIT": LIVE_GIT,
  424. "SNAPSHOT": SNAPSHOT,
  425. "DETACHED": DETACHED,
  426. },
  427. }
  428. stamp_replay_sidecar_identity(report, package_dir)
  429. try:
  430. from replay_semantic import stamp_replay_semantic
  431. except ImportError:
  432. from tools.replay_semantic import stamp_replay_semantic
  433. stamp_replay_semantic(report, zip_path=zip_path)
  434. return report
  435. def build_parser() -> argparse.ArgumentParser:
  436. parser = argparse.ArgumentParser(description=__doc__)
  437. parser.add_argument(
  438. "--package-dir",
  439. type=Path,
  440. required=True,
  441. help="published package directory (HANDOFF-INDEX.json + ZIP)",
  442. )
  443. parser.add_argument(
  444. "--extract-dir",
  445. type=Path,
  446. help="extract target (must not already exist)",
  447. )
  448. parser.add_argument(
  449. "--skip-software",
  450. action="store_true",
  451. help="only run package_content_replay",
  452. )
  453. parser.add_argument(
  454. "--json-out",
  455. type=Path,
  456. help="write full four-state report JSON",
  457. )
  458. return parser
  459. def main(argv: list[str] | None = None) -> int:
  460. args = build_parser().parse_args(argv)
  461. try:
  462. report = replay_review_compact(
  463. args.package_dir,
  464. extract_root=args.extract_dir,
  465. skip_software=args.skip_software,
  466. )
  467. except Exception as exc: # noqa: BLE001 - CLI boundary
  468. print(f"error: {exc}", file=sys.stderr)
  469. return 1
  470. text = json.dumps(report, ensure_ascii=False, indent=2)
  471. print(text)
  472. if args.json_out is not None:
  473. args.json_out.parent.mkdir(parents=True, exist_ok=True)
  474. args.json_out.write_text(text + "\n", encoding="utf-8")
  475. return 0 if report.get("status") == "pass" else 2
  476. if __name__ == "__main__":
  477. raise SystemExit(main())