소스 검색

fix(mse): fail-close detached replay evidence completeness

Sidecar nested status=pass is not enough: bind exact unit/layout/board
evidence and independently rerun extracted ZIP software replay.

Co-authored-by: Cursor <cursoragent@cursor.com>
root 3 달 전
부모
커밋
8606416840

+ 51 - 7
tests/unit/test_mse_r11_release_validation_bind.py

@@ -29,9 +29,25 @@ def _write_identity_zip(path: Path, *, extra: str = "payload") -> None:
         "delivery_commit": DELIVERY,
         "release_set_id": RELEASE_SET_ID,
     }
+    members = {
+        "meta/release-set-identity.json": json.dumps(identity),
+        "payload.txt": extra,
+    }
+    files = []
+    for name, blob in members.items():
+        data = blob.encode("utf-8") if isinstance(blob, str) else blob
+        files.append(
+            {
+                "archive_path": name,
+                "size": len(data),
+                "sha256": hashlib.sha256(data).hexdigest(),
+            }
+        )
+    manifest = {"schema": "prod2u-volume-manifest-v1", "file_count": len(files), "files": files}
     with zipfile.ZipFile(path, "w") as zf:
-        zf.writestr("meta/release-set-identity.json", json.dumps(identity))
-        zf.writestr("payload.txt", extra)
+        for name, blob in members.items():
+            zf.writestr(name, blob)
+        zf.writestr("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", json.dumps(manifest))
 
 
 def _pass_selftests():
@@ -69,21 +85,49 @@ def _complete_replay_sidecar(review: Path, *, review_sha: str | None = None) ->
         "package_content": {
             "status": "pass",
             "package_content_replay": "pass",
-            "checked_files": 12,
+            "checked_files": 2,
             "volumes": [{"file": review.name, "sha256": review_sha}],
         },
         "detached_software": {
             "status": "pass",
             "git_mode": "detached",
-            "layout": {"status": "pass"},
-            "provenance": {"status": "pass"},
+            "layout": {
+                "status": "pass",
+                "checks": {
+                    "source_dir": True,
+                    "meta_dir": True,
+                    "evidence_dir": True,
+                    "meta_git_dir": True,
+                    "no_raw_git_under_source": True,
+                    "no_raw_git_under_cpld": True,
+                    "project_contract_present": True,
+                },
+            },
+            "provenance": {
+                "status": "pass",
+                "head_txt": True,
+                "tree_manifest": True,
+                "sanitized_snapshot_status": True,
+                "raw_git_required": False,
+            },
             "unit": {
                 "status": "pass",
                 "modules": [
-                    {"module": "tests.unit.test_protocol", "status": "pass"},
+                    {"module": "tests.unit.test_protocol", "status": "pass", "returncode": 0},
+                    {"module": "tests.unit.test_project_config", "status": "pass", "returncode": 0},
+                    {
+                        "module": "tests.unit.test_product_contract_coverage",
+                        "status": "pass",
+                        "returncode": 0,
+                    },
                 ],
             },
-            "board": {"status": "pass", "mode": "validate_detached_derived"},
+            "board": {
+                "status": "pass",
+                "mode": "validate_detached_derived",
+                "returncode": 0,
+                "reference_regeneration_replay": "not_packaged_by_policy",
+            },
         },
     }
     attach_shared_identity_fields(doc, ident)

+ 328 - 0
tests/unit/test_mse_r15_replay_sidecar_bind.py

