replay_review_compact.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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 importlib.util
  12. import json
  13. import os
  14. import subprocess
  15. import sys
  16. import uuid
  17. from datetime import datetime, timezone
  18. from pathlib import Path
  19. from typing import Any
  20. ROOT = Path(__file__).resolve().parents[1]
  21. TOOLS = ROOT / "tools"
  22. if str(TOOLS) not in sys.path:
  23. sys.path.insert(0, str(TOOLS))
  24. from git_worktree_mode import ( # noqa: E402
  25. DETACHED,
  26. LIVE_GIT,
  27. SNAPSHOT,
  28. describe_git_mode,
  29. detect_git_mode,
  30. )
  31. REFERENCE_REGENERATION_REPLAY = "not_packaged_by_policy"
  32. HARDWARE_VALIDATION = "not_run"
  33. class ReplayError(RuntimeError):
  34. """Replay orchestration failure."""
  35. def _load_analyzer():
  36. path = ROOT / "package_for_agent_analysis.py"
  37. spec = importlib.util.spec_from_file_location("package_for_agent_analysis", path)
  38. if spec is None or spec.loader is None:
  39. raise ReplayError(f"unable to load packager module: {path}")
  40. module = importlib.util.module_from_spec(spec)
  41. spec.loader.exec_module(module)
  42. return module
  43. def resolve_cpld_root(extract_or_cpld: Path) -> Path:
  44. """Accept extract root, from-zip, or CPLD directory."""
  45. path = extract_or_cpld.expanduser().resolve(strict=True)
  46. candidates = (
  47. path,
  48. path / "CPLD",
  49. path / "from-zip" / "CPLD",
  50. )
  51. for candidate in candidates:
  52. if (candidate / "source").is_dir() or (candidate / "meta").is_dir():
  53. return candidate
  54. if candidate.name == "CPLD" and candidate.is_dir():
  55. return candidate
  56. raise ReplayError(f"unable to locate CPLD root under {path}")
  57. def extract_review_compact_package(
  58. package_dir: Path,
  59. *,
  60. extract_root: Path,
  61. ) -> dict[str, Any]:
  62. """Package-content replay via packager API."""
  63. analyzer = _load_analyzer()
  64. return analyzer.replay_analysis_package(package_dir, extract_root=extract_root)
  65. def _run_unittest_modules(software_root: Path, modules: list[str]) -> dict[str, Any]:
  66. """Run selected unittest modules with cwd/software_root; Git-optional."""
  67. env = os.environ.copy()
  68. env.setdefault("PRODU2_GIT_MODE", DETACHED)
  69. # Prefer the extracted source tree on sys.path for imports that use relative roots.
  70. pythonpath = str(software_root)
  71. if env.get("PYTHONPATH"):
  72. pythonpath = pythonpath + os.pathsep + env["PYTHONPATH"]
  73. env["PYTHONPATH"] = pythonpath
  74. results: list[dict[str, Any]] = []
  75. overall = "pass"
  76. for module in modules:
  77. # Only run modules that exist under the extracted source tree.
  78. rel = Path(*module.split("."))
  79. candidate = software_root / rel.with_suffix(".py")
  80. if not candidate.is_file():
  81. results.append(
  82. {
  83. "module": module,
  84. "status": "skipped_missing",
  85. "path": str(candidate),
  86. }
  87. )
  88. continue
  89. completed = subprocess.run(
  90. [sys.executable, "-B", "-m", "unittest", module, "-q"],
  91. cwd=str(software_root),
  92. env=env,
  93. stdout=subprocess.PIPE,
  94. stderr=subprocess.STDOUT,
  95. text=True,
  96. check=False,
  97. )
  98. status = "pass" if completed.returncode == 0 else "fail"
  99. if status == "fail":
  100. overall = "fail"
  101. results.append(
  102. {
  103. "module": module,
  104. "status": status,
  105. "returncode": completed.returncode,
  106. "output_tail": completed.stdout[-2000:],
  107. }
  108. )
  109. return {"status": overall, "modules": results}
  110. def _check_layout(cpld_root: Path) -> dict[str, Any]:
  111. source = cpld_root / "source"
  112. evidence = cpld_root / "evidence"
  113. meta = cpld_root / "meta"
  114. checks = {
  115. "source_dir": source.is_dir(),
  116. "meta_dir": meta.is_dir(),
  117. "evidence_dir": evidence.is_dir(),
  118. "meta_git_dir": (meta / "git").is_dir(),
  119. "no_raw_git_under_source": not (source / ".git").exists(),
  120. "no_raw_git_under_cpld": not (cpld_root / ".git").exists(),
  121. }
  122. # Prefer package contract markers when present.
  123. project = source / "projects" / "prod2u-door-temp" / "project.json"
  124. checks["project_contract_present"] = project.is_file()
  125. status = "pass" if all(
  126. checks[key]
  127. for key in (
  128. "source_dir",
  129. "meta_dir",
  130. "no_raw_git_under_source",
  131. "no_raw_git_under_cpld",
  132. )
  133. ) else "fail"
  134. return {"status": status, "checks": checks}
  135. def _board_detached_check(cpld_root: Path) -> dict[str, Any]:
  136. """Run board-viewer detached validation when P5 assets/API are available."""
  137. generated_candidates = (
  138. cpld_root / "evidence" / "board-viewer",
  139. cpld_root / "source" / "tools" / "board-viewer" / "generated",
  140. )
  141. generated = next((path for path in generated_candidates if path.is_dir()), None)
  142. if generated is None:
  143. return {
  144. "status": "skipped_no_board_assets",
  145. "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
  146. }
  147. # Prefer extracted source validator; fall back to live repo tools.
  148. validator_candidates = (
  149. cpld_root / "source" / "tools" / "board-viewer" / "validate_detached_derived.py",
  150. ROOT / "tools" / "board-viewer" / "validate_detached_derived.py",
  151. )
  152. validator = next((path for path in validator_candidates if path.is_file()), None)
  153. if validator is None:
  154. # Lightweight local checks without P5 module.
  155. required = (
  156. "board-data.json",
  157. "build-info.json",
  158. "import-report.json",
  159. "board-copper.svg",
  160. "board-silkscreen.svg",
  161. "board-mask-edge.svg",
  162. "board-copper-back.svg",
  163. "board-silkscreen-back.svg",
  164. "board-mask-edge-back.svg",
  165. )
  166. missing = [name for name in required if not (generated / name).is_file()]
  167. return {
  168. "status": "pass" if not missing else "fail",
  169. "mode": "asset_presence",
  170. "generated_dir": str(generated),
  171. "missing": missing,
  172. "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
  173. "regeneration_claim": "none",
  174. }
  175. completed = subprocess.run(
  176. [
  177. sys.executable,
  178. "-B",
  179. str(validator),
  180. "--generated",
  181. str(generated),
  182. ],
  183. cwd=str(validator.parent),
  184. stdout=subprocess.PIPE,
  185. stderr=subprocess.STDOUT,
  186. text=True,
  187. check=False,
  188. )
  189. return {
  190. "status": "pass" if completed.returncode == 0 else "fail",
  191. "mode": "validate_detached_derived",
  192. "generated_dir": str(generated),
  193. "returncode": completed.returncode,
  194. "output_tail": completed.stdout[-2000:],
  195. "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
  196. "regeneration_claim": "none",
  197. }
  198. def run_detached_software_replay(cpld_root: Path) -> dict[str, Any]:
  199. """Git-optional software replay against extracted CPLD tree."""
  200. cpld_root = resolve_cpld_root(cpld_root)
  201. source_root = cpld_root / "source"
  202. git_mode = detect_git_mode(cpld_root)
  203. if git_mode == LIVE_GIT:
  204. # Extracted compact trees must not expose raw .git; live_git here is unexpected.
  205. git_info = describe_git_mode(cpld_root)
  206. else:
  207. git_info = describe_git_mode(cpld_root)
  208. layout = _check_layout(cpld_root)
  209. board = _board_detached_check(cpld_root)
  210. unit_modules = [
  211. "tests.unit.test_protocol",
  212. "tests.unit.test_project_config",
  213. "tests.unit.test_product_contract_coverage",
  214. ]
  215. unit = (
  216. _run_unittest_modules(source_root, unit_modules)
  217. if source_root.is_dir()
  218. else {"status": "fail", "modules": [], "reason": "missing source/"}
  219. )
  220. # Meta git provenance must be usable without raw .git.
  221. meta_git = cpld_root / "meta" / "git"
  222. provenance = {
  223. "status": "pass" if meta_git.is_dir() else "fail",
  224. "head_txt": (meta_git / "HEAD.txt").is_file() if meta_git.is_dir() else False,
  225. "tree_manifest": (meta_git / "tree-manifest.json").is_file()
  226. if meta_git.is_dir()
  227. else False,
  228. "sanitized_snapshot_status": (
  229. meta_git / "sanitized-snapshot-status.json"
  230. ).is_file()
  231. if meta_git.is_dir()
  232. else False,
  233. "raw_git_required": False,
  234. }
  235. parts = {
  236. "layout": layout["status"],
  237. "provenance": provenance["status"],
  238. "unit": unit["status"],
  239. "board": board["status"],
  240. }
  241. # skipped_* board does not fail the lane; fail/skip-missing unit modules are soft
  242. # unless layout/provenance fail.
  243. soft_board = board["status"].startswith("skipped_")
  244. soft_unit_skip_only = unit["status"] == "pass" or (
  245. unit["status"] != "fail"
  246. and all(
  247. row.get("status") in {"pass", "skipped_missing"}
  248. for row in unit.get("modules", [])
  249. )
  250. )
  251. if layout["status"] != "pass" or provenance["status"] != "pass":
  252. overall = "fail"
  253. elif unit["status"] == "fail":
  254. overall = "fail"
  255. elif not soft_board and board["status"] == "fail":
  256. overall = "fail"
  257. else:
  258. overall = "pass"
  259. return {
  260. "status": overall,
  261. "git_mode": git_mode,
  262. "git_mode_info": git_info,
  263. "software_root": str(source_root),
  264. "layout": layout,
  265. "provenance": provenance,
  266. "unit": unit,
  267. "board": board,
  268. "part_statuses": parts,
  269. "soft_unit_skip_only": soft_unit_skip_only,
  270. "note": (
  271. "Detached software replay does not require raw .git; "
  272. "live_git commit-compare paths remain strict elsewhere."
  273. ),
  274. }
  275. def replay_review_compact(
  276. package_dir: Path,
  277. *,
  278. extract_root: Path | None = None,
  279. skip_software: bool = False,
  280. ) -> dict[str, Any]:
  281. """Run the four-state review-compact replay."""
  282. package_dir = package_dir.expanduser().resolve(strict=True)
  283. if extract_root is None:
  284. # Must NOT pre-create the directory: replay_analysis_package refuses
  285. # extract roots that already exist (exist_ok=False).
  286. extract_root = Path(os.environ.get("TMPDIR", "/tmp")) / (
  287. "prod2u-review-compact-replay-" + uuid.uuid4().hex
  288. )
  289. else:
  290. extract_root = extract_root.expanduser().resolve(strict=False)
  291. content = extract_review_compact_package(package_dir, extract_root=extract_root)
  292. package_content_status = str(content.get("package_content_replay") or content.get("status") or "fail")
  293. cpld_root_raw = content.get("cpld_root")
  294. if not cpld_root_raw:
  295. cpld_root = resolve_cpld_root(extract_root)
  296. else:
  297. cpld_root = Path(str(cpld_root_raw))
  298. if skip_software:
  299. software: dict[str, Any] = {
  300. "status": "not_run",
  301. "note": "skipped by --skip-software",
  302. }
  303. detached_status = "not_run"
  304. else:
  305. software = run_detached_software_replay(cpld_root)
  306. detached_status = str(software.get("status") or "fail")
  307. overall = "pass"
  308. if package_content_status != "pass":
  309. overall = "fail"
  310. elif detached_status not in {"pass", "not_run"}:
  311. overall = "fail"
  312. return {
  313. "schema": "cpld-review-compact-four-state-replay-v1",
  314. "generated_at_utc": datetime.now(timezone.utc).isoformat(),
  315. "status": overall,
  316. "package_dir": str(package_dir),
  317. "extract_root": str(extract_root),
  318. "cpld_root": str(cpld_root),
  319. "package_content_replay": package_content_status,
  320. "detached_software_replay": detached_status,
  321. "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
  322. "hardware_validation": HARDWARE_VALIDATION,
  323. "package_content": content,
  324. "detached_software": software,
  325. "git_modes": {
  326. "LIVE_GIT": LIVE_GIT,
  327. "SNAPSHOT": SNAPSHOT,
  328. "DETACHED": DETACHED,
  329. },
  330. }
  331. def build_parser() -> argparse.ArgumentParser:
  332. parser = argparse.ArgumentParser(description=__doc__)
  333. parser.add_argument(
  334. "--package-dir",
  335. type=Path,
  336. required=True,
  337. help="published package directory (HANDOFF-INDEX.json + ZIP)",
  338. )
  339. parser.add_argument(
  340. "--extract-dir",
  341. type=Path,
  342. help="extract target (must not already exist)",
  343. )
  344. parser.add_argument(
  345. "--skip-software",
  346. action="store_true",
  347. help="only run package_content_replay",
  348. )
  349. parser.add_argument(
  350. "--json-out",
  351. type=Path,
  352. help="write full four-state report JSON",
  353. )
  354. return parser
  355. def main(argv: list[str] | None = None) -> int:
  356. args = build_parser().parse_args(argv)
  357. try:
  358. report = replay_review_compact(
  359. args.package_dir,
  360. extract_root=args.extract_dir,
  361. skip_software=args.skip_software,
  362. )
  363. except Exception as exc: # noqa: BLE001 - CLI boundary
  364. print(f"error: {exc}", file=sys.stderr)
  365. return 1
  366. text = json.dumps(report, ensure_ascii=False, indent=2)
  367. print(text)
  368. if args.json_out is not None:
  369. args.json_out.parent.mkdir(parents=True, exist_ok=True)
  370. args.json_out.write_text(text + "\n", encoding="utf-8")
  371. return 0 if report.get("status") == "pass" else 2
  372. if __name__ == "__main__":
  373. raise SystemExit(main())