replay_semantic.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. #!/usr/bin/env python3
  2. """Independent review-ZIP exact inventory + detached-replay semantic digest.
  3. Sidecar nested ``status: pass`` is not evidence. Final claimed PASS requires
  4. exact VOLUME-MANIFEST inventory, a canonical ``replay_semantic`` object, and
  5. ``replay_semantic_sha256``. Inventory/path failures skip actual extract/replay.
  6. Dummy unit-test ZIPs without a source tree still run exact inventory and
  7. object/digest checks; they skip only the software rerun.
  8. """
  9. from __future__ import annotations
  10. import hashlib
  11. import json
  12. import shutil
  13. import stat
  14. import tempfile
  15. import zipfile
  16. from pathlib import Path
  17. from typing import Any
  18. VOLUME_MANIFEST_MEMBERS = (
  19. "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json",
  20. "HANDOFF-METADATA/VOLUME-MANIFEST.json",
  21. )
  22. OFFICIAL_MANIFEST_SCHEMA = "cpld-agent-analysis-volume-v1"
  23. COMPAT_MANIFEST_SCHEMA = "prod2u-volume-manifest-v1"
  24. ALLOWED_MANIFEST_SCHEMAS = frozenset({OFFICIAL_MANIFEST_SCHEMA, COMPAT_MANIFEST_SCHEMA})
  25. SHA256_HEX = 64
  26. class ArchivePathError(ValueError):
  27. """Unsafe or non-canonical ZIP member path."""
  28. def parse_archive_member(name: str, *, directory: bool = False) -> str:
  29. """Canonical relative path. Reject rather than silently rewrite."""
  30. raw = str(name or "")
  31. if not raw:
  32. raise ArchivePathError("empty")
  33. if "\x00" in raw:
  34. raise ArchivePathError("nul")
  35. if any(ord(ch) < 32 for ch in raw):
  36. raise ArchivePathError("control_char")
  37. if "\\" in raw:
  38. raise ArchivePathError("backslash")
  39. if raw.startswith("/") or raw.startswith("//"):
  40. raise ArchivePathError("absolute")
  41. if raw.startswith("\\\\") or raw.startswith("//"):
  42. raise ArchivePathError("unc")
  43. if len(raw) >= 2 and raw[1] == ":" and raw[0].isalpha():
  44. raise ArchivePathError("windows_drive")
  45. trailing_dir = raw.endswith("/")
  46. body = raw[:-1] if trailing_dir else raw
  47. while body.startswith("./"):
  48. body = body[2:]
  49. if not body:
  50. raise ArchivePathError("empty")
  51. parts = body.split("/")
  52. if any(part in ("", ".", "..") for part in parts):
  53. raise ArchivePathError("dot_segment")
  54. if directory or trailing_dir:
  55. return body + "/"
  56. return body
  57. def _zip_info_is_symlink(info: zipfile.ZipInfo) -> bool:
  58. mode = (info.external_attr >> 16) & 0xFFFF
  59. if mode and stat.S_IFMT(mode) == stat.S_IFLNK:
  60. return True
  61. return False
  62. def _zip_info_is_special(info: zipfile.ZipInfo) -> bool:
  63. mode = (info.external_attr >> 16) & 0xFFFF
  64. if not mode:
  65. return False
  66. kind = stat.S_IFMT(mode)
  67. return kind not in (0, stat.S_IFREG, stat.S_IFDIR)
  68. def review_zip_has_source_tree(zip_path: Path) -> bool:
  69. try:
  70. with zipfile.ZipFile(zip_path) as zf:
  71. for raw in zf.namelist():
  72. if raw.endswith("/"):
  73. continue
  74. try:
  75. name = parse_archive_member(raw)
  76. except ArchivePathError:
  77. continue
  78. if name.startswith("source/") or "/source/" in f"/{name}":
  79. return True
  80. except (OSError, zipfile.BadZipFile):
  81. return False
  82. return False
  83. def read_volume_manifest(zip_path: Path) -> dict[str, Any] | None:
  84. try:
  85. with zipfile.ZipFile(zip_path) as zf:
  86. names = list(zf.namelist())
  87. hits = [member for member in VOLUME_MANIFEST_MEMBERS if member in names]
  88. if len(hits) != 1:
  89. return None
  90. doc = json.loads(zf.read(hits[0]).decode("utf-8"))
  91. if isinstance(doc, dict):
  92. return doc
  93. except (OSError, zipfile.BadZipFile, json.JSONDecodeError, UnicodeDecodeError):
  94. return None
  95. return None
  96. def _int_or_none(value: Any) -> int | None:
  97. if isinstance(value, bool) or value is None:
  98. return None
  99. try:
  100. return int(value)
  101. except (TypeError, ValueError):
  102. return None
  103. def _looks_sha256(value: Any) -> str:
  104. text = str(value or "").strip().lower()
  105. if len(text) != SHA256_HEX:
  106. return ""
  107. if any(ch not in "0123456789abcdef" for ch in text):
  108. return ""
  109. return text
  110. def semantic_sha256(obj: dict[str, Any]) -> str:
  111. blob = json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode(
  112. "utf-8"
  113. )
  114. return hashlib.sha256(blob).hexdigest()
  115. def inventory_digest(inventory: dict[str, Any]) -> str:
  116. body = {
  117. "volume_manifest_member": inventory.get("volume_manifest_member"),
  118. "volume_manifest_schema": inventory.get("volume_manifest_schema"),
  119. "volume_manifest_sha256": inventory.get("volume_manifest_sha256"),
  120. "inventory_file_count": inventory.get("inventory_file_count"),
  121. "inventory_member_count": inventory.get("inventory_member_count"),
  122. "inventory_uncompressed_bytes": inventory.get("inventory_uncompressed_bytes"),
  123. "inventory_rows": inventory.get("inventory_rows") or [],
  124. }
  125. return semantic_sha256(body)
  126. def semantic_object(
  127. *,
  128. content: dict[str, Any],
  129. software: dict[str, Any],
  130. inventory: dict[str, Any] | None = None,
  131. ) -> dict[str, Any]:
  132. """Canonical subset used for sidecar vs nested vs actual-rerun comparison."""
  133. unit = software.get("unit") if isinstance(software.get("unit"), dict) else {}
  134. modules: list[dict[str, Any]] = []
  135. raw_modules = unit.get("modules") if isinstance(unit.get("modules"), list) else []
  136. for mod in raw_modules:
  137. if not isinstance(mod, dict):
  138. continue
  139. modules.append(
  140. {
  141. "module": str(mod.get("module") or ""),
  142. "status": str(mod.get("status") or ""),
  143. "returncode": _int_or_none(mod.get("returncode")),
  144. }
  145. )
  146. modules.sort(key=lambda row: row["module"])
  147. layout = software.get("layout") if isinstance(software.get("layout"), dict) else {}
  148. checks = layout.get("checks") if isinstance(layout.get("checks"), dict) else {}
  149. provenance = (
  150. software.get("provenance") if isinstance(software.get("provenance"), dict) else {}
  151. )
  152. board = software.get("board") if isinstance(software.get("board"), dict) else {}
  153. obj: dict[str, Any] = {
  154. "checked_files": _int_or_none(content.get("checked_files")) or 0,
  155. "git_mode": str(software.get("git_mode") or ""),
  156. "layout_status": str(layout.get("status") or ""),
  157. "layout_checks": {str(k): checks.get(k) is True for k in sorted(checks)},
  158. "provenance": {
  159. "status": str(provenance.get("status") or ""),
  160. "head_txt": provenance.get("head_txt") is True,
  161. "tree_manifest": provenance.get("tree_manifest") is True,
  162. "sanitized_snapshot_status": provenance.get("sanitized_snapshot_status") is True,
  163. "raw_git_required": provenance.get("raw_git_required") is True,
  164. },
  165. "unit_status": str(unit.get("status") or ""),
  166. "unit_modules": modules,
  167. "board": {
  168. "status": str(board.get("status") or ""),
  169. "mode": str(board.get("mode") or ""),
  170. "returncode": _int_or_none(board.get("returncode")),
  171. "reference_regeneration_replay": str(
  172. board.get("reference_regeneration_replay") or ""
  173. ),
  174. },
  175. "software_status": str(software.get("status") or ""),
  176. "volume_manifest_sha256": "",
  177. "inventory_digest": "",
  178. "inventory_file_count": 0,
  179. "inventory_member_count": 0,
  180. }
  181. if inventory:
  182. obj["volume_manifest_sha256"] = str(inventory.get("volume_manifest_sha256") or "")
  183. obj["inventory_digest"] = str(inventory.get("inventory_digest") or "")
  184. obj["inventory_file_count"] = int(inventory.get("inventory_file_count") or 0)
  185. obj["inventory_member_count"] = int(inventory.get("inventory_member_count") or 0)
  186. obj["checked_files"] = int(inventory.get("inventory_file_count") or 0)
  187. return obj
  188. def stamp_replay_semantic(
  189. report: dict[str, Any],
  190. *,
  191. zip_path: Path | None = None,
  192. ) -> dict[str, Any]:
  193. content = report.get("package_content") if isinstance(report.get("package_content"), dict) else {}
  194. software = (
  195. report.get("detached_software")
  196. if isinstance(report.get("detached_software"), dict)
  197. else {}
  198. )
  199. inventory = None
  200. if zip_path is not None:
  201. failures, inventory = verify_exact_inventory(zip_path)
  202. if failures:
  203. report["inventory_stamp_failures"] = list(failures)
  204. inventory = None
  205. elif inventory is not None:
  206. content["checked_files"] = int(inventory["inventory_file_count"])
  207. obj = semantic_object(content=content, software=software, inventory=inventory)
  208. report["replay_semantic"] = obj
  209. report["replay_semantic_sha256"] = semantic_sha256(obj)
  210. if inventory is not None:
  211. report["volume_manifest_sha256"] = inventory["volume_manifest_sha256"]
  212. report["inventory_digest"] = inventory["inventory_digest"]
  213. report["inventory_file_count"] = inventory["inventory_file_count"]
  214. report["inventory_member_count"] = inventory["inventory_member_count"]
  215. return report
  216. def align_checked_files_to_manifest(content: dict[str, Any], zip_path: Path) -> None:
  217. """Force package_content.checked_files to VOLUME-MANIFEST.file_count."""
  218. _failures, inventory = verify_exact_inventory(zip_path)
  219. if inventory is None:
  220. return
  221. content["checked_files"] = int(inventory["inventory_file_count"])
  222. def _ordinary_zip_members(zf: zipfile.ZipFile) -> tuple[list[str], list[str]]:
  223. """Return (canonical ordinary file members, failure codes)."""
  224. failures: list[str] = []
  225. ordinary: list[str] = []
  226. seen_raw: list[str] = []
  227. for info in zf.infolist():
  228. raw = info.filename
  229. seen_raw.append(raw)
  230. if info.is_dir() or raw.endswith("/"):
  231. try:
  232. parse_archive_member(raw, directory=True)
  233. except ArchivePathError:
  234. failures.append("replay_archive_unsafe_path")
  235. continue
  236. if _zip_info_is_symlink(info) or _zip_info_is_special(info):
  237. failures.append("replay_archive_non_regular_member")
  238. continue
  239. try:
  240. name = parse_archive_member(raw)
  241. except ArchivePathError:
  242. failures.append("replay_archive_unsafe_path")
  243. continue
  244. ordinary.append(name)
  245. if len(seen_raw) != len(set(seen_raw)):
  246. failures.append("replay_archive_duplicate_member")
  247. if len(ordinary) != len(set(ordinary)):
  248. failures.append("replay_archive_duplicate_member")
  249. folded = [n.casefold() for n in ordinary]
  250. if len(folded) != len(set(folded)):
  251. failures.append("replay_volume_manifest_casefold_collision")
  252. return ordinary, list(dict.fromkeys(failures))
  253. def verify_exact_inventory(zip_path: Path) -> tuple[list[str], dict[str, Any] | None]:
  254. """Exact VOLUME-MANIFEST inventory. Fail-closed; never silently rewrite paths."""
  255. failures: list[str] = []
  256. try:
  257. zf_ctx = zipfile.ZipFile(zip_path)
  258. except (OSError, zipfile.BadZipFile):
  259. return ["replay_volume_manifest_inventory_mismatch"], None
  260. with zf_ctx as zf:
  261. ordinary, path_failures = _ordinary_zip_members(zf)
  262. failures.extend(path_failures)
  263. ordinary_set = set(ordinary)
  264. present_manifests = [m for m in VOLUME_MANIFEST_MEMBERS if m in ordinary_set]
  265. if len(present_manifests) == 0:
  266. failures.append("replay_volume_manifest_missing")
  267. return list(dict.fromkeys(failures)), None
  268. if len(present_manifests) != 1:
  269. failures.append("replay_volume_manifest_duplicate_alias")
  270. return list(dict.fromkeys(failures)), None
  271. manifest_member = present_manifests[0]
  272. try:
  273. manifest_bytes = zf.read(manifest_member)
  274. manifest = json.loads(manifest_bytes.decode("utf-8"))
  275. except (KeyError, UnicodeDecodeError, json.JSONDecodeError):
  276. failures.append("replay_volume_manifest_missing")
  277. return list(dict.fromkeys(failures)), None
  278. if not isinstance(manifest, dict):
  279. failures.append("replay_volume_manifest_missing")
  280. return list(dict.fromkeys(failures)), None
  281. schema = str(manifest.get("schema") or "")
  282. if schema not in ALLOWED_MANIFEST_SCHEMAS:
  283. failures.append("replay_volume_manifest_schema_invalid")
  284. files = manifest.get("files")
  285. if not isinstance(files, list):
  286. failures.append("replay_volume_manifest_inventory_mismatch")
  287. return list(dict.fromkeys(failures)), None
  288. claimed_count = _int_or_none(manifest.get("file_count"))
  289. if claimed_count is None or claimed_count < 0:
  290. failures.append("replay_volume_manifest_missing")
  291. return list(dict.fromkeys(failures)), None
  292. if claimed_count != len(files):
  293. failures.append("replay_volume_manifest_file_count_mismatch")
  294. if schema == OFFICIAL_MANIFEST_SCHEMA:
  295. package_name = str(manifest.get("package_name") or "").strip()
  296. volume_number = _int_or_none(manifest.get("volume_number"))
  297. volume_count = _int_or_none(manifest.get("volume_count"))
  298. if not package_name:
  299. failures.append("replay_volume_manifest_schema_invalid")
  300. if volume_number is None or volume_number < 1:
  301. failures.append("replay_volume_manifest_schema_invalid")
  302. if volume_count is None or volume_count < 1:
  303. failures.append("replay_volume_manifest_schema_invalid")
  304. rows: list[dict[str, Any]] = []
  305. row_paths: list[str] = []
  306. row_folded: list[str] = []
  307. size_sum = 0
  308. for row in files:
  309. if not isinstance(row, dict):
  310. failures.append("replay_volume_manifest_inventory_mismatch")
  311. continue
  312. if "path" in row and "archive_path" not in row:
  313. failures.append("replay_volume_manifest_row_missing_archive_path")
  314. continue
  315. if "archive_path" not in row:
  316. failures.append("replay_volume_manifest_row_missing_archive_path")
  317. continue
  318. if "size" not in row:
  319. failures.append("replay_volume_manifest_row_missing_size")
  320. continue
  321. if "sha256" not in row:
  322. failures.append("replay_volume_manifest_row_missing_sha256")
  323. continue
  324. try:
  325. rel = parse_archive_member(str(row.get("archive_path") or ""))
  326. except ArchivePathError:
  327. failures.append("replay_archive_unsafe_path")
  328. continue
  329. if rel.endswith("/"):
  330. failures.append("replay_volume_manifest_row_directory")
  331. continue
  332. if rel == manifest_member:
  333. failures.append("replay_volume_manifest_self_listed")
  334. continue
  335. size = _int_or_none(row.get("size"))
  336. if size is None or size < 0:
  337. failures.append("replay_volume_manifest_row_invalid_size")
  338. continue
  339. sha = _looks_sha256(row.get("sha256"))
  340. if not sha:
  341. failures.append("replay_volume_manifest_row_invalid_sha256")
  342. continue
  343. if rel not in ordinary_set:
  344. failures.append("replay_volume_manifest_listed_missing")
  345. continue
  346. data = zf.read(rel)
  347. if size != len(data):
  348. failures.append("replay_volume_manifest_size_mismatch")
  349. continue
  350. if sha != hashlib.sha256(data).hexdigest():
  351. failures.append("replay_volume_manifest_hash_mismatch")
  352. continue
  353. row_paths.append(rel)
  354. row_folded.append(rel.casefold())
  355. size_sum += size
  356. rows.append({"archive_path": rel, "size": size, "sha256": sha})
  357. if len(row_paths) != len(set(row_paths)):
  358. failures.append("replay_volume_manifest_duplicate_path")
  359. if len(row_folded) != len(set(row_folded)):
  360. failures.append("replay_volume_manifest_casefold_collision")
  361. expected = set(row_paths) | {manifest_member}
  362. extra = ordinary_set - expected
  363. missing = set(row_paths) - ordinary_set
  364. if extra:
  365. failures.append("replay_volume_manifest_unmanifested_extra")
  366. if missing:
  367. failures.append("replay_volume_manifest_listed_missing")
  368. uncompressed = _int_or_none(manifest.get("uncompressed_bytes"))
  369. if schema == OFFICIAL_MANIFEST_SCHEMA:
  370. if uncompressed is None:
  371. failures.append("replay_volume_manifest_uncompressed_bytes_mismatch")
  372. elif uncompressed != size_sum:
  373. failures.append("replay_volume_manifest_uncompressed_bytes_mismatch")
  374. elif uncompressed is not None and uncompressed != size_sum:
  375. failures.append("replay_volume_manifest_uncompressed_bytes_mismatch")
  376. failures = list(dict.fromkeys(failures))
  377. if failures:
  378. return failures, None
  379. inventory = {
  380. "volume_manifest_member": manifest_member,
  381. "volume_manifest_schema": schema,
  382. "volume_manifest_sha256": hashlib.sha256(manifest_bytes).hexdigest(),
  383. "inventory_file_count": claimed_count,
  384. "inventory_member_count": len(ordinary_set),
  385. "inventory_uncompressed_bytes": size_sum,
  386. "inventory_rows": sorted(rows, key=lambda r: r["archive_path"]),
  387. }
  388. inventory["inventory_digest"] = inventory_digest(inventory)
  389. return [], inventory
  390. def verify_volume_manifest_inventory(zip_path: Path) -> list[str]:
  391. failures, _inventory = verify_exact_inventory(zip_path)
  392. return failures
  393. def safe_extract_zip(zip_path: Path, dest: Path) -> list[Path]:
  394. """Extract regular files only after strict path validation. No extractall."""
  395. failures, inventory = verify_exact_inventory(zip_path)
  396. if failures or inventory is None:
  397. raise ValueError("unsafe or inexact archive inventory: " + ",".join(failures))
  398. allowed = {row["archive_path"] for row in inventory["inventory_rows"]}
  399. allowed.add(inventory["volume_manifest_member"])
  400. dest.mkdir(parents=True, exist_ok=False)
  401. dest_res = dest.resolve()
  402. written: list[Path] = []
  403. with zipfile.ZipFile(zip_path) as zf:
  404. for info in zf.infolist():
  405. if info.is_dir() or info.filename.endswith("/"):
  406. continue
  407. name = parse_archive_member(info.filename)
  408. if name not in allowed:
  409. raise ValueError(f"extract of non-inventory member: {info.filename!r}")
  410. target = dest / Path(*name.split("/"))
  411. resolved = target.resolve()
  412. if dest_res not in resolved.parents and resolved != dest_res:
  413. raise ValueError(f"zip-slip archive member: {info.filename!r}")
  414. target.parent.mkdir(parents=True, exist_ok=True)
  415. with zf.open(info, "r") as source, target.open("wb") as out:
  416. shutil.copyfileobj(source, out, length=1024 * 1024)
  417. written.append(target)
  418. return written
  419. def _run_actual_software_replay(zip_path: Path) -> dict[str, Any]:
  420. try:
  421. from replay_review_compact import resolve_cpld_root, run_detached_software_replay
  422. except ImportError:
  423. from tools.replay_review_compact import ( # type: ignore
  424. resolve_cpld_root,
  425. run_detached_software_replay,
  426. )
  427. tmp = Path(tempfile.mkdtemp(prefix="prod2u-replay-bind-"))
  428. try:
  429. dest = tmp / "from-zip"
  430. safe_extract_zip(zip_path, dest)
  431. cpld = resolve_cpld_root(dest)
  432. return run_detached_software_replay(cpld)
  433. finally:
  434. shutil.rmtree(tmp, ignore_errors=True)
  435. def _field_mismatches(claimed: dict[str, Any], actual: dict[str, Any]) -> list[str]:
  436. failures: list[str] = []
  437. if claimed["unit_modules"] != actual["unit_modules"] or claimed["unit_status"] != actual["unit_status"]:
  438. failures.append("replay_semantic_unit_mismatch")
  439. if claimed["layout_checks"] != actual["layout_checks"] or claimed["layout_status"] != actual["layout_status"]:
  440. failures.append("replay_semantic_layout_mismatch")
  441. if claimed["provenance"] != actual["provenance"]:
  442. failures.append("replay_semantic_provenance_mismatch")
  443. if claimed["board"] != actual["board"]:
  444. failures.append("replay_semantic_board_mismatch")
  445. if claimed["software_status"] != actual["software_status"]:
  446. failures.append("replay_semantic_software_status_mismatch")
  447. if claimed["git_mode"] and actual["git_mode"] and claimed["git_mode"] != actual["git_mode"]:
  448. failures.append("replay_semantic_git_mode_mismatch")
  449. if claimed["checked_files"] != actual["checked_files"]:
  450. failures.append("replay_semantic_checked_files_mismatch")
  451. if claimed.get("volume_manifest_sha256") != actual.get("volume_manifest_sha256"):
  452. failures.append("replay_semantic_inventory_mismatch")
  453. if claimed.get("inventory_digest") != actual.get("inventory_digest"):
  454. failures.append("replay_semantic_inventory_mismatch")
  455. if claimed.get("inventory_file_count") != actual.get("inventory_file_count"):
  456. failures.append("replay_semantic_inventory_mismatch")
  457. if claimed.get("inventory_member_count") != actual.get("inventory_member_count"):
  458. failures.append("replay_semantic_inventory_mismatch")
  459. return list(dict.fromkeys(failures))
  460. def bind_independent_replay(zip_path: Path, sidecar: dict[str, Any]) -> list[str]:
  461. """Four-way bind: sidecar object, digest, nested evidence, actual ZIP.
  462. Dummy ZIPs without a source tree skip only the independent software rerun.
  463. Inventory/path failures never continue into extract/replay.
  464. """
  465. failures, inventory = verify_exact_inventory(zip_path)
  466. content = sidecar.get("package_content") if isinstance(sidecar.get("package_content"), dict) else {}
  467. claimed_sw = (
  468. sidecar.get("detached_software")
  469. if isinstance(sidecar.get("detached_software"), dict)
  470. else {}
  471. )
  472. nested = semantic_object(content=content, software=claimed_sw, inventory=inventory)
  473. sidecar_obj = sidecar.get("replay_semantic")
  474. if not isinstance(sidecar_obj, dict) or not sidecar_obj:
  475. failures.append("replay_semantic_missing")
  476. sidecar_obj = None
  477. claimed_digest = str(sidecar.get("replay_semantic_sha256") or "").strip().lower()
  478. if not claimed_digest:
  479. failures.append("replay_semantic_sha256_missing")
  480. elif sidecar_obj is not None:
  481. recomputed = semantic_sha256(sidecar_obj)
  482. if claimed_digest != recomputed:
  483. failures.append("replay_semantic_sha256_mismatch")
  484. if sidecar_obj is not None and sidecar_obj != nested:
  485. failures.append("replay_semantic_nested_mismatch")
  486. failures.extend(_field_mismatches(sidecar_obj, nested))
  487. if inventory is None or any(
  488. code.startswith("replay_volume_manifest_") or code.startswith("replay_archive_")
  489. for code in failures
  490. ):
  491. return list(dict.fromkeys(failures))
  492. if sidecar_obj is not None:
  493. failures.extend(_field_mismatches(sidecar_obj, nested))
  494. if not review_zip_has_source_tree(zip_path):
  495. return list(dict.fromkeys(failures))
  496. try:
  497. actual_software = _run_actual_software_replay(zip_path)
  498. except Exception: # noqa: BLE001 — bind must fail-closed, not raise
  499. failures.append("replay_actual_rerun_error")
  500. return list(dict.fromkeys(failures))
  501. if str(actual_software.get("status") or "").casefold() != "pass":
  502. failures.append("replay_actual_rerun_not_pass")
  503. actual = semantic_object(content=content, software=actual_software, inventory=inventory)
  504. if sidecar_obj is not None and sidecar_obj != actual:
  505. failures.append("replay_semantic_actual_mismatch")
  506. failures.extend(_field_mismatches(sidecar_obj, actual))
  507. failures.extend(_field_mismatches(nested, actual))
  508. return list(dict.fromkeys(failures))