Просмотр исходного кода

feat(replay): add four-state compact replay and sanitized git snapshot

Enable Git-optional detached/snapshot modes for review-compact packages while
keeping live_git commit-compare paths strict, and wire synthetic→original
snapshot mapping without impersonating the tip.

Co-authored-by: Cursor <cursoragent@cursor.com>
root 3 месяцев назад
Родитель
Сommit
0a0fdb3f4d

+ 2 - 1
PACKAGE_FOR_AGENT_ANALYSIS.README.zh-CN.md

@@ -38,9 +38,10 @@ tools/package-review-compact.sh
 
 
 可选:
 可选:
 
 
-- `--include-sanitized-git-snapshot`:预留 P2 合成单 commit 快照钩子(当前写入 `meta/git/sanitized-snapshot-status.json`,不冒充原始 tip)
+- `--include-sanitized-git-snapshot`:可选合成单 commit 快照(`meta/git/sanitized-snapshot.bundle` + mapping;明确 synthetic→original,不冒充原始 tip)
 - `--audit-only`:只扫描不写 ZIP
 - `--audit-only`:只扫描不写 ZIP
 - `--explain PATH`:解释某路径是否收入
 - `--explain PATH`:解释某路径是否收入
+- 四分态回放:`tools/replay-review-compact.sh <package-dir>`(或 `tools/replay_review_compact.py`);仅解压校验用 `tools/extract-review-compact.sh`
 
 
 ## 收入与排除(review-*)
 ## 收入与排除(review-*)
 
 

+ 20 - 2
package_for_agent_analysis.py

@@ -1013,6 +1013,7 @@ def collect_analysis_inputs(
             root,
             root,
             include_sanitized_git_snapshot=include_sanitized_git_snapshot,
             include_sanitized_git_snapshot=include_sanitized_git_snapshot,
             meta_prefix="meta/git",
             meta_prefix="meta/git",
+            temp_root=temp_root / "sanitized-git",
         )
         )
         binding = handoff.build_td_source_closure_binding_hook(root)
         binding = handoff.build_td_source_closure_binding_hook(root)
         provenance_artifacts["meta/td-source-closure-binding.json"] = handoff.json_bytes(binding)
         provenance_artifacts["meta/td-source-closure-binding.json"] = handoff.json_bytes(binding)