@@ -0,0 +1,328 @@
+"""Round-15: detached replay sidecar evidence completeness must fail-close."""
+
+from __future__ import annotations
+
+import copy
+import hashlib
+import json
+import zipfile
+from pathlib import Path
+from unittest import mock
+
+from tests.unit.test_mse_r11_release_validation_bind import (
+    _matching_sidecars,
+    _validate,
+    _write_identity_zip,
+)
+from tools import replay_semantic as rs
+
+
+def _setup(tmp_path: Path):
+    review = tmp_path / "review.zip"
+    firmware = tmp_path / "firmware.zip"
+    _write_identity_zip(review)
+    _write_identity_zip(firmware, extra="fw")
+    return review, firmware, _matching_sidecars(tmp_path, review, firmware)
+
+
+def _mutate_and_validate(tmp_path: Path, mutate):
+    review, firmware, sidecars = _setup(tmp_path)
+    doc = json.loads(sidecars["review_detached_replay_json"].read_text(encoding="utf-8"))
+    mutate(doc)
+    sidecars["review_detached_replay_json"].write_text(json.dumps(doc), encoding="utf-8")
+    return _validate(tmp_path, review, firmware, sidecars)
+
+
+def _assert_fail(result: dict, *codes: str) -> None:
+    assert result["status"] != "pass"
+    joined = " ".join(result.get("failures") or [])
+    for code in codes:
+        assert code in joined, f"missing {code} in {result.get('failures')}"
+
+
+def test_r15_happy_complete_sidecar_still_pass(tmp_path: Path):
+    review, firmware, sidecars = _setup(tmp_path)
+    result = _validate(tmp_path, review, firmware, sidecars)
+    assert result["status"] == "pass", result.get("failures")
+    assert result.get("failures") == []
+
+
+def test_r15_empty_unit_modules_fail(tmp_path: Path):
+    def mutate(doc):
+        doc["detached_software"]["unit"]["modules"] = []
+
+    _assert_fail(_mutate_and_validate(tmp_path, mutate), "replay_sidecar_unit_modules_empty")
+
+
+def test_r15_partial_unit_modules_fail(tmp_path: Path):
+    def mutate(doc):
+        doc["detached_software"]["unit"]["modules"] = [
+            {"module": "tests.unit.test_protocol", "status": "pass", "returncode": 0}
+        ]
+
+    _assert_fail(
+        _mutate_and_validate(tmp_path, mutate), "replay_sidecar_unit_modules_incomplete"
+    )
+
+
+def test_r15_wrong_unit_module_fail(tmp_path: Path):
+    def mutate(doc):
+        mods = doc["detached_software"]["unit"]["modules"]
+        mods[0]["module"] = "tests.unit.test_not_a_required_module"
+
+    _assert_fail(_mutate_and_validate(tmp_path, mutate), "replay_sidecar_unit_module_unknown")
+
+
+def test_r15_duplicate_unit_module_fail(tmp_path: Path):
+    def mutate(doc):
+        mods = doc["detached_software"]["unit"]["modules"]
+        mods[1] = copy.deepcopy(mods[0])
+
+    _assert_fail(
+        _mutate_and_validate(tmp_path, mutate), "replay_sidecar_unit_module_duplicate"
+    )
+
+
+def test_r15_unit_pass_nonzero_rc_fail(tmp_path: Path):
+    def mutate(doc):
+        doc["detached_software"]["unit"]["modules"][0]["returncode"] = 13
+
+    _assert_fail(
+        _mutate_and_validate(tmp_path, mutate), "replay_sidecar_unit_module_not_pass"
+    )
+
+
+def test_r15_minimal_nested_pass_fail(tmp_path: Path):
+    def mutate(doc):
+        doc["package_content"] = {
+            "status": "pass",
+            "package_content_replay": "pass",
+            "checked_files": 1,
+            "volumes": doc["package_content"]["volumes"],
+        }
+        doc["detached_software"] = {
+            "status": "pass",
+            "git_mode": "detached",
+            "layout": {"status": "pass"},
+            "provenance": {"status": "pass"},
+            "unit": {"status": "pass", "modules": []},
+            "board": {"status": "pass"},
+        }
+
+    _assert_fail(
+        _mutate_and_validate(tmp_path, mutate),
+        "replay_sidecar_unit_modules_empty",
+        "replay_sidecar_layout_checks_missing",
+        "replay_volume_manifest_file_count_mismatch",
+    )
+
+
+def test_r15_board_status_only_fail(tmp_path: Path):
+    def mutate(doc):
+        doc["detached_software"]["board"] = {"status": "pass"}
+
+    _assert_fail(
+        _mutate_and_validate(tmp_path, mutate), "replay_sidecar_board_mode_not_canonical"
+    )
+
+
+def test_r15_board_mode_bogus_fail(tmp_path: Path):
+    def mutate(doc):
+        doc["detached_software"]["board"]["mode"] = "bogus"
+        doc["detached_software"]["board"]["returncode"] = 99
+
+    _assert_fail(
+        _mutate_and_validate(tmp_path, mutate),
+        "replay_sidecar_board_mode_not_canonical",
+        "replay_sidecar_board_returncode_nonzero",
+    )
+
+
+def test_r15_layout_checks_false_fail(tmp_path: Path):
+    def mutate(doc):
+        for key in doc["detached_software"]["layout"]["checks"]:
+            doc["detached_software"]["layout"]["checks"][key] = False
+
+    _assert_fail(
+        _mutate_and_validate(tmp_path, mutate), "replay_sidecar_layout_required_check_false"
+    )
+
+
+def test_r15_provenance_details_false_fail(tmp_path: Path):
+    def mutate(doc):
+        doc["detached_software"]["provenance"]["head_txt"] = False
+        doc["detached_software"]["provenance"]["tree_manifest"] = False
+        doc["detached_software"]["provenance"]["sanitized_snapshot_status"] = False
+        doc["detached_software"]["provenance"]["raw_git_required"] = True
+
+    _assert_fail(
+        _mutate_and_validate(tmp_path, mutate),
+        "replay_sidecar_provenance_details_false",
+        "replay_sidecar_provenance_raw_git_required",
+    )
+
+
+def test_r15_checked_files_one_fail(tmp_path: Path):
+    def mutate(doc):
+        doc["package_content"]["checked_files"] = 1
+
+    _assert_fail(
+        _mutate_and_validate(tmp_path, mutate), "replay_volume_manifest_file_count_mismatch"
+    )
+
+
+def _write_source_review_zip(path: Path) -> None:
+    identity = {
+        "schema": "prod2u-release-set-identity-v1",
+        "delivery_commit": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+        "release_set_id": "bb" * 32,
+    }
+    members = {
+        "meta/release-set-identity.json": json.dumps(identity).encode("utf-8"),
+        "payload.txt": b"review-source",
+        "CPLD/source/hello.py": b"x = 1\n",
+    }
+    files = [
+        {
+            "archive_path": name,
+            "size": len(blob),
+            "sha256": hashlib.sha256(blob).hexdigest(),
+        }
+        for name, blob in members.items()
+    ]
+    manifest = {"schema": "prod2u-volume-manifest-v1", "file_count": len(files), "files": files}
+    with zipfile.ZipFile(path, "w") as zf:
+        for name, blob in members.items():
+            zf.writestr(name, blob)
+        zf.writestr("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", json.dumps(manifest))
+
+
+def _matching_source_software() -> dict:
+    return {
+        "status": "pass",
+        "git_mode": "detached",
+        "layout": {
+            "status": "pass",
+            "checks": {
+                "source_dir": True,
+                "meta_dir": True,
+                "evidence_dir": True,
+                "meta_git_dir": True,
+                "no_raw_git_under_source": True,
+                "no_raw_git_under_cpld": True,
+                "project_contract_present": True,
+            },
+        },
+        "provenance": {
+            "status": "pass",
+            "head_txt": True,
+            "tree_manifest": True,
+            "sanitized_snapshot_status": True,
+            "raw_git_required": False,
+        },
+        "unit": {
+            "status": "pass",
+            "modules": [
+                {"module": "tests.unit.test_protocol", "status": "pass", "returncode": 0},
+                {"module": "tests.unit.test_project_config", "status": "pass", "returncode": 0},
+                {
+                    "module": "tests.unit.test_product_contract_coverage",
+                    "status": "pass",
+                    "returncode": 0,
+                },
+            ],
+        },
+        "board": {
+            "status": "pass",
+            "mode": "validate_detached_derived",
+            "returncode": 0,
+            "reference_regeneration_replay": "not_packaged_by_policy",
+        },
+    }
+
+
+def test_r15_dummy_zip_skips_independent_rerun(tmp_path: Path):
+    review, firmware, sidecars = _setup(tmp_path)
+    assert rs.review_zip_has_source_tree(review) is False
+    result = _validate(tmp_path, review, firmware, sidecars)
+    assert result["status"] == "pass", result.get("failures")
+
+
+def test_r15_independent_rerun_matches_sidecar(tmp_path: Path):
+    review = tmp_path / "review.zip"
+    firmware = tmp_path / "firmware.zip"
+    _write_source_review_zip(review)
+    _write_identity_zip(firmware, extra="fw")
+    sidecars = _matching_sidecars(tmp_path, review, firmware)
+    doc = json.loads(sidecars["review_detached_replay_json"].read_text(encoding="utf-8"))
+    doc["package_content"]["checked_files"] = 3
+    actual = _matching_source_software()
+    claimed = rs.semantic_object(
+        content=doc["package_content"], software=doc["detached_software"]
+    )
+    actual_sem = rs.semantic_object(content=doc["package_content"], software=actual)
+    actual_sem["checked_files"] = 3
+    doc["replay_semantic_sha256"] = rs.semantic_sha256(actual_sem)
+    sidecars["review_detached_replay_json"].write_text(json.dumps(doc), encoding="utf-8")
+    with mock.patch.object(rs, "_run_actual_software_replay", return_value=actual):
+        result = _validate(tmp_path, review, firmware, sidecars)
+    assert result["status"] == "pass", result.get("failures")
+    assert claimed["unit_modules"] == actual_sem["unit_modules"]
+
+
+def test_r15_independent_rerun_unit_mismatch_fail(tmp_path: Path):
+    review = tmp_path / "review.zip"
+    firmware = tmp_path / "firmware.zip"
+    _write_source_review_zip(review)
+    _write_identity_zip(firmware, extra="fw")
+    sidecars = _matching_sidecars(tmp_path, review, firmware)
+    doc = json.loads(sidecars["review_detached_replay_json"].read_text(encoding="utf-8"))
+    doc["package_content"]["checked_files"] = 3
+    sidecars["review_detached_replay_json"].write_text(json.dumps(doc), encoding="utf-8")
+    actual = _matching_source_software()
+    actual["unit"]["modules"][0]["module"] = "tests.unit.test_not_replayed"
+    with mock.patch.object(rs, "_run_actual_software_replay", return_value=actual):
+        result = _validate(tmp_path, review, firmware, sidecars)
+    _assert_fail(result, "replay_semantic_unit_mismatch")
+
+
+def test_r15_mkdtemp_then_extract_does_not_file_exists(tmp_path: Path):
+    """Regression: mkdtemp() + mkdir(exist_ok=False) on the same path."""
+    review = tmp_path / "review.zip"
+    _write_source_review_zip(review)
+    result = rs._run_actual_software_replay(review)
+    assert isinstance(result, dict)
+    assert "status" in result
+    assert "layout" in result
+
+
+def test_r15_independent_rerun_error_fail(tmp_path: Path):
+    review = tmp_path / "review.zip"
+    firmware = tmp_path / "firmware.zip"
+    _write_source_review_zip(review)
+    _write_identity_zip(firmware, extra="fw")
+    sidecars = _matching_sidecars(tmp_path, review, firmware)
+    doc = json.loads(sidecars["review_detached_replay_json"].read_text(encoding="utf-8"))
+    doc["package_content"]["checked_files"] = 3
+    sidecars["review_detached_replay_json"].write_text(json.dumps(doc), encoding="utf-8")
+    with mock.patch.object(rs, "_run_actual_software_replay", side_effect=RuntimeError("extract")):
+        result = _validate(tmp_path, review, firmware, sidecars)
+    _assert_fail(result, "replay_actual_rerun_error")
+
+
+def test_r15_semantic_checked_files_mismatch_fail(tmp_path: Path):
+    review = tmp_path / "review.zip"
+    firmware = tmp_path / "firmware.zip"
+    _write_source_review_zip(review)
+    _write_identity_zip(firmware, extra="fw")
+    sidecars = _matching_sidecars(tmp_path, review, firmware)
+    doc = json.loads(sidecars["review_detached_replay_json"].read_text(encoding="utf-8"))
+    doc["package_content"]["checked_files"] = 1
+    sidecars["review_detached_replay_json"].write_text(json.dumps(doc), encoding="utf-8")
+    with mock.patch.object(rs, "_run_actual_software_replay", return_value=_matching_source_software()):
+        result = _validate(tmp_path, review, firmware, sidecars)
+    _assert_fail(
+        result,
+        "replay_volume_manifest_file_count_mismatch",
+        "replay_semantic_checked_files_mismatch",
+    )

