#!/usr/bin/env python3 """Focused tests for Lane P2 four-state replay and Git-optional modes.""" from __future__ import annotations import importlib.util import json import os import shutil import subprocess import sys import tempfile import unittest import zipfile from pathlib import Path from types import ModuleType ROOT = Path(__file__).resolve().parents[2] TOOLS = ROOT / "tools" ANALYZER_PATH = ROOT / "package_for_agent_analysis.py" def write_file(root: Path, relative: str, data: bytes = b"fixture\n") -> Path: path = root / Path(relative) path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(data) return path def load_module(path: Path, name: str) -> ModuleType: spec = importlib.util.spec_from_file_location(name, path) assert spec is not None and spec.loader is not None module = importlib.util.module_from_spec(spec) sys.modules[name] = module spec.loader.exec_module(module) return module def load_analyzer() -> ModuleType: return load_module(ANALYZER_PATH, "package_for_agent_analysis_p2") def load_handoff() -> ModuleType: sys.path.insert(0, str(TOOLS)) return load_module(TOOLS / "package_agent_handoff.py", "package_agent_handoff_p2") def load_git_mode() -> ModuleType: sys.path.insert(0, str(TOOLS)) return load_module(TOOLS / "git_worktree_mode.py", "git_worktree_mode_p2") def load_replay() -> ModuleType: sys.path.insert(0, str(TOOLS)) return load_module(TOOLS / "replay_review_compact.py", "replay_review_compact_p2") class GitWorktreeModeTests(unittest.TestCase): def test_detect_live_git_on_repo_root(self) -> None: """Construct a real live Git fixture — do not assume arbitrary ROOT is live.""" git_mode = load_git_mode() git = shutil.which("git") if not git: self.skipTest("Git is required") old = os.environ.pop(git_mode.ENV_GIT_MODE, None) try: with tempfile.TemporaryDirectory() as tmp: repo = Path(tmp) / "live-repo" repo.mkdir() subprocess.run([git, "init", "-q", str(repo)], check=True) subprocess.run( [git, "-C", str(repo), "config", "user.name", "Test"], check=True ) subprocess.run( [git, "-C", str(repo), "config", "user.email", "t@example.invalid"], check=True, ) write_file(repo, "tracked.txt", b"live\n") subprocess.run([git, "-C", str(repo), "add", "tracked.txt"], check=True) subprocess.run( [git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True ) mode = git_mode.detect_git_mode(repo) self.assertEqual(mode, git_mode.LIVE_GIT) self.assertEqual(git_mode.live_only_status(repo), "pass") finally: if old is not None: os.environ[git_mode.ENV_GIT_MODE] = old def test_detached_without_raw_git(self) -> None: git_mode = load_git_mode() with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) / "extract" write_file(root, "source/src/core.v", b"module core; endmodule\n") write_file(root, "meta/git/HEAD.txt", b"deadbeef\n") old = os.environ.pop(git_mode.ENV_GIT_MODE, None) try: self.assertEqual(git_mode.detect_git_mode(root), git_mode.DETACHED) self.assertTrue(git_mode.git_optional_ok(root)) finally: if old is not None: os.environ[git_mode.ENV_GIT_MODE] = old def test_snapshot_mode_when_bundle_present(self) -> None: git_mode = load_git_mode() with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) / "extract" write_file(root, "meta/git/sanitized-snapshot.bundle", b"GITBUNDLE\n") write_file( root, "meta/git/sanitized-snapshot-status.json", json.dumps({"requested": True, "status": "pass"}).encode("utf-8"), ) old = os.environ.pop(git_mode.ENV_GIT_MODE, None) try: self.assertEqual(git_mode.detect_git_mode(root), git_mode.SNAPSHOT) finally: if old is not None: os.environ[git_mode.ENV_GIT_MODE] = old def test_require_live_git_skips_in_detached(self) -> None: git_mode = load_git_mode() class Probe(unittest.TestCase): def runTest(self) -> None: # pragma: no cover - not executed as suite return None with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) write_file(root, "README", b"x\n") old = os.environ.pop(git_mode.ENV_GIT_MODE, None) try: probe = Probe() with self.assertRaises(unittest.SkipTest) as raised: git_mode.require_live_git(root, probe) self.assertEqual( str(raised.exception), git_mode.NOT_APPLICABLE_BY_PACKAGE_POLICY, ) self.assertEqual( git_mode.live_only_status(root), git_mode.NOT_APPLICABLE_BY_PACKAGE_POLICY, ) finally: if old is not None: os.environ[git_mode.ENV_GIT_MODE] = old class SanitizedSnapshotTests(unittest.TestCase): def _init_repo(self, repo: Path) -> str: git = shutil.which("git") if not git: self.skipTest("Git is required") repo.mkdir(parents=True, exist_ok=True) subprocess.run([git, "init", "-q", str(repo)], check=True) subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True) subprocess.run( [git, "-C", str(repo), "config", "user.email", "test@example.invalid"], check=True, ) write_file(repo, "src/core.v", b"module core; endmodule\n") write_file(repo, "receipts/final.json", b'{"status":"pass"}\n') write_file(repo, "reference/original/board/main.brd", b"BOARD") write_file(repo, "secret.pdf", b"%PDF-secret") subprocess.run( [git, "-C", str(repo), "add", "src/core.v", "receipts/final.json", "secret.pdf"], check=True, ) # Keep heavy original untracked or tracked — either way snapshot filter drops it. subprocess.run([git, "-C", str(repo), "add", "-f", "reference/original/board/main.brd"], check=False) subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True) return git def test_sanitized_snapshot_maps_synthetic_to_original(self) -> None: handoff = load_handoff() with tempfile.TemporaryDirectory() as tmp: temp = Path(tmp) repo = temp / "repo" git = self._init_repo(repo) original = subprocess.check_output( [git, "-C", str(repo), "rev-parse", "HEAD"], text=True ).strip() status, artifacts = handoff.create_sanitized_git_snapshot( repo, git=git, original_head=original, temp_root=temp / "snap", meta_prefix="meta/git", ) self.assertEqual(status["status"], "pass") self.assertFalse(status["impersonates_original_tip"]) self.assertEqual(status["original_commit"], original) self.assertNotEqual(status["synthetic_commit"], original) self.assertIn("meta/git/sanitized-snapshot.bundle", artifacts) mapping = json.loads( artifacts["meta/git/sanitized-snapshot-mapping.json"].decode("utf-8") ) self.assertEqual(mapping["original_commit"], original) self.assertEqual(mapping["synthetic_commit"], status["synthetic_commit"]) self.assertFalse(mapping["impersonates_original_tip"]) files = set(mapping["files"]) self.assertIn("src/core.v", files) self.assertNotIn("secret.pdf", files) self.assertNotIn("reference/original/board/main.brd", files) def test_collect_review_provenance_wires_snapshot_flag(self) -> None: handoff = load_handoff() with tempfile.TemporaryDirectory() as tmp: temp = Path(tmp) repo = temp / "repo" self._init_repo(repo) provenance, artifacts = handoff.collect_review_git_provenance( repo, include_sanitized_git_snapshot=True, meta_prefix="meta/git", temp_root=temp / "prov", ) snap = provenance["sanitized_git_snapshot"] self.assertTrue(snap["requested"]) self.assertEqual(snap["status"], "pass") self.assertIn("meta/git/sanitized-snapshot.bundle", artifacts) self.assertIn("meta/git/sanitized-snapshot-mapping.json", artifacts) class FourStateReplayTests(unittest.TestCase): def _init_repo(self, repo: Path) -> None: git = shutil.which("git") if not git: self.skipTest("Git is required") repo.mkdir(parents=True, exist_ok=True) subprocess.run([git, "init", "-q", str(repo)], check=True) subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True) subprocess.run( [git, "-C", str(repo), "config", "user.email", "test@example.invalid"], check=True, ) write_file(repo, "src/core.v", b"module core; endmodule\n") write_file(repo, "receipts/final.json", b'{"status":"pass"}\n') write_file( repo, "projects/prod2u-door-temp/project.json", b'{"name":"prod2u-door-temp"}\n', ) subprocess.run( [ git, "-C", str(repo), "add", "src/core.v", "receipts/final.json", "projects/prod2u-door-temp/project.json", ], check=True, ) subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True) def test_four_state_replay_statuses(self) -> None: analyzer = load_analyzer() replay = load_replay() with tempfile.TemporaryDirectory() as tmp: temp = Path(tmp) repo = temp / "repo" self._init_repo(repo) generated = temp / "generated" for name, data in ( ("board-data.json", b'{"ok":true}\n'), ("build-info.json", b'{"ok":true}\n'), ("import-report.json", b'{"ok":true}\n'), ("board-copper.svg", b"\n"), ("board-silkscreen.svg", b"\n"), ("board-mask-edge.svg", b"\n"), ("board-copper-back.svg", b"\n"), ("board-silkscreen-back.svg", b"\n"), ("board-mask-edge-back.svg", b"\n"), ): write_file(generated, name, data) config = analyzer.HandoffConfig( max_zip_bytes=5_000_000, target_zip_bytes=4_000_000, external_sources=( analyzer.ExternalSource( id="board-viewer-generated", category="hardware", kind="directory", path_candidates=(generated,), archive_policy="copy", ), ), extra_exclusions=(), ) collection = analyzer.collect_analysis_inputs( repo_root=repo, config=config, temp_root=temp / "run", include_git_bundle=False, profile="review-compact", package_name="p2-replay-smoke", ) result = analyzer.create_analysis_package( collection=collection, output_root=temp / "output", package_name="p2-replay-smoke", max_zip_bytes=5_000_000, target_zip_bytes=4_000_000, force=False, profile="review-compact", ) package_dir = Path(result["output_dir"]) report = replay.replay_review_compact( package_dir, extract_root=temp / "extract", skip_software=False, ) self.assertEqual(report["package_content_replay"], "pass") self.assertEqual( report["reference_regeneration_replay"], "not_packaged_by_policy", ) self.assertEqual(report["hardware_validation"], "not_run") self.assertIn(report["detached_software_replay"], {"pass", "fail"}) # Compact extract must be Git-optional (no raw .git). cpld = Path(report["cpld_root"]) self.assertFalse((cpld / ".git").exists()) self.assertFalse((cpld / "source" / ".git").exists()) self.assertEqual( report["detached_software"]["git_mode"] in {"detached", "snapshot"}, True, ) # Layout + provenance should pass even if unit modules are absent in fixture. self.assertEqual(report["detached_software"]["layout"]["status"], "pass") self.assertEqual(report["detached_software"]["provenance"]["status"], "pass") # Missing required unit modules must fail-close (not skipped_missing + pass). self.assertEqual(report["detached_software"]["status"], "fail") self.assertEqual(report["detached_software_replay"], "fail") self.assertFalse(report["detached_software"].get("unit_exact_set")) unit_statuses = [ str(row.get("status") or "") for row in report["detached_software"]["unit"].get("modules") or [] ] self.assertTrue( any(st == "fail_missing" for st in unit_statuses), unit_statuses, ) self.assertRegex(str(report.get("replay_semantic_sha256") or ""), r"^[0-9a-f]{64}$") self.assertIsInstance(report.get("replay_semantic"), dict) self.assertEqual(report["status"], "fail") self.assertEqual( report["detached_software"]["part_statuses"]["unit"], report["detached_software"]["unit"]["status"], ) self.assertEqual( report["detached_software"]["part_statuses"]["board"], report["detached_software"]["board"]["status"], ) # Content replay API also exposes four-state skeleton. content = report["package_content"] self.assertEqual(content["package_content_replay"], "pass") self.assertEqual(content["reference_regeneration_replay"], "not_packaged_by_policy") self.assertEqual(content["hardware_validation"], "not_run") zips = list(package_dir.glob("*.zip")) self.assertTrue(zips) self.assertEqual(report["actual_zip_basename"], zips[0].name) self.assertEqual(report["package_sha256"], analyzer.handoff.sha256_file(zips[0])) self.assertEqual(report["package_size"], zips[0].stat().st_size) self.assertEqual(report["package_stage"], "final-review") def test_replay_analysis_package_four_state_skeleton(self) -> None: analyzer = load_analyzer() with tempfile.TemporaryDirectory() as tmp: temp = Path(tmp) package_dir = temp / "pkg" package_dir.mkdir() # Minimal hand-built package for content replay only. payload = { "schema": "cpld-agent-analysis-handoff-index-v1", "profile": "review-compact", "files": [ { "path": "source/src/core.v", "sha256": "", "size": 0, } ], "content_dedup": [], "derived_evidence": [], } core = b"module core; endmodule\n" import hashlib digest = hashlib.sha256(core).hexdigest() payload["files"][0]["sha256"] = digest payload["files"][0]["size"] = len(core) (package_dir / "HANDOFF-INDEX.json").write_text( json.dumps(payload), encoding="utf-8" ) (package_dir / "EXCLUSIONS.txt").write_text("none\n", encoding="utf-8") zip_path = package_dir / "volume.zip" with zipfile.ZipFile(zip_path, "w") as archive: archive.writestr("CPLD/source/src/core.v", core) (package_dir / "SHA256SUMS.txt").write_text( f"{analyzer.handoff.sha256_file(zip_path)} volume.zip\n", encoding="ascii", ) report = analyzer.replay_analysis_package( package_dir, extract_root=temp / "replay" ) self.assertEqual(report["status"], "pass") self.assertEqual(report["package_content_replay"], "pass") self.assertEqual(report["detached_software_replay"], "not_run") self.assertEqual(report["reference_regeneration_replay"], "not_packaged_by_policy") self.assertEqual(report["hardware_validation"], "not_run") def test_board_asset_presence_fallback_fails(self) -> None: replay = load_replay() with tempfile.TemporaryDirectory() as tmp: temp = Path(tmp) cpld = temp / "CPLD" generated = cpld / "evidence" / "board-viewer" for name in ( "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", ): write_file(generated, name, b"{}\n") replay.ROOT = temp / "no-live-tools" board = replay._board_detached_check(cpld) self.assertEqual(board["status"], "fail") self.assertEqual(board["mode"], "asset_presence") if __name__ == "__main__": unittest.main()