test_replay_review_compact.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. #!/usr/bin/env python3
  2. """Focused tests for Lane P2 four-state replay and Git-optional modes."""
  3. from __future__ import annotations
  4. import importlib.util
  5. import json
  6. import os
  7. import shutil
  8. import subprocess
  9. import sys
  10. import tempfile
  11. import unittest
  12. import zipfile
  13. from pathlib import Path
  14. from types import ModuleType
  15. ROOT = Path(__file__).resolve().parents[2]
  16. TOOLS = ROOT / "tools"
  17. ANALYZER_PATH = ROOT / "package_for_agent_analysis.py"
  18. def write_file(root: Path, relative: str, data: bytes = b"fixture\n") -> Path:
  19. path = root / Path(relative)
  20. path.parent.mkdir(parents=True, exist_ok=True)
  21. path.write_bytes(data)
  22. return path
  23. def load_module(path: Path, name: str) -> ModuleType:
  24. spec = importlib.util.spec_from_file_location(name, path)
  25. assert spec is not None and spec.loader is not None
  26. module = importlib.util.module_from_spec(spec)
  27. sys.modules[name] = module
  28. spec.loader.exec_module(module)
  29. return module
  30. def load_analyzer() -> ModuleType:
  31. return load_module(ANALYZER_PATH, "package_for_agent_analysis_p2")
  32. def load_handoff() -> ModuleType:
  33. sys.path.insert(0, str(TOOLS))
  34. return load_module(TOOLS / "package_agent_handoff.py", "package_agent_handoff_p2")
  35. def load_git_mode() -> ModuleType:
  36. sys.path.insert(0, str(TOOLS))
  37. return load_module(TOOLS / "git_worktree_mode.py", "git_worktree_mode_p2")
  38. def load_replay() -> ModuleType:
  39. sys.path.insert(0, str(TOOLS))
  40. return load_module(TOOLS / "replay_review_compact.py", "replay_review_compact_p2")
  41. class GitWorktreeModeTests(unittest.TestCase):
  42. def test_detect_live_git_on_repo_root(self) -> None:
  43. """Construct a real live Git fixture — do not assume arbitrary ROOT is live."""
  44. git_mode = load_git_mode()
  45. git = shutil.which("git")
  46. if not git:
  47. self.skipTest("Git is required")
  48. old = os.environ.pop(git_mode.ENV_GIT_MODE, None)
  49. try:
  50. with tempfile.TemporaryDirectory() as tmp:
  51. repo = Path(tmp) / "live-repo"
  52. repo.mkdir()
  53. subprocess.run([git, "init", "-q", str(repo)], check=True)
  54. subprocess.run(
  55. [git, "-C", str(repo), "config", "user.name", "Test"], check=True
  56. )
  57. subprocess.run(
  58. [git, "-C", str(repo), "config", "user.email", "t@example.invalid"],
  59. check=True,
  60. )
  61. write_file(repo, "tracked.txt", b"live\n")
  62. subprocess.run([git, "-C", str(repo), "add", "tracked.txt"], check=True)
  63. subprocess.run(
  64. [git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True
  65. )
  66. mode = git_mode.detect_git_mode(repo)
  67. self.assertEqual(mode, git_mode.LIVE_GIT)
  68. self.assertEqual(git_mode.live_only_status(repo), "pass")
  69. finally:
  70. if old is not None:
  71. os.environ[git_mode.ENV_GIT_MODE] = old
  72. def test_detached_without_raw_git(self) -> None:
  73. git_mode = load_git_mode()
  74. with tempfile.TemporaryDirectory() as tmp:
  75. root = Path(tmp) / "extract"
  76. write_file(root, "source/src/core.v", b"module core; endmodule\n")
  77. write_file(root, "meta/git/HEAD.txt", b"deadbeef\n")
  78. old = os.environ.pop(git_mode.ENV_GIT_MODE, None)
  79. try:
  80. self.assertEqual(git_mode.detect_git_mode(root), git_mode.DETACHED)
  81. self.assertTrue(git_mode.git_optional_ok(root))
  82. finally:
  83. if old is not None:
  84. os.environ[git_mode.ENV_GIT_MODE] = old
  85. def test_snapshot_mode_when_bundle_present(self) -> None:
  86. git_mode = load_git_mode()
  87. with tempfile.TemporaryDirectory() as tmp:
  88. root = Path(tmp) / "extract"
  89. write_file(root, "meta/git/sanitized-snapshot.bundle", b"GITBUNDLE\n")
  90. write_file(
  91. root,
  92. "meta/git/sanitized-snapshot-status.json",
  93. json.dumps({"requested": True, "status": "pass"}).encode("utf-8"),
  94. )
  95. old = os.environ.pop(git_mode.ENV_GIT_MODE, None)
  96. try:
  97. self.assertEqual(git_mode.detect_git_mode(root), git_mode.SNAPSHOT)
  98. finally:
  99. if old is not None:
  100. os.environ[git_mode.ENV_GIT_MODE] = old
  101. def test_require_live_git_skips_in_detached(self) -> None:
  102. git_mode = load_git_mode()
  103. class Probe(unittest.TestCase):
  104. def runTest(self) -> None: # pragma: no cover - not executed as suite
  105. return None
  106. with tempfile.TemporaryDirectory() as tmp:
  107. root = Path(tmp)
  108. write_file(root, "README", b"x\n")
  109. old = os.environ.pop(git_mode.ENV_GIT_MODE, None)
  110. try:
  111. probe = Probe()
  112. with self.assertRaises(unittest.SkipTest) as raised:
  113. git_mode.require_live_git(root, probe)
  114. self.assertEqual(
  115. str(raised.exception),
  116. git_mode.NOT_APPLICABLE_BY_PACKAGE_POLICY,
  117. )
  118. self.assertEqual(
  119. git_mode.live_only_status(root),
  120. git_mode.NOT_APPLICABLE_BY_PACKAGE_POLICY,
  121. )
  122. finally:
  123. if old is not None:
  124. os.environ[git_mode.ENV_GIT_MODE] = old
  125. class SanitizedSnapshotTests(unittest.TestCase):
  126. def _init_repo(self, repo: Path) -> str:
  127. git = shutil.which("git")
  128. if not git:
  129. self.skipTest("Git is required")
  130. repo.mkdir(parents=True, exist_ok=True)
  131. subprocess.run([git, "init", "-q", str(repo)], check=True)
  132. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  133. subprocess.run(
  134. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  135. check=True,
  136. )
  137. write_file(repo, "src/core.v", b"module core; endmodule\n")
  138. write_file(repo, "receipts/final.json", b'{"status":"pass"}\n')
  139. write_file(repo, "reference/original/board/main.brd", b"BOARD")
  140. write_file(repo, "secret.pdf", b"%PDF-secret")
  141. subprocess.run(
  142. [git, "-C", str(repo), "add", "src/core.v", "receipts/final.json", "secret.pdf"],
  143. check=True,
  144. )
  145. # Keep heavy original untracked or tracked — either way snapshot filter drops it.
  146. subprocess.run([git, "-C", str(repo), "add", "-f", "reference/original/board/main.brd"], check=False)
  147. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  148. return git
  149. def test_sanitized_snapshot_maps_synthetic_to_original(self) -> None:
  150. handoff = load_handoff()
  151. with tempfile.TemporaryDirectory() as tmp:
  152. temp = Path(tmp)
  153. repo = temp / "repo"
  154. git = self._init_repo(repo)
  155. original = subprocess.check_output(
  156. [git, "-C", str(repo), "rev-parse", "HEAD"], text=True
  157. ).strip()
  158. status, artifacts = handoff.create_sanitized_git_snapshot(
  159. repo,
  160. git=git,
  161. original_head=original,
  162. temp_root=temp / "snap",
  163. meta_prefix="meta/git",
  164. )
  165. self.assertEqual(status["status"], "pass")
  166. self.assertFalse(status["impersonates_original_tip"])
  167. self.assertEqual(status["original_commit"], original)
  168. self.assertNotEqual(status["synthetic_commit"], original)
  169. self.assertIn("meta/git/sanitized-snapshot.bundle", artifacts)
  170. mapping = json.loads(
  171. artifacts["meta/git/sanitized-snapshot-mapping.json"].decode("utf-8")
  172. )
  173. self.assertEqual(mapping["original_commit"], original)
  174. self.assertEqual(mapping["synthetic_commit"], status["synthetic_commit"])
  175. self.assertFalse(mapping["impersonates_original_tip"])
  176. files = set(mapping["files"])
  177. self.assertIn("src/core.v", files)
  178. self.assertNotIn("secret.pdf", files)
  179. self.assertNotIn("reference/original/board/main.brd", files)
  180. def test_collect_review_provenance_wires_snapshot_flag(self) -> None:
  181. handoff = load_handoff()
  182. with tempfile.TemporaryDirectory() as tmp:
  183. temp = Path(tmp)
  184. repo = temp / "repo"
  185. self._init_repo(repo)
  186. provenance, artifacts = handoff.collect_review_git_provenance(
  187. repo,
  188. include_sanitized_git_snapshot=True,
  189. meta_prefix="meta/git",
  190. temp_root=temp / "prov",
  191. )
  192. snap = provenance["sanitized_git_snapshot"]
  193. self.assertTrue(snap["requested"])
  194. self.assertEqual(snap["status"], "pass")
  195. self.assertIn("meta/git/sanitized-snapshot.bundle", artifacts)
  196. self.assertIn("meta/git/sanitized-snapshot-mapping.json", artifacts)
  197. class FourStateReplayTests(unittest.TestCase):
  198. def _init_repo(self, repo: Path) -> None:
  199. git = shutil.which("git")
  200. if not git:
  201. self.skipTest("Git is required")
  202. repo.mkdir(parents=True, exist_ok=True)
  203. subprocess.run([git, "init", "-q", str(repo)], check=True)
  204. subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
  205. subprocess.run(
  206. [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
  207. check=True,
  208. )
  209. write_file(repo, "src/core.v", b"module core; endmodule\n")
  210. write_file(repo, "receipts/final.json", b'{"status":"pass"}\n')
  211. write_file(
  212. repo,
  213. "projects/prod2u-door-temp/project.json",
  214. b'{"name":"prod2u-door-temp"}\n',
  215. )
  216. subprocess.run(
  217. [
  218. git,
  219. "-C",
  220. str(repo),
  221. "add",
  222. "src/core.v",
  223. "receipts/final.json",
  224. "projects/prod2u-door-temp/project.json",
  225. ],
  226. check=True,
  227. )
  228. subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
  229. def test_four_state_replay_statuses(self) -> None:
  230. analyzer = load_analyzer()
  231. replay = load_replay()
  232. with tempfile.TemporaryDirectory() as tmp:
  233. temp = Path(tmp)
  234. repo = temp / "repo"
  235. self._init_repo(repo)
  236. generated = temp / "generated"
  237. for name, data in (
  238. ("board-data.json", b'{"ok":true}\n'),
  239. ("build-info.json", b'{"ok":true}\n'),
  240. ("import-report.json", b'{"ok":true}\n'),
  241. ("board-copper.svg", b"<svg/>\n"),
  242. ("board-silkscreen.svg", b"<svg/>\n"),
  243. ("board-mask-edge.svg", b"<svg/>\n"),
  244. ("board-copper-back.svg", b"<svg/>\n"),
  245. ("board-silkscreen-back.svg", b"<svg/>\n"),
  246. ("board-mask-edge-back.svg", b"<svg/>\n"),
  247. ):
  248. write_file(generated, name, data)
  249. config = analyzer.HandoffConfig(
  250. max_zip_bytes=5_000_000,
  251. target_zip_bytes=4_000_000,
  252. external_sources=(
  253. analyzer.ExternalSource(
  254. id="board-viewer-generated",
  255. category="hardware",
  256. kind="directory",
  257. path_candidates=(generated,),
  258. archive_policy="copy",
  259. ),
  260. ),
  261. extra_exclusions=(),
  262. )
  263. collection = analyzer.collect_analysis_inputs(
  264. repo_root=repo,
  265. config=config,
  266. temp_root=temp / "run",
  267. include_git_bundle=False,
  268. profile="review-compact",
  269. package_name="p2-replay-smoke",
  270. )
  271. result = analyzer.create_analysis_package(
  272. collection=collection,
  273. output_root=temp / "output",
  274. package_name="p2-replay-smoke",
  275. max_zip_bytes=5_000_000,
  276. target_zip_bytes=4_000_000,
  277. force=False,
  278. profile="review-compact",
  279. )
  280. package_dir = Path(result["output_dir"])
  281. report = replay.replay_review_compact(
  282. package_dir,
  283. extract_root=temp / "extract",
  284. skip_software=False,
  285. )
  286. self.assertEqual(report["package_content_replay"], "pass")
  287. self.assertEqual(
  288. report["reference_regeneration_replay"],
  289. "not_packaged_by_policy",
  290. )
  291. self.assertEqual(report["hardware_validation"], "not_run")
  292. self.assertIn(report["detached_software_replay"], {"pass", "fail"})
  293. # Compact extract must be Git-optional (no raw .git).
  294. cpld = Path(report["cpld_root"])
  295. self.assertFalse((cpld / ".git").exists())
  296. self.assertFalse((cpld / "source" / ".git").exists())
  297. self.assertEqual(
  298. report["detached_software"]["git_mode"] in {"detached", "snapshot"},
  299. True,
  300. )
  301. # Layout + provenance should pass even if unit modules are absent in fixture.
  302. self.assertEqual(report["detached_software"]["layout"]["status"], "pass")
  303. self.assertEqual(report["detached_software"]["provenance"]["status"], "pass")
  304. # Missing required unit modules must fail-close (not skipped_missing + pass).
  305. self.assertEqual(report["detached_software"]["status"], "fail")
  306. self.assertEqual(report["detached_software_replay"], "fail")
  307. self.assertFalse(report["detached_software"].get("unit_exact_set"))
  308. unit_statuses = [
  309. str(row.get("status") or "")
  310. for row in report["detached_software"]["unit"].get("modules") or []
  311. ]
  312. self.assertTrue(
  313. any(st == "fail_missing" for st in unit_statuses),
  314. unit_statuses,
  315. )
  316. self.assertRegex(str(report.get("replay_semantic_sha256") or ""), r"^[0-9a-f]{64}$")
  317. self.assertIsInstance(report.get("replay_semantic"), dict)
  318. self.assertEqual(report["status"], "fail")
  319. self.assertEqual(
  320. report["detached_software"]["part_statuses"]["unit"],
  321. report["detached_software"]["unit"]["status"],
  322. )
  323. self.assertEqual(
  324. report["detached_software"]["part_statuses"]["board"],
  325. report["detached_software"]["board"]["status"],
  326. )
  327. # Content replay API also exposes four-state skeleton.
  328. content = report["package_content"]
  329. self.assertEqual(content["package_content_replay"], "pass")
  330. self.assertEqual(content["reference_regeneration_replay"], "not_packaged_by_policy")
  331. self.assertEqual(content["hardware_validation"], "not_run")
  332. zips = list(package_dir.glob("*.zip"))
  333. self.assertTrue(zips)
  334. self.assertEqual(report["actual_zip_basename"], zips[0].name)
  335. self.assertEqual(report["package_sha256"], analyzer.handoff.sha256_file(zips[0]))
  336. self.assertEqual(report["package_size"], zips[0].stat().st_size)
  337. self.assertEqual(report["package_stage"], "final-review")
  338. def test_replay_analysis_package_four_state_skeleton(self) -> None:
  339. analyzer = load_analyzer()
  340. with tempfile.TemporaryDirectory() as tmp:
  341. temp = Path(tmp)
  342. package_dir = temp / "pkg"
  343. package_dir.mkdir()
  344. # Minimal hand-built package for content replay only.
  345. payload = {
  346. "schema": "cpld-agent-analysis-handoff-index-v1",
  347. "profile": "review-compact",
  348. "files": [
  349. {
  350. "path": "source/src/core.v",
  351. "sha256": "",
  352. "size": 0,
  353. }
  354. ],
  355. "content_dedup": [],
  356. "derived_evidence": [],
  357. }
  358. core = b"module core; endmodule\n"
  359. import hashlib
  360. digest = hashlib.sha256(core).hexdigest()
  361. payload["files"][0]["sha256"] = digest
  362. payload["files"][0]["size"] = len(core)
  363. (package_dir / "HANDOFF-INDEX.json").write_text(
  364. json.dumps(payload), encoding="utf-8"
  365. )
  366. (package_dir / "EXCLUSIONS.txt").write_text("none\n", encoding="utf-8")
  367. zip_path = package_dir / "volume.zip"
  368. with zipfile.ZipFile(zip_path, "w") as archive:
  369. archive.writestr("CPLD/source/src/core.v", core)
  370. (package_dir / "SHA256SUMS.txt").write_text(
  371. f"{analyzer.handoff.sha256_file(zip_path)} volume.zip\n",
  372. encoding="ascii",
  373. )
  374. report = analyzer.replay_analysis_package(
  375. package_dir, extract_root=temp / "replay"
  376. )
  377. self.assertEqual(report["status"], "pass")
  378. self.assertEqual(report["package_content_replay"], "pass")
  379. self.assertEqual(report["detached_software_replay"], "not_run")
  380. self.assertEqual(report["reference_regeneration_replay"], "not_packaged_by_policy")
  381. self.assertEqual(report["hardware_validation"], "not_run")
  382. def test_board_asset_presence_fallback_fails(self) -> None:
  383. replay = load_replay()
  384. with tempfile.TemporaryDirectory() as tmp:
  385. temp = Path(tmp)
  386. cpld = temp / "CPLD"
  387. generated = cpld / "evidence" / "board-viewer"
  388. for name in (
  389. "board-data.json",
  390. "build-info.json",
  391. "import-report.json",
  392. "board-copper.svg",
  393. "board-silkscreen.svg",
  394. "board-mask-edge.svg",
  395. "board-copper-back.svg",
  396. "board-silkscreen-back.svg",
  397. "board-mask-edge-back.svg",
  398. ):
  399. write_file(generated, name, b"{}\n")
  400. replay.ROOT = temp / "no-live-tools"
  401. board = replay._board_detached_check(cpld)
  402. self.assertEqual(board["status"], "fail")
  403. self.assertEqual(board["mode"], "asset_presence")
  404. if __name__ == "__main__":
  405. unittest.main()