@@ -1676,7 +1677,14 @@ def classify_derived_evidence(items: tuple[PackageItem, ...]) -> list[dict[str,
 
 
 
 
 def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[str, object]:
 def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[str, object]:
-    """Extract a published package and verify SHA256SUMS plus inventory hashes."""
+    """Extract a published package and verify SHA256SUMS plus inventory hashes.
+
+    Returns package-content verification plus the four-state replay skeleton:
+    ``package_content_replay``, ``detached_software_replay`` (not_run here),
+    ``reference_regeneration_replay=not_packaged_by_policy``,
+    ``hardware_validation=not_run``. Full detached software orchestration lives in
+    ``tools/replay_review_compact.py``.
+    """
     package_dir = package_dir.expanduser().resolve(strict=True)
     package_dir = package_dir.expanduser().resolve(strict=True)
     extract_root = extract_root.expanduser().resolve(strict=False)
     extract_root = extract_root.expanduser().resolve(strict=False)
     if extract_root.exists():
     if extract_root.exists():
@@ -1752,11 +1760,13 @@ def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[st
             alias_path = zip_extract_root / "CPLD" / Path(*str(alias).split("/"))
             alias_path = zip_extract_root / "CPLD" / Path(*str(alias).split("/"))
             if alias_path.exists():
             if alias_path.exists():
                 raise PackagingError(f"replay found duplicated physical alias path: {alias}")
                 raise PackagingError(f"replay found duplicated physical alias path: {alias}")
+    cpld_root = zip_extract_root / "CPLD"
     return {
     return {
         "status": "pass",
         "status": "pass",
         "mode": "package_replay",
         "mode": "package_replay",
         "package_dir": str(package_dir),
         "package_dir": str(package_dir),
         "extract_root": str(extract_root),
         "extract_root": str(extract_root),
+        "cpld_root": str(cpld_root) if cpld_root.is_dir() else None,
         "volumes": verified_volumes,
         "volumes": verified_volumes,
         "sidecars": verified_sidecars,
         "sidecars": verified_sidecars,
         "exclusions_present": exclusions_path.is_file(),
         "exclusions_present": exclusions_path.is_file(),
@@ -1764,6 +1774,11 @@ def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[st
         "checked_files": checked_files,
         "checked_files": checked_files,
         "content_dedup_groups": len(index.get("content_dedup", [])),
         "content_dedup_groups": len(index.get("content_dedup", [])),
         "derived_evidence_count": len(index.get("derived_evidence", [])),
         "derived_evidence_count": len(index.get("derived_evidence", [])),
+        # Four-state skeleton (content only; software lane filled by replay_review_compact).
+        "package_content_replay": "pass",
+        "detached_software_replay": "not_run",
+        "reference_regeneration_replay": "not_packaged_by_policy",
+        "hardware_validation": "not_run",
     }
     }
 
 
 
 
@@ -2803,7 +2818,10 @@ def build_parser() -> argparse.ArgumentParser:
     parser.add_argument(
     parser.add_argument(
         "--include-sanitized-git-snapshot",
         "--include-sanitized-git-snapshot",
         action="store_true",
         action="store_true",
-        help="request sanitized synthetic git snapshot hook (P2 extension; records reserved status)",
+        help=(
+            "include sanitized synthetic single-commit git snapshot under meta/git "
+            "(records synthetic→original mapping; does not impersonate the original tip)"
+        ),
     )
     )
     parser.add_argument(
     parser.add_argument(
         "--profile",
         "--profile",

+ 5 - 0
tests/unit/test_build_firmware_package.py

@@ -246,6 +246,11 @@ class BuildFirmwarePackageTests(unittest.TestCase):
         self.assertEqual(comparison["production_changed_paths"], [])
         self.assertEqual(comparison["production_changed_paths"], [])
 
 
     def test_source_closure_live_commit_compare(self) -> None:
     def test_source_closure_live_commit_compare(self) -> None:
+        # live_git remains strict; compact/detached hosts skip instead of hard-failing.
+        sys.path.insert(0, str(ROOT / "tools"))
+        from git_worktree_mode import require_live_git  # noqa: WPS433
+
+        require_live_git(ROOT, self)
         head = subprocess.check_output(
         head = subprocess.check_output(
             ["git", "-C", str(ROOT), "rev-parse", "HEAD"],
             ["git", "-C", str(ROOT), "rev-parse", "HEAD"],
             text=True,
             text=True,

+ 357 - 0
tests/unit/test_replay_review_compact.py

@@ -0,0 +1,357 @@
+#!/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:
+        git_mode = load_git_mode()
+        # Clear override for this assertion.
+        old = os.environ.pop(git_mode.ENV_GIT_MODE, None)
+        try:
+            mode = git_mode.detect_git_mode(ROOT)
+            self.assertEqual(mode, git_mode.LIVE_GIT)
+        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):
+                    git_mode.require_live_git(root, probe)
+            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"<svg/>\n"),
+                ("board-silkscreen.svg", b"<svg/>\n"),
+                ("board-mask-edge.svg", b"<svg/>\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")
+            # 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")
+
+    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")
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 19 - 0
tools/extract-review-compact.sh

@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+# Thin entrypoint: extract + package_content_replay only (no software lane).
+set -euo pipefail
+unset LD_LIBRARY_PATH LD_PRELOAD QT_PLUGIN_PATH || true
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+VENV="${PRODU2_VERIFY_VENV:-${XDG_CACHE_HOME:-$HOME/.cache}/prod2u/venvs/verify}"
+PY="${VENV}/bin/python"
+[[ -x "$PY" ]] || PY=python3
+if [[ $# -lt 1 ]]; then
+  echo "usage: $0 <package-dir> [extract-dir]" >&2
+  exit 2
+fi
+PACKAGE_DIR="$1"
+EXTRACT_DIR="${2:-}"
+ARGS=(--package-dir "$PACKAGE_DIR" --skip-software)
+if [[ -n "$EXTRACT_DIR" ]]; then
+  ARGS+=(--extract-dir "$EXTRACT_DIR")
+fi
+exec "$PY" -B "$ROOT/tools/replay_review_compact.py" "${ARGS[@]}"

+ 197 - 0
tools/git_worktree_mode.py

@@ -0,0 +1,197 @@
+#!/usr/bin/env python3
+"""Detect live_git vs snapshot vs detached review modes.
+
+Compact packages do not ship raw ``.git``. Tests and replay entrypoints must
+distinguish:
+
+- ``live_git``: resolvable raw ``.git`` (strict commit-compare paths OK)
+- ``snapshot``: sanitized synthetic single-commit snapshot present (no raw ``.git``)
+- ``detached``: extracted package / copy without raw ``.git`` or snapshot
+
+Override with ``PRODU2_GIT_MODE`` when intentionally forcing a mode.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any
+
+
+LIVE_GIT = "live_git"
+SNAPSHOT = "snapshot"
+DETACHED = "detached"
+GIT_MODES = frozenset({LIVE_GIT, SNAPSHOT, DETACHED})
+
+ENV_GIT_MODE = "PRODU2_GIT_MODE"
+
+
+def _tools_dir() -> Path:
+    return Path(__file__).resolve().parent
+
+
+def _load_handoff():
+    tools = _tools_dir()
+    if str(tools) not in sys.path:
+        sys.path.insert(0, str(tools))
+    import package_agent_handoff as handoff  # noqa: WPS433
+
+    return handoff
+
+
+def _read_json(path: Path) -> dict[str, Any] | None:
+    if not path.is_file():
+        return None
+    try:
+        payload = json.loads(path.read_text(encoding="utf-8"))
+    except (OSError, UnicodeError, json.JSONDecodeError):
+        return None
+    return payload if isinstance(payload, dict) else None
+
+
+def find_meta_git_dir(root: Path) -> Path | None:
+    """Locate ``meta/git`` under a repo root or extracted CPLD tree."""
+    candidates = (
+        root / "meta" / "git",
+        root / "CPLD" / "meta" / "git",
+    )
+    for path in candidates:
+        if path.is_dir():
+            return path
+    return None
+
+
+def snapshot_present(root: Path) -> bool:
+    meta_git = find_meta_git_dir(root)
+    if meta_git is None:
+        return False
+    bundle = meta_git / "sanitized-snapshot.bundle"
+    status = _read_json(meta_git / "sanitized-snapshot-status.json")
+    if bundle.is_file():
+        return True
+    if status and status.get("status") == "pass" and status.get("requested") is True:
+        return True
+    return False
+
+
+def raw_git_marker_present(root: Path) -> bool:
+    """True when a raw ``.git`` file/directory marker exists (incl. linked worktrees)."""
+    marker = root / ".git"
+    try:
+        return marker.exists()
+    except OSError:
+        return False
+
+
+def live_git_usable(root: Path) -> bool:
+    """True when git treats ``root`` as an inside-work-tree checkout.
+
+    Packager ``resolve_git_dir`` intentionally rejects linked-worktree gitdirs that
+    point outside the tree (security). Mode detection still treats those as
+    ``live_git`` so commit-compare tests stay strict on real checkouts.
+    """
+    if not raw_git_marker_present(root):
+        return False
+    git = shutil.which("git")
+    if not git:
+        # Marker present but tool missing: still classify as live_git for policy.
+        return True
+    try:
+        completed = subprocess.run(
+            [git, "-C", str(root), "rev-parse", "--is-inside-work-tree"],
+            stdout=subprocess.PIPE,
+            stderr=subprocess.DEVNULL,
+            text=True,
+            check=False,
+        )
+    except OSError:
+        return True
+    return completed.returncode == 0 and completed.stdout.strip() == "true"
+
+
+def detect_git_mode(root: Path | None = None) -> str:
+    """Return ``live_git``, ``snapshot``, or ``detached`` for ``root``."""
+    override = os.environ.get(ENV_GIT_MODE, "").strip().casefold()
+    if override:
+        if override not in GIT_MODES:
+            raise ValueError(
+                f"invalid {ENV_GIT_MODE}={override!r}; expected one of "
+                f"{sorted(GIT_MODES)}"
+            )
+        return override
+
+    base = (root or Path.cwd()).expanduser().resolve(strict=False)
+    if live_git_usable(base):
+        return LIVE_GIT
+    if snapshot_present(base):
+        return SNAPSHOT
+    return DETACHED
+
+
+def require_live_git(root: Path, testcase: Any | None = None) -> str:
+    """Assert or skip unless ``root`` is in ``live_git`` mode.
+
+    When ``testcase`` is a unittest.TestCase, skips instead of raising so
+    compact/detached replay hosts stay green. Live worktrees remain strict.
+    """
+    mode = detect_git_mode(root)
+    if mode == LIVE_GIT:
+        return mode
+    message = (
+        f"requires live_git (raw .git); current mode={mode} under {root}. "
+        "Compact/detached packages are Git-optional by policy."
+    )
+    if testcase is not None and hasattr(testcase, "skipTest"):
+        testcase.skipTest(message)
+    raise RuntimeError(message)
+
+
+def git_optional_ok(root: Path | None = None) -> bool:
+    """True when software checks may run without raw ``.git``."""
+    return detect_git_mode(root) in {SNAPSHOT, DETACHED, LIVE_GIT}
+
+
+def describe_git_mode(root: Path | None = None) -> dict[str, Any]:
+    base = (root or Path.cwd()).expanduser().resolve(strict=False)
+    mode = detect_git_mode(base)
+    handoff = _load_handoff()
+    packager_git_dir = handoff.resolve_git_dir(base)
+    meta_git = find_meta_git_dir(base)
+    status = _read_json(meta_git / "sanitized-snapshot-status.json") if meta_git else None
+    return {
+        "schema": "cpld-git-worktree-mode-v1",
+        "root": str(base),
+        "mode": mode,
+        "raw_git_marker_present": raw_git_marker_present(base),
+        "packager_resolve_git_dir": str(packager_git_dir) if packager_git_dir else None,
+        "packager_resolve_rejects_linked_worktree": (
+            raw_git_marker_present(base) and packager_git_dir is None and mode == LIVE_GIT
+        ),
+        "meta_git_dir": str(meta_git) if meta_git is not None else None,
+        "sanitized_snapshot_present": snapshot_present(base),
+        "sanitized_snapshot_status": status,
+        "env_override": os.environ.get(ENV_GIT_MODE) or None,
+    }
+
+
+def main(argv: list[str] | None = None) -> int:
+    import argparse
+
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument(
+        "--root",
+        type=Path,
+        default=Path.cwd(),
+        help="repository or extracted CPLD root",
+    )
+    args = parser.parse_args(argv)
+    print(json.dumps(describe_git_mode(args.root), ensure_ascii=False, indent=2))
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 241 - 15
tools/package_agent_handoff.py

@@ -1317,11 +1317,211 @@ def build_td_source_closure_binding_hook(root: Path) -> dict[str, object]:
     return binding
     return binding
 
 
 
 
+_SANITIZED_SNAPSHOT_SKIP_PREFIXES = (
+    "reference/original/",
+    "node_modules/",
+    ".venv/",
+    "venv/",
+    "__pycache__/",
+    ".git/",
+    "tmp/",
+    "tools/board-viewer/node_modules/",
+)
+_SANITIZED_SNAPSHOT_SKIP_SUFFIXES = (
+    ".pdf",
+    ".brd",
+    ".dsn",
+    ".zip",
+    ".7z",
+    ".rar",
+    ".bundle",
+)
+_SANITIZED_SNAPSHOT_FIXTURE_KEEP = "tests/board_viewer/fixtures/"
+
+
+def allow_sanitized_snapshot_path(relative: str) -> bool:
+    """Filter tracked paths for the optional synthetic single-commit snapshot."""
+    rel = relative.replace("\\", "/").lstrip("./")
+    lower = rel.casefold()
+    if any(lower.startswith(prefix) for prefix in _SANITIZED_SNAPSHOT_SKIP_PREFIXES):
+        return False
+    if lower.startswith(_SANITIZED_SNAPSHOT_FIXTURE_KEEP.casefold()):
+        return True
+    if any(lower.endswith(suffix) for suffix in _SANITIZED_SNAPSHOT_SKIP_SUFFIXES):
+        return False
+    name = lower.rsplit("/", 1)[-1]
+    if name.startswith(".run_id"):
+        return False
+    return True
+
+
+def create_sanitized_git_snapshot(
+    root: Path,
+    *,
+    git: str,
+    original_head: str | None,
+    temp_root: Path,
+    meta_prefix: str = "meta/git",
+    file_rels: Iterable[str] | None = None,
+) -> tuple[dict[str, object], dict[str, bytes]]:
+    """Build a synthetic single-commit git bundle with synthetic→original mapping.
+
+    The synthetic commit must never be presented as the original tip.
+    """
+    work = temp_root / "sanitized-git-snapshot-work"
+    if work.exists():
+        shutil.rmtree(work)
+    work.mkdir(parents=True, exist_ok=True)
+    code, _ = run_capture([git, "init", "-q"], cwd=work)
+    if code != 0:
+        status = {
+            "requested": True,
+            "status": "fail_git_init",
+            "original_commit": original_head,
+            "impersonates_original_tip": False,
+        }
+        return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)}
+    for cfg_key, cfg_val in (
+        ("user.name", "Prod2U Sanitized Snapshot"),
+        ("user.email", "sanitized-snapshot@invalid.local"),
+    ):
+        run_capture([git, "config", cfg_key, cfg_val], cwd=work)
+
+    selected: list[str] = []
+    if file_rels is None:
+        ls_files = _git_bytes(git, ["ls-files", "-z"], cwd=root)
+        if ls_files is None:
+            status = {
+                "requested": True,
+                "status": "fail_ls_files",
+                "original_commit": original_head,
+                "impersonates_original_tip": False,
+            }
+            return status, {
+                f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)
+            }
+        file_rels = [
+            raw.decode("utf-8", errors="surrogateescape")
+            for raw in ls_files.split(b"\0")
+            if raw
+        ]
+    for rel in file_rels:
+        if not allow_sanitized_snapshot_path(rel):
+            continue
+        src = root / Path(*rel.split("/"))
+        if not src.is_file():
+            continue
+        dest = work / Path(*rel.split("/"))
+        dest.parent.mkdir(parents=True, exist_ok=True)
+        shutil.copy2(src, dest)
+        selected.append(rel.replace("\\", "/"))
+    selected.sort()
+    if not selected:
+        status = {
+            "requested": True,
+            "status": "fail_empty_snapshot",
+            "original_commit": original_head,
+            "impersonates_original_tip": False,
+            "file_count": 0,
+        }
+        return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)}
+
+    code, _ = run_capture([git, "add", "-A"], cwd=work)
+    if code != 0:
+        status = {
+            "requested": True,
+            "status": "fail_git_add",
+            "original_commit": original_head,
+            "impersonates_original_tip": False,
+        }
+        return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)}
+    message = (
+        f"synthetic sanitized snapshot of {original_head or 'unknown'}\n\n"
+        "This is a synthetic single-commit snapshot for detached review.\n"
+        "It does NOT impersonate the original tip commit.\n"
+    )
+    code, _ = run_capture([git, "commit", "-q", "-m", message], cwd=work)
+    if code != 0:
+        status = {
+            "requested": True,
+            "status": "fail_git_commit",
+            "original_commit": original_head,
+            "impersonates_original_tip": False,
+        }
+        return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)}
+    synthetic_raw = _git_bytes(git, ["rev-parse", "HEAD"], cwd=work)
+    synthetic = (
+        synthetic_raw.decode("utf-8", errors="replace").strip()
+        if synthetic_raw is not None
+        else None
+    )
+    if not synthetic or synthetic == original_head:
+        status = {
+            "requested": True,
+            "status": "fail_synthetic_identity",
+            "original_commit": original_head,
+            "synthetic_commit": synthetic,
+            "impersonates_original_tip": False,
+            "note": "Synthetic commit must be distinct from original tip.",
+        }
+        return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)}
+
+    bundle_path = temp_root / "sanitized-snapshot.bundle"
+    code, verify = run_capture(
+        [git, "bundle", "create", str(bundle_path), "HEAD"],
+        cwd=work,
+    )
+    if code != 0 or not bundle_path.is_file():
+        status = {
+            "requested": True,
+            "status": "fail_bundle_create",
+            "original_commit": original_head,
+            "synthetic_commit": synthetic,
+            "impersonates_original_tip": False,
+            "detail": verify.decode("utf-8", errors="replace")[:500],
+        }
+        return status, {f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status)}
+
+    mapping = {
+        "schema": "cpld-sanitized-git-snapshot-mapping-v1",
+        "synthetic_commit": synthetic,
+        "original_commit": original_head,
+        "impersonates_original_tip": False,
+        "file_count": len(selected),
+        "files": selected,
+        "note": (
+            "Synthetic→original mapping only. Consumers must treat synthetic_commit "
+            "as a packaging artifact, never as the repository tip."
+        ),
+    }
+    status = {
+        "requested": True,
+        "status": "pass",
+        "synthetic_commit": synthetic,
+        "original_commit": original_head,
+        "impersonates_original_tip": False,
+        "bundle_path": f"{meta_prefix}/sanitized-snapshot.bundle",
+        "mapping_path": f"{meta_prefix}/sanitized-snapshot-mapping.json",
+        "file_count": len(selected),
+        "note": (
+            "Optional sanitized synthetic single-commit snapshot. "
+            "Records synthetic→original mapping and must not impersonate the original tip."
+        ),
+    }
+    artifacts = {
+        f"{meta_prefix}/sanitized-snapshot.bundle": bundle_path.read_bytes(),
+        f"{meta_prefix}/sanitized-snapshot-mapping.json": json_bytes(mapping),
+        f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(status),
+    }
+    return status, artifacts
+
+
 def collect_review_git_provenance(
 def collect_review_git_provenance(
     root: Path,
     root: Path,
     *,
     *,
     include_sanitized_git_snapshot: bool = False,
     include_sanitized_git_snapshot: bool = False,
     meta_prefix: str = "meta/git",
     meta_prefix: str = "meta/git",
+    temp_root: Path | None = None,
 ) -> tuple[dict[str, object], dict[str, bytes]]:
 ) -> tuple[dict[str, object], dict[str, bytes]]:
     """Git provenance for review-* packages: no full bundle; commit/status/log/tree/hashes."""
     """Git provenance for review-* packages: no full bundle; commit/status/log/tree/hashes."""
     git_dir = resolve_git_dir(root)
     git_dir = resolve_git_dir(root)
@@ -1338,6 +1538,9 @@ def collect_review_git_provenance(
                 "status": "not_applicable",
                 "status": "not_applicable",
             },
             },
         }
         }
+        artifacts[f"{meta_prefix}/sanitized-snapshot-status.json"] = json_bytes(
+            metadata["sanitized_git_snapshot"]
+        )
         return metadata, artifacts
         return metadata, artifacts
 
 
     branch, head = read_head_metadata(git_dir)
     branch, head = read_head_metadata(git_dir)
@@ -1353,7 +1556,14 @@ def collect_review_git_provenance(
                 "requested": include_sanitized_git_snapshot,
                 "requested": include_sanitized_git_snapshot,
                 "status": "blocked_missing_git_tool",
                 "status": "blocked_missing_git_tool",
             },
             },
-        }, artifacts
+        }, {
+            f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(
+                {
+                    "requested": include_sanitized_git_snapshot,
+                    "status": "blocked_missing_git_tool",
+                }
+            )
+        }
 
 
     status_payload = _git_bytes(
     status_payload = _git_bytes(
         git,
         git,
@@ -1382,11 +1592,13 @@ def collect_review_git_provenance(
 
 
     tree_rows: list[dict[str, object]] = []
     tree_rows: list[dict[str, object]] = []
     file_hashes: dict[str, str] = {}
     file_hashes: dict[str, str] = {}
+    file_rels: list[str] = []
     if ls_files is not None:
     if ls_files is not None:
         for raw in ls_files.split(b"\0"):
         for raw in ls_files.split(b"\0"):
             if not raw:
             if not raw:
                 continue
                 continue
             rel = raw.decode("utf-8", errors="surrogateescape")
             rel = raw.decode("utf-8", errors="surrogateescape")
+            file_rels.append(rel)
             path = root / Path(*rel.split("/"))
             path = root / Path(*rel.split("/"))
             if not path.is_file():
             if not path.is_file():
                 continue
                 continue
@@ -1418,20 +1630,34 @@ def collect_review_git_provenance(
         }
         }
     )
     )
 
 
-    snapshot_status = {
-        "requested": include_sanitized_git_snapshot,
-        "status": (
-            "reserved_for_p2"
-            if include_sanitized_git_snapshot
-            else "not_requested"
-        ),
-        "note": (
-            "Optional sanitized synthetic single-commit snapshot is a P2 extension. "
-            "When implemented it must record synthetic→original commit mapping and "
-            "must not impersonate the original tip."
-        ),
-    }
-    artifacts[f"{meta_prefix}/sanitized-snapshot-status.json"] = json_bytes(snapshot_status)
+    if include_sanitized_git_snapshot:
+        snap_temp = temp_root if temp_root is not None else Path(
+            tempfile.mkdtemp(prefix="prod2u-sanitized-git-", dir=os.environ.get("TMPDIR", "/tmp"))
+        )
+        snap_temp.mkdir(parents=True, exist_ok=True)
+        snapshot_status, snap_artifacts = create_sanitized_git_snapshot(
+            root,
+            git=git,
+            original_head=head,
+            temp_root=snap_temp,
+            meta_prefix=meta_prefix,
+            file_rels=file_rels,
+        )
+        artifacts.update(snap_artifacts)
+    else:
+        snapshot_status = {
+            "requested": False,
+            "status": "not_requested",
+            "impersonates_original_tip": False,
+            "note": (
+                "Optional sanitized synthetic single-commit snapshot via "
+                "--include-sanitized-git-snapshot. When present it records "
+                "synthetic→original mapping and must not impersonate the original tip."
+            ),
+        }
+        artifacts[f"{meta_prefix}/sanitized-snapshot-status.json"] = json_bytes(
+            snapshot_status
+        )
 
 
     capture_status = "pass"
     capture_status = "pass"
     if status_payload is None or log_payload is None or ls_files is None:
     if status_payload is None or log_payload is None or ls_files is None:

+ 15 - 0
tools/replay-review-compact.sh

@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+# Thin entrypoint: four-state review-compact replay.
+set -euo pipefail
+unset LD_LIBRARY_PATH LD_PRELOAD QT_PLUGIN_PATH || true
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+VENV="${PRODU2_VERIFY_VENV:-${XDG_CACHE_HOME:-$HOME/.cache}/prod2u/venvs/verify}"
+PY="${VENV}/bin/python"
+[[ -x "$PY" ]] || PY=python3
+if [[ $# -lt 1 ]]; then
+  echo "usage: $0 <package-dir> [--extract-dir DIR] [--skip-software] [--json-out PATH]" >&2
+  exit 2
+fi
+PACKAGE_DIR="$1"
+shift
+exec "$PY" -B "$ROOT/tools/replay_review_compact.py" --package-dir "$PACKAGE_DIR" "$@"

+ 415 - 0
tools/replay_review_compact.py

@@ -0,0 +1,415 @@
+#!/usr/bin/env python3
+"""Four-state replay for review-compact packages.
+
+Statuses (distinct):
+- package_content_replay: SHA256SUMS + inventory extract/hash verify
+- detached_software_replay: Git-optional software checks on extracted source/
+- reference_regeneration_replay: always ``not_packaged_by_policy``
+- hardware_validation: always ``not_run``
+"""
+
+from __future__ import annotations
+
+import argparse
+import importlib.util
+import json
+import os
+import subprocess
+import sys
+import tempfile
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+
+ROOT = Path(__file__).resolve().parents[1]
+TOOLS = ROOT / "tools"
+if str(TOOLS) not in sys.path:
+    sys.path.insert(0, str(TOOLS))
+
+from git_worktree_mode import (  # noqa: E402
+    DETACHED,
+    LIVE_GIT,
+    SNAPSHOT,
+    describe_git_mode,
+    detect_git_mode,
+)
+
+
+REFERENCE_REGENERATION_REPLAY = "not_packaged_by_policy"
+HARDWARE_VALIDATION = "not_run"
+
+
+class ReplayError(RuntimeError):
+    """Replay orchestration failure."""
+
+
+def _load_analyzer():
+    path = ROOT / "package_for_agent_analysis.py"
+    spec = importlib.util.spec_from_file_location("package_for_agent_analysis", path)
+    if spec is None or spec.loader is None:
+        raise ReplayError(f"unable to load packager module: {path}")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+def resolve_cpld_root(extract_or_cpld: Path) -> Path:
+    """Accept extract root, from-zip, or CPLD directory."""
+    path = extract_or_cpld.expanduser().resolve(strict=True)
+    candidates = (
+        path,
+        path / "CPLD",
+        path / "from-zip" / "CPLD",
+    )
+    for candidate in candidates:
+        if (candidate / "source").is_dir() or (candidate / "meta").is_dir():
+            return candidate
+        if candidate.name == "CPLD" and candidate.is_dir():
+            return candidate
+    raise ReplayError(f"unable to locate CPLD root under {path}")
+
+
+def extract_review_compact_package(
+    package_dir: Path,
+    *,
+    extract_root: Path,
+) -> dict[str, Any]:
+    """Package-content replay via packager API."""
+    analyzer = _load_analyzer()
+    return analyzer.replay_analysis_package(package_dir, extract_root=extract_root)
+
+
+def _run_unittest_modules(software_root: Path, modules: list[str]) -> dict[str, Any]:
+    """Run selected unittest modules with cwd/software_root; Git-optional."""
+    env = os.environ.copy()
+    env.setdefault("PRODU2_GIT_MODE", DETACHED)
+    # Prefer the extracted source tree on sys.path for imports that use relative roots.
+    pythonpath = str(software_root)
+    if env.get("PYTHONPATH"):
+        pythonpath = pythonpath + os.pathsep + env["PYTHONPATH"]
+    env["PYTHONPATH"] = pythonpath
+    results: list[dict[str, Any]] = []
+    overall = "pass"
+    for module in modules:
+        # Only run modules that exist under the extracted source tree.
+        rel = Path(*module.split("."))
+        candidate = software_root / rel.with_suffix(".py")
+        if not candidate.is_file():
+            results.append(
+                {
+                    "module": module,
+                    "status": "skipped_missing",
+                    "path": str(candidate),
+                }
+            )
+            continue
+        completed = subprocess.run(
+            [sys.executable, "-B", "-m", "unittest", module, "-q"],
+            cwd=str(software_root),
+            env=env,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.STDOUT,
+            text=True,
+            check=False,
+        )
+        status = "pass" if completed.returncode == 0 else "fail"
+        if status == "fail":
+            overall = "fail"
+        results.append(
+            {
+                "module": module,
+                "status": status,
+                "returncode": completed.returncode,
+                "output_tail": completed.stdout[-2000:],
+            }
+        )
+    return {"status": overall, "modules": results}
+
+
+def _check_layout(cpld_root: Path) -> dict[str, Any]:
+    source = cpld_root / "source"
+    evidence = cpld_root / "evidence"
+    meta = cpld_root / "meta"
+    checks = {
+        "source_dir": source.is_dir(),
+        "meta_dir": meta.is_dir(),
+        "evidence_dir": evidence.is_dir(),
+        "meta_git_dir": (meta / "git").is_dir(),
+        "no_raw_git_under_source": not (source / ".git").exists(),
+        "no_raw_git_under_cpld": not (cpld_root / ".git").exists(),
+    }
+    # Prefer package contract markers when present.
+    project = source / "projects" / "prod2u-door-temp" / "project.json"
+    checks["project_contract_present"] = project.is_file()
+    status = "pass" if all(
+        checks[key]
+        for key in (
+            "source_dir",
+            "meta_dir",
+            "no_raw_git_under_source",
+            "no_raw_git_under_cpld",
+        )
+    ) else "fail"
+    return {"status": status, "checks": checks}
+
+
+def _board_detached_check(cpld_root: Path) -> dict[str, Any]:
+    """Run board-viewer detached validation when P5 assets/API are available."""
+    generated_candidates = (
+        cpld_root / "evidence" / "board-viewer",
+        cpld_root / "source" / "tools" / "board-viewer" / "generated",
+    )
+    generated = next((path for path in generated_candidates if path.is_dir()), None)
+    if generated is None:
+        return {
+            "status": "skipped_no_board_assets",
+            "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
+        }
+
+    # Prefer extracted source validator; fall back to live repo tools.
+    validator_candidates = (
+        cpld_root / "source" / "tools" / "board-viewer" / "validate_detached_derived.py",
+        ROOT / "tools" / "board-viewer" / "validate_detached_derived.py",
+    )
+    validator = next((path for path in validator_candidates if path.is_file()), None)
+    if validator is None:
+        # Lightweight local checks without P5 module.
+        required = (
+            "board-data.json",
+            "build-info.json",
+            "import-report.json",
+            "board-copper.svg",
+            "board-silkscreen.svg",
+            "board-mask-edge.svg",
+        )
+        missing = [name for name in required if not (generated / name).is_file()]
+        return {
+            "status": "pass" if not missing else "fail",
+            "mode": "asset_presence",
+            "generated_dir": str(generated),
+            "missing": missing,
+            "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
+            "regeneration_claim": "none",
+        }
+
+    completed = subprocess.run(
+        [
+            sys.executable,
+            "-B",
+            str(validator),
+            "--generated-dir",
+            str(generated),
+        ],
+        cwd=str(validator.parent),
+        stdout=subprocess.PIPE,
+        stderr=subprocess.STDOUT,
+        text=True,
+        check=False,
+    )
+    return {
+        "status": "pass" if completed.returncode == 0 else "fail",
+        "mode": "validate_detached_derived",
+        "generated_dir": str(generated),
+        "returncode": completed.returncode,
+        "output_tail": completed.stdout[-2000:],
+        "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
+        "regeneration_claim": "none",
+    }
+
+
+def run_detached_software_replay(cpld_root: Path) -> dict[str, Any]:
+    """Git-optional software replay against extracted CPLD tree."""
+    cpld_root = resolve_cpld_root(cpld_root)
+    source_root = cpld_root / "source"
+    git_mode = detect_git_mode(cpld_root)
+    if git_mode == LIVE_GIT:
+        # Extracted compact trees must not expose raw .git; live_git here is unexpected.
+        git_info = describe_git_mode(cpld_root)
+    else:
+        git_info = describe_git_mode(cpld_root)
+
+    layout = _check_layout(cpld_root)
+    board = _board_detached_check(cpld_root)
+
+    unit_modules = [
+        "tests.unit.test_protocol",
+        "tests.unit.test_project_config",
+        "tests.unit.test_product_contract_coverage",
+    ]
+    unit = (
+        _run_unittest_modules(source_root, unit_modules)
+        if source_root.is_dir()
+        else {"status": "fail", "modules": [], "reason": "missing source/"}
+    )
+
+    # Meta git provenance must be usable without raw .git.
+    meta_git = cpld_root / "meta" / "git"
+    provenance = {
+        "status": "pass" if meta_git.is_dir() else "fail",
+        "head_txt": (meta_git / "HEAD.txt").is_file() if meta_git.is_dir() else False,
+        "tree_manifest": (meta_git / "tree-manifest.json").is_file()
+        if meta_git.is_dir()
+        else False,
+        "sanitized_snapshot_status": (
+            meta_git / "sanitized-snapshot-status.json"
+        ).is_file()
+        if meta_git.is_dir()
+        else False,
+        "raw_git_required": False,
+    }
+
+    parts = {
+        "layout": layout["status"],
+        "provenance": provenance["status"],
+        "unit": unit["status"],
+        "board": board["status"],
+    }
+    # skipped_* board does not fail the lane; fail/skip-missing unit modules are soft
+    # unless layout/provenance fail.
+    soft_board = board["status"].startswith("skipped_")
+    soft_unit_skip_only = unit["status"] == "pass" or (
+        unit["status"] != "fail"
+        and all(
+            row.get("status") in {"pass", "skipped_missing"}
+            for row in unit.get("modules", [])
+        )
+    )
+    if layout["status"] != "pass" or provenance["status"] != "pass":
+        overall = "fail"
+    elif unit["status"] == "fail":
+        overall = "fail"
+    elif not soft_board and board["status"] == "fail":
+        overall = "fail"
+    else:
+        overall = "pass"
+
+    return {
+        "status": overall,
+        "git_mode": git_mode,
+        "git_mode_info": git_info,
+        "software_root": str(source_root),
+        "layout": layout,
+        "provenance": provenance,
+        "unit": unit,
+        "board": board,
+        "part_statuses": parts,
+        "soft_unit_skip_only": soft_unit_skip_only,
+        "note": (
+            "Detached software replay does not require raw .git; "
+            "live_git commit-compare paths remain strict elsewhere."
+        ),
+    }
+
+
+def replay_review_compact(
+    package_dir: Path,
+    *,
+    extract_root: Path | None = None,
+    skip_software: bool = False,
+) -> dict[str, Any]:
+    """Run the four-state review-compact replay."""
+    package_dir = package_dir.expanduser().resolve(strict=True)
+    if extract_root is None:
+        extract_root = Path(
+            tempfile.mkdtemp(
+                prefix="prod2u-review-compact-replay-",
+                dir=os.environ.get("TMPDIR", "/tmp"),
+            )
+        )
+    else:
+        extract_root = extract_root.expanduser().resolve(strict=False)
+
+    content = extract_review_compact_package(package_dir, extract_root=extract_root)
+    package_content_status = str(content.get("package_content_replay") or content.get("status") or "fail")
+
+    cpld_root_raw = content.get("cpld_root")
+    if not cpld_root_raw:
+        cpld_root = resolve_cpld_root(extract_root)
+    else:
+        cpld_root = Path(str(cpld_root_raw))
+
+    if skip_software:
+        software: dict[str, Any] = {
+            "status": "not_run",
+            "note": "skipped by --skip-software",
+        }
+        detached_status = "not_run"
+    else:
+        software = run_detached_software_replay(cpld_root)
+        detached_status = str(software.get("status") or "fail")
+
+    overall = "pass"
+    if package_content_status != "pass":
+        overall = "fail"
+    elif detached_status not in {"pass", "not_run"}:
+        overall = "fail"
+
+    return {
+        "schema": "cpld-review-compact-four-state-replay-v1",
+        "generated_at_utc": datetime.now(timezone.utc).isoformat(),
+        "status": overall,
+        "package_dir": str(package_dir),
+        "extract_root": str(extract_root),
+        "cpld_root": str(cpld_root),
+        "package_content_replay": package_content_status,
+        "detached_software_replay": detached_status,
+        "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
+        "hardware_validation": HARDWARE_VALIDATION,
+        "package_content": content,
+        "detached_software": software,
+        "git_modes": {
+            "LIVE_GIT": LIVE_GIT,
+            "SNAPSHOT": SNAPSHOT,
+            "DETACHED": DETACHED,
+        },
+    }
+
+
+def build_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument(
+        "--package-dir",
+        type=Path,
+        required=True,
+        help="published package directory (HANDOFF-INDEX.json + ZIP)",
+    )
+    parser.add_argument(
+        "--extract-dir",
+        type=Path,
+        help="extract target (must not already exist)",
+    )
+    parser.add_argument(
+        "--skip-software",
+        action="store_true",
+        help="only run package_content_replay",
+    )
+    parser.add_argument(
+        "--json-out",
+        type=Path,
+        help="write full four-state report JSON",
+    )
+    return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = build_parser().parse_args(argv)
+    try:
+        report = replay_review_compact(
+            args.package_dir,
+            extract_root=args.extract_dir,
+            skip_software=args.skip_software,
+        )
+    except Exception as exc:  # noqa: BLE001 - CLI boundary
+        print(f"error: {exc}", file=sys.stderr)
+        return 1
+    text = json.dumps(report, ensure_ascii=False, indent=2)
+    print(text)
+    if args.json_out is not None:
+        args.json_out.parent.mkdir(parents=True, exist_ok=True)
+        args.json_out.write_text(text + "\n", encoding="utf-8")
+    return 0 if report.get("status") == "pass" else 2
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())