+ 47 - 0
tests/unit/test_replay_review_compact.py

@@ -331,6 +331,29 @@ class FourStateReplayTests(unittest.TestCase):
             # 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")
@@ -390,5 +413,29 @@ class FourStateReplayTests(unittest.TestCase):
             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()

+ 125 - 1
tools/release_validation.py

@@ -26,6 +26,7 @@ try:
         verify_cross_package,
     )
     from package_provenance import compute_release_set_id
+    from replay_semantic import bind_independent_replay
 except ImportError:  # pytest imports tools.release_validation
     from tools.compact_package_selftest import run_compact_zip_selftest
     from tools.cross_package_verify import (
@@ -35,6 +36,7 @@ except ImportError:  # pytest imports tools.release_validation
         verify_cross_package,
     )
     from tools.package_provenance import compute_release_set_id
+    from tools.replay_semantic import bind_independent_replay
 
 try:
     try:
@@ -64,6 +66,20 @@ REQUIRED_PARTS = (
 _CLOSED_STATUSES = frozenset(
     {"", "skipped", "not_provided", "missing", "unknown", "incompatible"}
 )
+LAYOUT_REQUIRED_CHECKS = (
+    "source_dir",
+    "meta_dir",
+    "evidence_dir",
+    "meta_git_dir",
+    "no_raw_git_under_source",
+    "no_raw_git_under_cpld",
+    "project_contract_present",
+)
+REQUIRED_BOARD_MODE = "validate_detached_derived"
+VOLUME_MANIFEST_MEMBERS = (
+    "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json",
+    "HANDOFF-METADATA/VOLUME-MANIFEST.json",
+)
 _BASENAME_HINT_KEYS = (
     "package_path",
     "zip_path",
@@ -429,6 +445,112 @@ def _bind_review_sidecar(doc: dict[str, Any], facts: dict[str, Any], *, require:
     return failures
 
 
+def _expected_unit_modules() -> list[str]:
+    try:
+        from test_profiles import detached_replay_unit_modules
+    except ImportError:
+        from tools.test_profiles import detached_replay_unit_modules
+    return list(detached_replay_unit_modules())
+
+
+def _volume_manifest_file_count(zip_path: Path) -> int | None:
+    try:
+        with zipfile.ZipFile(zip_path) as zf:
+            names = set(zf.namelist())
+            for member in VOLUME_MANIFEST_MEMBERS:
+                if member not in names:
+                    continue
+                doc = json.loads(zf.read(member).decode("utf-8"))
+                if isinstance(doc, dict) and "file_count" in doc:
+                    return int(doc["file_count"])
+    except (OSError, zipfile.BadZipFile, json.JSONDecodeError, TypeError, ValueError):
+        return None
+    return None
+
+
+def _bind_replay_completeness(
+    doc: dict[str, Any],
+    content: dict[str, Any],
+    software: dict[str, Any],
+    zip_path: Path,
+) -> list[str]:
+    """Fail-closed evidence completeness (Round-15). Nested status=pass is not enough."""
+    failures: list[str] = []
+    expected = _expected_unit_modules()
+    unit = _as_dict(software.get("unit"))
+    raw_modules = unit.get("modules") if isinstance(unit.get("modules"), list) else []
+    names: list[str] = []
+    for mod in raw_modules:
+        if not isinstance(mod, dict):
+            failures.append("replay_sidecar_unit_module_not_pass")
+            continue
+        name = str(mod.get("module") or "")
+        names.append(name)
+        st = str(mod.get("status") or "").casefold()
+        try:
+            rc = int(mod.get("returncode"))
+        except (TypeError, ValueError):
+            rc = None
+        if st != "pass" or rc != 0:
+            failures.append("replay_sidecar_unit_module_not_pass")
+    if not names:
+        failures.append("replay_sidecar_unit_modules_empty")
+    elif sorted(names) != sorted(expected):
+        if any(n not in expected for n in names):
+            failures.append("replay_sidecar_unit_module_unknown")
+        if len(names) != len(set(names)):
+            failures.append("replay_sidecar_unit_module_duplicate")
+        if set(expected) - set(names):
+            failures.append("replay_sidecar_unit_modules_incomplete")
+        if "replay_sidecar_unit_modules_incomplete" not in failures and sorted(names) != sorted(
+            expected
+        ):
+            failures.append("replay_sidecar_unit_modules_incomplete")
+
+    layout = _as_dict(software.get("layout"))
+    checks = _as_dict(layout.get("checks"))
+    if not checks:
+        failures.append("replay_sidecar_layout_checks_missing")
+    else:
+        for key in LAYOUT_REQUIRED_CHECKS:
+            if checks.get(key) is not True:
+                failures.append("replay_sidecar_layout_required_check_false")
+                break
+
+    provenance = _as_dict(software.get("provenance"))
+    if provenance.get("raw_git_required") is True:
+        failures.append("replay_sidecar_provenance_raw_git_required")
+    for field in ("head_txt", "tree_manifest", "sanitized_snapshot_status"):
+        if provenance.get(field) is not True:
+            failures.append("replay_sidecar_provenance_details_false")
+            break
+
+    board = _as_dict(software.get("board"))
+    if str(board.get("mode") or "") != REQUIRED_BOARD_MODE:
+        failures.append("replay_sidecar_board_mode_not_canonical")
+    try:
+        board_rc = int(board.get("returncode"))
+    except (TypeError, ValueError):
+        board_rc = None
+    if board_rc != 0:
+        failures.append("replay_sidecar_board_returncode_nonzero")
+    regen = str(board.get("reference_regeneration_replay") or doc.get("reference_regeneration_replay") or "")
+    if regen and regen.casefold() not in {"not_packaged_by_policy"}:
+        failures.append("replay_sidecar_board_reference_policy")
+
+    file_count = _volume_manifest_file_count(zip_path)
+    if file_count is None:
+        failures.append("replay_volume_manifest_missing")
+    else:
+        try:
+            checked = int(content.get("checked_files") or 0)
+        except (TypeError, ValueError):
+            checked = 0
+        if checked != file_count:
+            failures.append("replay_volume_manifest_file_count_mismatch")
+    return failures
+
+
 def _iter_replay_zip_claims(doc: dict[str, Any]) -> list[tuple[str | None, str | None]]:
     claims: list[tuple[str | None, str | None]] = []
     buckets = [doc, _as_dict(doc.get("package_content"))]
@@ -580,12 +702,14 @@ def _bind_replay_sidecar(
             if not isinstance(mod, dict):
                 continue
             st = str(mod.get("status") or "").casefold()
-            if st in {"fail", "skipped_missing"}:
+            if st in {"fail", "skipped_missing", "fail_missing"}:
                 failures.append("replay_sidecar_unit_module_not_pass")
                 break
         git_mode = str(software.get("git_mode") or "").casefold()
         if git_mode not in {"detached", "snapshot"}:
             failures.append("replay_sidecar_git_mode_not_detached")
+        failures.extend(_bind_replay_completeness(doc, content, software, zip_path))
+        failures.extend(bind_independent_replay(zip_path, doc))
 
     for name, sha in _iter_replay_zip_claims(doc):
         if name and not _basename_matches(name, zip_path):

+ 62 - 40
tools/replay_review_compact.py

@@ -183,10 +183,12 @@ def _run_unittest_modules(software_root: Path, modules: list[str]) -> dict[str,
         rel = Path(*module.split("."))
         candidate = software_root / rel.with_suffix(".py")
         if not candidate.is_file():
+            overall = "fail"
             results.append(
                 {
                     "module": module,
-                    "status": "skipped_missing",
+                    "status": "fail_missing",
+                    "returncode": None,
                     "path": str(candidate),
                 }
             )
@@ -229,15 +231,7 @@ def _check_layout(cpld_root: Path) -> dict[str, Any]:
     # 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"
+    status = "pass" if all(checks.values()) else "fail"
     return {"status": status, "checks": checks}
 
 
@@ -250,8 +244,11 @@ def _board_detached_check(cpld_root: Path) -> dict[str, Any]:
     generated = next((path for path in generated_candidates if path.is_dir()), None)
     if generated is None:
         return {
-            "status": "skipped_no_board_assets",
+            "status": "fail",
+            "mode": "missing_board_assets",
+            "returncode": None,
             "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
+            "regeneration_claim": "none",
         }
 
     # Prefer extracted source validator; fall back to live repo tools.
@@ -275,10 +272,12 @@ def _board_detached_check(cpld_root: Path) -> dict[str, Any]:
         )
         missing = [name for name in required if not (generated / name).is_file()]
         return {
-            "status": "pass" if not missing else "fail",
+            "status": "fail",
             "mode": "asset_presence",
+            "returncode": None,
             "generated_dir": str(generated),
             "missing": missing,
+            "reason": "final-review forbids asset_presence fallback",
             "reference_regeneration_replay": REFERENCE_REGENERATION_REPLAY,
             "regeneration_claim": "none",
         }
@@ -342,45 +341,55 @@ def run_detached_software_replay(cpld_root: Path) -> dict[str, Any]:
 
     # 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()
+    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 = (
+        (meta_git / "sanitized-snapshot-status.json").is_file()
         if meta_git.is_dir()
-        else False,
+        else False
+    )
+    provenance = {
+        "status": "pass"
+        if (meta_git.is_dir() and head_txt and tree_manifest and sanitized)
+        else "fail",
+        "head_txt": head_txt,
+        "tree_manifest": tree_manifest,
+        "sanitized_snapshot_status": sanitized,
         "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", [])
-        )
+    observed = [str(row.get("module") or "") for row in unit.get("modules", [])]
+    unit_exact = sorted(observed) == sorted(unit_modules) and unit["status"] == "pass"
+    try:
+        board_rc = int(board.get("returncode"))
+    except (TypeError, ValueError):
+        board_rc = None
+    board_ok = (
+        board.get("status") == "pass"
+        and str(board.get("mode") or "") == "validate_detached_derived"
+        and board_rc == 0
     )
     if layout["status"] != "pass" or provenance["status"] != "pass":
         overall = "fail"
-    elif unit["status"] == "fail":
+    elif unit["status"] == "fail" or not unit_exact:
         overall = "fail"
-    elif not soft_board and board["status"] == "fail":
+        unit["status"] = "fail"
+    elif not board_ok:
         overall = "fail"
+        if board.get("status") == "pass":
+            board["status"] = "fail"
     else:
         overall = "pass"
 
+    parts = {
+        "layout": layout["status"],
+        "provenance": provenance["status"],
+        "unit": unit["status"],
+        "board": board["status"],
+    }
+
     return {
         "status": overall,
         "git_mode": git_mode,
@@ -391,7 +400,7 @@ def run_detached_software_replay(cpld_root: Path) -> dict[str, Any]:
         "unit": unit,
         "board": board,
         "part_statuses": parts,
-        "soft_unit_skip_only": soft_unit_skip_only,
+        "unit_exact_set": unit_exact,
         "note": (
             "Detached software replay does not require raw .git; "
             "live_git commit-compare paths remain strict elsewhere."
@@ -435,6 +444,14 @@ def replay_review_compact(
         software = run_detached_software_replay(cpld_root)
         detached_status = str(software.get("status") or "fail")
 
+    zip_path = _review_zip_in_package_dir(package_dir)
+    if isinstance(content, dict) and zip_path is not None:
+        try:
+            from replay_semantic import align_checked_files_to_manifest
+        except ImportError:
+            from tools.replay_semantic import align_checked_files_to_manifest
+        align_checked_files_to_manifest(content, zip_path)
+
     overall = "pass"
     if package_content_status != "pass":
         overall = "fail"
@@ -461,6 +478,11 @@ def replay_review_compact(
         },
     }
     stamp_replay_sidecar_identity(report, package_dir)
+    try:
+        from replay_semantic import stamp_replay_semantic
+    except ImportError:
+        from tools.replay_semantic import stamp_replay_semantic
+    stamp_replay_semantic(report, zip_path=zip_path)
     return report
 
 

+ 286 - 0
tools/replay_semantic.py

@@ -0,0 +1,286 @@
+#!/usr/bin/env python3
+"""Independent review-ZIP inventory + detached-replay semantic digest.
+
+Sidecar nested ``status: pass`` is not evidence. When the ZIP contains a
+``source/`` tree, release-validation safe-extracts the actual bytes, reruns
+``run_detached_software_replay`` on the extracted CPLD root, and compares a
+canonical semantic object (and optional ``replay_semantic_sha256``) to the
+external sidecar. Dummy unit-test ZIPs without source skip the rerun.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import re
+import shutil
+import tempfile
+import zipfile
+from pathlib import Path
+from typing import Any
+
+VOLUME_MANIFEST_MEMBERS = (
+    "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json",
+    "HANDOFF-METADATA/VOLUME-MANIFEST.json",
+)
+
+
+def _norm_member(name: str) -> str:
+    return str(name or "").replace("\\", "/").lstrip("./")
+
+
+def review_zip_has_source_tree(zip_path: Path) -> bool:
+    try:
+        with zipfile.ZipFile(zip_path) as zf:
+            for raw in zf.namelist():
+                name = _norm_member(raw)
+                if name.endswith("/"):
+                    continue
+                if name.startswith("source/") or "/source/" in f"/{name}":
+                    return True
+    except (OSError, zipfile.BadZipFile):
+        return False
+    return False
+
+
+def read_volume_manifest(zip_path: Path) -> dict[str, Any] | None:
+    try:
+        with zipfile.ZipFile(zip_path) as zf:
+            names = set(zf.namelist())
+            for member in VOLUME_MANIFEST_MEMBERS:
+                if member not in names:
+                    continue
+                doc = json.loads(zf.read(member).decode("utf-8"))
+                if isinstance(doc, dict):
+                    return doc
+    except (OSError, zipfile.BadZipFile, json.JSONDecodeError, UnicodeDecodeError):
+        return None
+    return None
+
+
+def _int_or_none(value: Any) -> int | None:
+    try:
+        if value is None:
+            return None
+        return int(value)
+    except (TypeError, ValueError):
+        return None
+
+
+def semantic_object(*, content: dict[str, Any], software: dict[str, Any]) -> dict[str, Any]:
+    """Canonical subset used for sidecar vs actual-rerun comparison."""
+    unit = software.get("unit") if isinstance(software.get("unit"), dict) else {}
+    modules: list[dict[str, Any]] = []
+    raw_modules = unit.get("modules") if isinstance(unit.get("modules"), list) else []
+    for mod in raw_modules:
+        if not isinstance(mod, dict):
+            continue
+        modules.append(
+            {
+                "module": str(mod.get("module") or ""),
+                "status": str(mod.get("status") or ""),
+                "returncode": _int_or_none(mod.get("returncode")),
+            }
+        )
+    modules.sort(key=lambda row: row["module"])
+    layout = software.get("layout") if isinstance(software.get("layout"), dict) else {}
+    checks = layout.get("checks") if isinstance(layout.get("checks"), dict) else {}
+    provenance = (
+        software.get("provenance") if isinstance(software.get("provenance"), dict) else {}
+    )
+    board = software.get("board") if isinstance(software.get("board"), dict) else {}
+    return {
+        "checked_files": _int_or_none(content.get("checked_files")) or 0,
+        "git_mode": str(software.get("git_mode") or ""),
+        "layout_status": str(layout.get("status") or ""),
+        "layout_checks": {str(k): checks.get(k) is True for k in sorted(checks)},
+        "provenance": {
+            "status": str(provenance.get("status") or ""),
+            "head_txt": provenance.get("head_txt") is True,
+            "tree_manifest": provenance.get("tree_manifest") is True,
+            "sanitized_snapshot_status": provenance.get("sanitized_snapshot_status") is True,
+            "raw_git_required": provenance.get("raw_git_required") is True,
+        },
+        "unit_status": str(unit.get("status") or ""),
+        "unit_modules": modules,
+        "board": {
+            "status": str(board.get("status") or ""),
+            "mode": str(board.get("mode") or ""),
+            "returncode": _int_or_none(board.get("returncode")),
+            "reference_regeneration_replay": str(
+                board.get("reference_regeneration_replay") or ""
+            ),
+        },
+        "software_status": str(software.get("status") or ""),
+    }
+
+
+def semantic_sha256(obj: dict[str, Any]) -> str:
+    blob = json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode(
+        "utf-8"
+    )
+    return hashlib.sha256(blob).hexdigest()
+
+
+def stamp_replay_semantic(
+    report: dict[str, Any],
+    *,
+    zip_path: Path | None = None,
+) -> dict[str, Any]:
+    content = report.get("package_content") if isinstance(report.get("package_content"), dict) else {}
+    software = (
+        report.get("detached_software")
+        if isinstance(report.get("detached_software"), dict)
+        else {}
+    )
+    if zip_path is not None:
+        align_checked_files_to_manifest(content, zip_path)
+    obj = semantic_object(content=content, software=software)
+    report["replay_semantic"] = obj
+    report["replay_semantic_sha256"] = semantic_sha256(obj)
+    return report
+
+
+def align_checked_files_to_manifest(content: dict[str, Any], zip_path: Path) -> None:
+    """Force package_content.checked_files to VOLUME-MANIFEST.file_count."""
+    manifest = read_volume_manifest(zip_path)
+    if not isinstance(manifest, dict) or "file_count" not in manifest:
+        return
+    count = _int_or_none(manifest.get("file_count"))
+    if count is None:
+        return
+    content["checked_files"] = count
+
+
+def safe_extract_zip(zip_path: Path, dest: Path) -> list[Path]:
+    """Extract regular files only. No extractall; reject zip-slip paths."""
+    dest.mkdir(parents=True, exist_ok=False)
+    dest_res = dest.resolve()
+    written: list[Path] = []
+    with zipfile.ZipFile(zip_path) as zf:
+        for info in zf.infolist():
+            name = _norm_member(info.filename)
+            if not name or name.startswith("/") or re.match(r"^[A-Za-z]:", name):
+                raise ValueError(f"unsafe archive member path: {info.filename!r}")
+            parts = Path(name).parts
+            if ".." in parts:
+                raise ValueError(f"unsafe archive member path: {info.filename!r}")
+            if info.is_dir() or name.endswith("/"):
+                continue
+            target = dest / Path(*parts)
+            resolved = target.resolve()
+            if dest_res not in resolved.parents and resolved != dest_res:
+                raise ValueError(f"zip-slip archive member: {info.filename!r}")
+            target.parent.mkdir(parents=True, exist_ok=True)
+            with zf.open(info, "r") as source, target.open("wb") as out:
+                shutil.copyfileobj(source, out, length=1024 * 1024)
+            written.append(target)
+    return written
+
+
+def verify_volume_manifest_inventory(zip_path: Path) -> list[str]:
+    failures: list[str] = []
+    manifest = read_volume_manifest(zip_path)
+    if not isinstance(manifest, dict):
+        return ["replay_volume_manifest_missing"]
+    files = manifest.get("files") if isinstance(manifest.get("files"), list) else []
+    try:
+        claimed_count = int(manifest.get("file_count"))
+    except (TypeError, ValueError):
+        claimed_count = None
+    if claimed_count is None:
+        failures.append("replay_volume_manifest_missing")
+        return failures
+    if claimed_count != len(files):
+        failures.append("replay_volume_manifest_file_count_mismatch")
+    try:
+        with zipfile.ZipFile(zip_path) as zf:
+            names = {_norm_member(n) for n in zf.namelist() if not n.endswith("/")}
+            for row in files:
+                if not isinstance(row, dict):
+                    failures.append("replay_volume_manifest_inventory_mismatch")
+                    continue
+                rel = _norm_member(str(row.get("archive_path") or row.get("path") or ""))
+                if not rel or rel not in names:
+                    failures.append("replay_volume_manifest_inventory_mismatch")
+                    continue
+                data = zf.read(rel)
+                size = _int_or_none(row.get("size"))
+                if size is not None and size != len(data):
+                    failures.append("replay_volume_manifest_inventory_mismatch")
+                    continue
+                sha = str(row.get("sha256") or "").strip().lower()
+                if sha and sha != hashlib.sha256(data).hexdigest():
+                    failures.append("replay_volume_manifest_inventory_mismatch")
+    except (OSError, zipfile.BadZipFile, KeyError):
+        failures.append("replay_volume_manifest_inventory_mismatch")
+    return list(dict.fromkeys(failures))
+
+
+def _run_actual_software_replay(zip_path: Path) -> dict[str, Any]:
+    try:
+        from replay_review_compact import resolve_cpld_root, run_detached_software_replay
+    except ImportError:
+        from tools.replay_review_compact import (  # type: ignore
+            resolve_cpld_root,
+            run_detached_software_replay,
+        )
+    tmp = Path(tempfile.mkdtemp(prefix="prod2u-replay-bind-"))
+    try:
+        # mkdtemp already created tmp/; extract into a child so mkdir(exist_ok=False) succeeds.
+        dest = tmp / "from-zip"
+        safe_extract_zip(zip_path, dest)
+        cpld = resolve_cpld_root(dest)
+        return run_detached_software_replay(cpld)
+    finally:
+        shutil.rmtree(tmp, ignore_errors=True)
+
+
+def bind_independent_replay(zip_path: Path, sidecar: dict[str, Any]) -> list[str]:
+    """Compare sidecar semantic object to an actual ZIP extract + replay.
+
+    Dummy ZIPs without a source tree skip the independent rerun so unit-test
+    identity fixtures remain completeness-on-sidecar only.
+    """
+    if not review_zip_has_source_tree(zip_path):
+        return []
+    failures = verify_volume_manifest_inventory(zip_path)
+    try:
+        actual_software = _run_actual_software_replay(zip_path)
+    except Exception:  # noqa: BLE001 — bind must fail-closed, not raise
+        failures.append("replay_actual_rerun_error")
+        return list(dict.fromkeys(failures))
+    if str(actual_software.get("status") or "").casefold() != "pass":
+        failures.append("replay_actual_rerun_not_pass")
+
+    content = sidecar.get("package_content") if isinstance(sidecar.get("package_content"), dict) else {}
+    claimed_sw = (
+        sidecar.get("detached_software")
+        if isinstance(sidecar.get("detached_software"), dict)
+        else {}
+    )
+    claimed = semantic_object(content=content, software=claimed_sw)
+    actual = semantic_object(content=content, software=actual_software)
+    manifest = read_volume_manifest(zip_path) or {}
+    actual["checked_files"] = _int_or_none(manifest.get("file_count")) or 0
+
+    if claimed["unit_modules"] != actual["unit_modules"] or claimed["unit_status"] != actual["unit_status"]:
+        failures.append("replay_semantic_unit_mismatch")
+    if claimed["layout_checks"] != actual["layout_checks"] or claimed["layout_status"] != actual["layout_status"]:
+        failures.append("replay_semantic_layout_mismatch")
+    if claimed["provenance"] != actual["provenance"]:
+        failures.append("replay_semantic_provenance_mismatch")
+    if claimed["board"] != actual["board"]:
+        failures.append("replay_semantic_board_mismatch")
+    if claimed["software_status"] != actual["software_status"]:
+        failures.append("replay_semantic_software_status_mismatch")
+    if claimed["git_mode"] and actual["git_mode"] and claimed["git_mode"] != actual["git_mode"]:
+        failures.append("replay_semantic_git_mode_mismatch")
+    if claimed["checked_files"] != actual["checked_files"]:
+        failures.append("replay_semantic_checked_files_mismatch")
+
+    claimed_digest = str(sidecar.get("replay_semantic_sha256") or "").strip().lower()
+    actual_digest = semantic_sha256(actual)
+    if claimed_digest and claimed_digest != actual_digest:
+        failures.append("replay_semantic_sha256_mismatch")
+    return list(dict.fromkeys(failures))