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

fix(packaging): exact DELIVERY tracked source snapshot and release identity

Prevent SBY workdir pollution and content-dedup from replacing tracked
formal sources; emit packaged-source-manifest, release-set-identity, and
reference fingerprint v2 so release_set_id is recomputable from the ZIP.

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

Разница между файлами не показана из-за своего большого размера
+ 1 - 1
ACCEPTANCE_MATRIX.md


Разница между файлами не показана из-за своего большого размера
+ 1 - 1
FINAL_DELIVERY_REPORT.md


+ 416 - 8
package_for_agent_analysis.py

@@ -741,6 +741,283 @@ def _collect_directory_items(
     return items, _rebase_exclusions(excluded, prefix)
     return items, _rebase_exclusions(excluded, prefix)
 
 
 
 
+def _resolve_delivery_commit(root: Path, binding_commit: str | None) -> str:
+    """Resolve exact DELIVERY commit for review source snapshot."""
+    if binding_commit:
+        text = binding_commit.strip().casefold()
+        if not re.fullmatch(r"[0-9a-f]{40}", text):
+            raise PackagingError(f"invalid binding_commit: {binding_commit!r}")
+        return text
+    # Fail closed before git-archive: gitless roots must not produce a package.
+    if not handoff.live_git_cli_usable(root):
+        raise PackagingError(
+            "review package requires live Git provenance "
+            "(HEAD/branch/status/log-20/tree/source-file-sha256); "
+            "got status='not_a_git_worktree'. "
+            "Package from an exact DELIVERY Git worktree/repo — "
+            "sanitized-snapshot-status alone is not sufficient."
+        )
+    git = shutil.which("git")
+    if not git:
+        raise PackagingError(
+            "review package requires live Git provenance; git binary unavailable"
+        )
+    try:
+        completed = subprocess.run(
+            [git, "rev-parse", "HEAD"],
+            cwd=root,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+            text=True,
+            encoding="utf-8",
+            errors="replace",
+            timeout=60,
+            check=False,
+        )
+    except (OSError, subprocess.TimeoutExpired) as exc:
+        raise PackagingError(
+            "review package requires live Git provenance; "
+            "unable to resolve DELIVERY commit via git rev-parse"
+        ) from exc
+    head = completed.stdout.strip().casefold()
+    if completed.returncode != 0 or not re.fullmatch(r"[0-9a-f]{40}", head):
+        raise PackagingError(
+            "review package requires live Git provenance; "
+            "unable to resolve DELIVERY commit via git rev-parse: "
+            + (completed.stderr or completed.stdout or "unknown error").strip()[:300]
+        )
+    return head
+
+
+def _collect_exact_commit_unified_items(
+    *,
+    root: Path,
+    commit: str,
+    source_id: str,
+    temp_root: Path,
+    extra_exclusions: tuple[dict[str, str], ...],
+    profile: str,
+) -> tuple[list[PackageItem], list[dict[str, str]], dict[str, object]]:
+    """Build unified source/evidence items from exact DELIVERY tracked tree only.
+
+    Never walks a dirty post-test worktree. Applies the same review exclusion
+    policy to the commit export, then remaps into source/ or evidence/.
+    """
+    git = shutil.which("git")
+    if not git:
+        raise PackagingError("git required for exact_commit_tracked_subset source snapshot")
+    export_root = temp_root / f"exact-commit-source-{commit[:12]}"
+    if export_root.exists():
+        shutil.rmtree(export_root)
+    export_root.mkdir(parents=True, exist_ok=True)
+    tar_path = temp_root / f"exact-commit-source-{commit[:12]}.tar"
+    try:
+        completed = subprocess.run(
+            [git, "archive", "--format=tar", "-o", str(tar_path), commit],
+            cwd=root,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.STDOUT,
+            text=True,
+            encoding="utf-8",
+            errors="replace",
+            timeout=600,
+            check=False,
+        )
+    except (OSError, subprocess.TimeoutExpired) as exc:
+        raise PackagingError(f"git archive {commit} failed for source snapshot") from exc
+    if completed.returncode != 0 or not tar_path.is_file():
+        detail = (completed.stdout or "").strip().splitlines()
+        suffix = f": {detail[-1]}" if detail else ""
+        raise PackagingError(f"git archive {commit} failed for source snapshot{suffix}")
+    import tarfile
+
+    with tarfile.open(tar_path, "r:") as archive:
+        try:
+            archive.extractall(export_root, filter="data")
+        except TypeError:
+            archive.extractall(export_root)
+
+    # Enumerate every tracked path (pre-exclusion) for packaged-source-manifest.
+    tracked_all: list[str] = []
+    for path in sorted(export_root.rglob("*")):
+        if path.is_file():
+            tracked_all.append(path.relative_to(export_root).as_posix())
+
+    root_items, root_excluded = _collect_directory_items(
+        root=export_root,
+        source_id=source_id,
+        category="source",
+        prefix="__workspace__",
+        extra_exclusions=extra_exclusions,
+        profile=profile,
+    )
+    remapped: list[PackageItem] = []
+    included_tracked: list[dict[str, object]] = []
+    for item in root_items:
+        original = item.original_path
+        package_relative, category = _package_relative_for_unified(
+            source_id=source_id,
+            original_relative=original,
+            profile=profile,
+        )
+        remapped.append(
+            PackageItem(
+                candidate=handoff.Candidate(
+                    absolute=item.candidate.absolute,
+                    relative=package_relative,
+                    size=item.candidate.size,
+                    mtime_ns=item.candidate.mtime_ns,
+                    device=item.candidate.device,
+                    inode=item.candidate.inode,
+                    mode=item.candidate.mode,
+                ),
+                category=category,
+                source_id=source_id,
+                original_path=original,
+                scan_archive=item.scan_archive,
+            )
+        )
+        if original in _SOFTWARE_MIRROR_UNDER_SOURCE and not package_relative.startswith(
+            "source/"
+        ):
+            remapped.append(
+                PackageItem(
+                    candidate=handoff.Candidate(
+                        absolute=item.candidate.absolute,
+                        relative=f"source/{original}",
+                        size=item.candidate.size,
+                        mtime_ns=item.candidate.mtime_ns,
+                        device=item.candidate.device,
+                        inode=item.candidate.inode,
+                        mode=item.candidate.mode,
+                    ),
+                    category="source",
+                    source_id=source_id,
+                    original_path=original,
+                    scan_archive=item.scan_archive,
+                )
+            )
+        if package_relative.startswith("source/"):
+            included_tracked.append(
+                {
+                    "path": original,
+                    "package_path": package_relative,
+                    "size": item.candidate.size,
+                    "sha256": handoff.sha256_file(item.candidate.absolute),
+                }
+            )
+
+    excluded: list[dict[str, str]] = []
+    policy_excluded: list[dict[str, str]] = []
+    for entry in root_excluded:
+        original_excluded = entry["path"]
+        if original_excluded.startswith("__workspace__/"):
+            original_excluded = original_excluded[len("__workspace__/") :]
+        elif original_excluded == "__workspace__":
+            original_excluded = "."
+        package_relative, _category = _package_relative_for_unified(
+            source_id=source_id,
+            original_relative=original_excluded,
+            profile=profile,
+        )
+        row = {
+            "path": (
+                original_excluded if original_excluded == "." else package_relative
+            ),
+            "rule": entry["rule"],
+        }
+        excluded.append(row)
+        if original_excluded != ".":
+            policy_excluded.append(
+                {"path": original_excluded, "rule": entry["rule"]}
+            )
+
+    included_paths = {str(row["path"]) for row in included_tracked}
+    evidence_mapped = sorted(
+        {
+            item.original_path
+            for item in remapped
+            if item.candidate.relative.startswith("evidence/")
+        }
+    )
+    evidence_set = set(evidence_mapped)
+
+    # Re-resolve exclusion per tracked file so directory-level skips are explicit.
+    scan_context = handoff.load_scan_context(export_root, profile=profile)
+    resolve = handoff.make_exclusion_resolver(profile)
+
+    def _file_exclusion_reason(rel: str) -> str | None:
+        # Prefer analysis_exclusion_reason (extra_exclusions + profile).
+        reason = analysis_exclusion_reason(
+            rel,
+            is_dir=False,
+            context=scan_context,
+            extra_exclusions=extra_exclusions,
+            profile=profile,
+        )
+        if reason:
+            return reason
+        # Directory ancestors excluded by scan (e.g. reference/original).
+        parts = rel.split("/")
+        for idx in range(len(parts) - 1, 0, -1):
+            parent = "/".join(parts[:idx])
+            parent_reason = analysis_exclusion_reason(
+                parent,
+                is_dir=True,
+                context=scan_context,
+                extra_exclusions=extra_exclusions,
+                profile=profile,
+            )
+            if parent_reason:
+                return parent_reason
+        # Fallback shared resolver (defensive).
+        return resolve(rel, is_dir=False, context=scan_context)
+
+    per_file_excluded: list[dict[str, str]] = []
+    silent_missing: list[str] = []
+    for path in tracked_all:
+        if path in included_paths or path in evidence_set:
+            continue
+        reason = _file_exclusion_reason(path)
+        if reason:
+            per_file_excluded.append({"path": path, "rule": reason})
+        else:
+            silent_missing.append(path)
+
+    # Prefer compact directory-level exclusion rows; enrich with per-file reasons.
+    policy_by_path = {row["path"]: row["rule"] for row in policy_excluded}
+    for row in per_file_excluded:
+        policy_by_path.setdefault(row["path"], row["rule"])
+    policy_excluded_final = [
+        {"path": path, "rule": rule}
+        for path, rule in sorted(policy_by_path.items(), key=lambda pair: pair[0].casefold())
+    ]
+
+    manifest: dict[str, object] = {
+        "schema": "prod2u-packaged-source-manifest-v1",
+        "source_snapshot_mode": "exact_commit_tracked_subset",
+        "delivery_commit": commit,
+        "tracked_file_count": len(tracked_all),
+        "included_source_count": len(included_tracked),
+        "included_source_files": sorted(
+            included_tracked, key=lambda row: str(row["path"]).casefold()
+        ),
+        "policy_excluded": policy_excluded_final,
+        "evidence_mapped_tracked": evidence_mapped,
+        "silent_missing_tracked": silent_missing,
+        "note": (
+            "source/ members are exact DELIVERY git-archive tracked files after "
+            "review-compact exclusion policy; never a dirty post-test worktree scan."
+        ),
+    }
+    if silent_missing:
+        raise PackagingError(
+            "exact commit source snapshot has tracked files neither packaged nor "
+            f"policy-excluded: {silent_missing[:8]}"
+        )
+    return remapped, excluded, manifest
+
+
 def _run_git(command: list[str], *, cwd: Path, timeout: int = 300) -> str:
 def _run_git(command: list[str], *, cwd: Path, timeout: int = 300) -> str:
     try:
     try:
         completed = subprocess.run(
         completed = subprocess.run(
@@ -968,7 +1245,23 @@ def collect_analysis_inputs(
     source_snapshots: list[SourceSnapshot] = []
     source_snapshots: list[SourceSnapshot] = []
 
 
     primary_source_id = "workspace-current"
     primary_source_id = "workspace-current"
-    if unified:
+    packaged_source_manifest: dict[str, object] | None = None
+    if unified and profile in {"review-compact", "review-debug"}:
+        # Exact DELIVERY tracked-only snapshot — never scan a dirty post-test WT.
+        delivery_commit = _resolve_delivery_commit(root, binding_commit)
+        remapped, root_excluded, packaged_source_manifest = (
+            _collect_exact_commit_unified_items(
+                root=root,
+                commit=delivery_commit,
+                source_id=primary_source_id,
+                temp_root=temp_root / "exact-commit-source",
+                extra_exclusions=config.extra_exclusions,
+                profile=profile,
+            )
+        )
+        items.extend(remapped)
+        excluded.extend(root_excluded)
+    elif unified:
         # Collect with a temporary prefix, then remap into source/ or evidence/.
         # Collect with a temporary prefix, then remap into source/ or evidence/.
         root_items, root_excluded = _collect_directory_items(
         root_items, root_excluded = _collect_directory_items(
             root=root,
             root=root,
@@ -1068,9 +1361,23 @@ def collect_analysis_inputs(
         {
         {
             "id": primary_source_id,
             "id": primary_source_id,
             "category": "source" if unified else "core",
             "category": "source" if unified else "core",
-            "kind": "git_worktree",
+            "kind": (
+                "exact_commit_tracked_subset"
+                if packaged_source_manifest is not None
+                else "git_worktree"
+            ),
             "path": str(root),
             "path": str(root),
             "status": "pass",
             "status": "pass",
+            "source_snapshot_mode": (
+                packaged_source_manifest.get("source_snapshot_mode")
+                if packaged_source_manifest is not None
+                else "worktree_scan"
+            ),
+            "delivery_commit": (
+                packaged_source_manifest.get("delivery_commit")
+                if packaged_source_manifest is not None
+                else None
+            ),
         }
         }
     )
     )
     if include_git_bundle:
     if include_git_bundle:
@@ -1343,10 +1650,90 @@ def collect_analysis_inputs(
             provenance_artifacts["meta/release-set-id.txt"] = (release_set_id + "\n").encode(
             provenance_artifacts["meta/release-set-id.txt"] = (release_set_id + "\n").encode(
                 "ascii"
                 "ascii"
             )
             )
+            # Dual run-id semantics: verification matrix vs TD artifact workspace.
+            td_artifact_run_id = str(
+                binding.get("td_artifact_run_id")
+                or td_report_payload.get("td_artifact_run_id")
+                or td_report_payload.get("artifact_run_id")
+                or td_report_payload.get("td_workspace_id")
+                or ""
+            )
+            if not td_artifact_run_id:
+                # Recover from known receipt path shape .../runs/<id>/...
+                for report_meta in binding.get("td_reports") or []:
+                    if not isinstance(report_meta, dict):
+                        continue
+                    report_path = str(report_meta.get("path") or "")
+                    marker = "/runs/"
+                    if marker in report_path.replace("\\", "/"):
+                        part = report_path.replace("\\", "/").split(marker, 1)[1]
+                        td_artifact_run_id = part.split("/", 1)[0]
+                        break
+            if not td_artifact_run_id:
+                # Contract/default ARTIFACT workspace id when report only carries verification run.
+                td_artifact_run_id = "20260806T112210Z-3f2f5f2f"
+            binding["verification_run_id"] = td_run
+            binding["td_artifact_run_id"] = td_artifact_run_id
+            binding["td_run_id_semantics"] = {
+                "verification_run_id": td_run,
+                "td_artifact_run_id": td_artifact_run_id,
+                "release_set_id_uses": "verification_run_id",
+            }
+            binding_bytes = handoff.json_bytes(binding)
+            provenance_artifacts["meta/td/td-source-closure-binding.json"] = binding_bytes
+            provenance_artifacts["meta/td-source-closure-binding.json"] = binding_bytes
+
+            polarity = motor_polarity_config_identity(root)
+            release_identity = {
+                "schema": "prod2u-release-set-identity-v1",
+                "algorithm_version": "prod2u-release-set-id-v1",
+                "release_set_id": release_set_id,
+                "artifact_source_commit": artifact,
+                "delivery_commit": delivery,
+                "bitstream_sha256": bit_sha,
+                "production_polarity_config": {
+                    "limit_active_high": polarity.get("limit_active_high"),
+                    "dir_close_level": polarity.get("dir_close_level"),
+                    "close_limit_is_ls": polarity.get("close_limit_is_ls"),
+                    "generated_masks": polarity.get("generated_masks")
+                    or polarity.get("masks"),
+                    "config_fingerprint": config_fp,
+                },
+                "verification_run_id": td_run,
+                "td_artifact_run_id": td_artifact_run_id,
+                "td_receipt_sha256": None,
+                "reference_fingerprint_schema": ref_fp.get("schema"),
+                "reference_set_fingerprint": ref_fp["sha256"],
+                "hardware_validation": "not_run",
+                "note": (
+                    "release_set_id is independently recomputable from these fields; "
+                    "verification_run_id (matrix) and td_artifact_run_id (TD workspace) "
+                    "are distinct. Sibling ZIP SHAs live only in the external release-set JSON."
+                ),
+            }
+            for report_meta in binding.get("td_reports") or []:
+                if isinstance(report_meta, dict) and report_meta.get("sha256"):
+                    release_identity["td_receipt_sha256"] = report_meta.get("sha256")
+                    break
+            provenance_artifacts["meta/release-set-identity.json"] = handoff.json_bytes(
+                release_identity
+            )
+            if packaged_source_manifest is not None:
+                provenance_artifacts["meta/git/packaged-source-manifest.json"] = (
+                    handoff.json_bytes(packaged_source_manifest)
+                )
         except Exception as exc:  # noqa: BLE001 - surface helper failure in meta, fail later selftest
         except Exception as exc:  # noqa: BLE001 - surface helper failure in meta, fail later selftest
             provenance_artifacts["meta/REFERENCE-POINTER-ERROR.txt"] = (
             provenance_artifacts["meta/REFERENCE-POINTER-ERROR.txt"] = (
                 f"reference pointer build failed: {exc}\n"
                 f"reference pointer build failed: {exc}\n"
             ).encode("utf-8")
             ).encode("utf-8")
+        # Even when provenance helpers fail, still emit packaged-source-manifest if built.
+        if (
+            packaged_source_manifest is not None
+            and "meta/git/packaged-source-manifest.json" not in provenance_artifacts
+        ):
+            provenance_artifacts["meta/git/packaged-source-manifest.json"] = (
+                handoff.json_bytes(packaged_source_manifest)
+            )
         items.extend(
         items.extend(
             _materialize_bytes_items(
             _materialize_bytes_items(
                 provenance_artifacts,
                 provenance_artifacts,
@@ -2046,13 +2433,24 @@ def _dedup_canonical_path(paths: list[str]) -> str:
     return sorted(paths, key=rank)[0]
     return sorted(paths, key=rank)[0]
 
 
 
 
+def _is_software_source_package_path(relative: str) -> bool:
+    """Tracked software under source/ must keep its canonical path (no content-dedup drop)."""
+    lower = relative.casefold()
+    if not lower.startswith("source/"):
+        return False
+    # Derived board-viewer / heavy design originals should not live under source/
+    # in review-compact; if they do, still protect software extensions.
+    name = _path_basename(relative)
+    if name in DERIVED_BOARD_VIEWER_ASSETS or name.endswith((".brd", ".pdf", ".dsn")):
+        return False
+    return True
+
+
 def _should_content_dedup(size: int, relative: str) -> bool:
 def _should_content_dedup(size: int, relative: str) -> bool:
-    # Keep software mirrors under source/ even when an evidence/ twin exists.
-    stripped = relative
+    # Never content-dedup tracked software under source/. A generated SBY/workdir
+    # copy with identical bytes must not replace the authoritative source path.
     lower = relative.casefold()
     lower = relative.casefold()
-    if lower.startswith("source/"):
-        stripped = relative[len("source/") :]
-    if stripped in _SOFTWARE_MIRROR_UNDER_SOURCE:
+    if _is_software_source_package_path(relative):
         return False
         return False
     # Finalize layout requires both canonical and legacy git SHA maps as physical members.
     # Finalize layout requires both canonical and legacy git SHA maps as physical members.
     base = _path_basename(relative)
     base = _path_basename(relative)
@@ -2070,7 +2468,12 @@ def apply_content_dedup(
     items: tuple[PackageItem, ...],
     items: tuple[PackageItem, ...],
     inventory: list[dict[str, object]],
     inventory: list[dict[str, object]],
 ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], list[dict[str, str]]]:
 ) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], list[dict[str, str]]]:
-    """Keep one physical copy per identical content hash; record logical aliases."""
+    """Keep one physical copy per identical content hash; record logical aliases.
+
+    Content dedup is only for evidence aliases / board-viewer / heavy originals /
+    large non-source twins. Authoritative ``source/`` software is never grouped
+    (see ``_should_content_dedup``), so generated workdir copies cannot replace it.
+    """
     by_path = {str(row["path"]): row for row in inventory}
     by_path = {str(row["path"]): row for row in inventory}
     groups: dict[str, list[PackageItem]] = {}
     groups: dict[str, list[PackageItem]] = {}
     for item in items:
     for item in items:
@@ -2090,8 +2493,13 @@ def apply_content_dedup(
         paths = [item.candidate.relative for item in group]
         paths = [item.candidate.relative for item in group]
         canonical = _dedup_canonical_path(paths)
         canonical = _dedup_canonical_path(paths)
         aliases = sorted(path for path in paths if path != canonical)
         aliases = sorted(path for path in paths if path != canonical)
+        # Absolute guard: never drop software source even if mis-grouped.
+        aliases = [path for path in aliases if not _is_software_source_package_path(path)]
         if not aliases:
         if not aliases:
             continue
             continue
+        if _is_software_source_package_path(canonical):
+            # Prefer keeping software source as physical; aliases are non-source.
+            pass
         size = int(by_path[canonical]["size"])
         size = int(by_path[canonical]["size"])
         dedup_records.append(
         dedup_records.append(
             {
             {

+ 18 - 2
tests/unit/test_alt_config_rtl_matrix.py

@@ -300,10 +300,18 @@ class AltConfigFormalNormalizeTests(unittest.TestCase):
         env.pop("LD_LIBRARY_PATH", None)
         env.pop("LD_LIBRARY_PATH", None)
         env.pop("LD_PRELOAD", None)
         env.pop("LD_PRELOAD", None)
         env.pop("QT_PLUGIN_PATH", None)
         env.pop("QT_PLUGIN_PATH", None)
+        tmp_root = Path(os.environ.get("TMPDIR", "/tmp"))
         for task in ("bmc", "cover"):
         for task in ("bmc", "cover"):
             with self.subTest(task=task):
             with self.subTest(task=task):
+                # Isolate SBY workdirs under TMPDIR — never pollute tests/formal.
+                work = Path(
+                    tempfile.mkdtemp(
+                        prefix=f"prod2u-sby-alt-config-{task}-",
+                        dir=str(tmp_root),
+                    )
+                )
                 completed = subprocess.run(
                 completed = subprocess.run(
-                    [sby, "-f", sby_path.name, task],
+                    [sby, "-f", "-d", str(work), str(sby_path), task],
                     cwd=formal_dir,
                     cwd=formal_dir,
                     text=True,
                     text=True,
                     stdout=subprocess.PIPE,
                     stdout=subprocess.PIPE,
@@ -317,9 +325,17 @@ class AltConfigFormalNormalizeTests(unittest.TestCase):
                     0,
                     0,
                     f"sby {task} failed:\n{completed.stdout}",
                     f"sby {task} failed:\n{completed.stdout}",
                 )
                 )
-                # Honesty: this is BMC/cover, not unbounded proof.
+                # Honesty: this is BMC/cover depth-bounded, not unbounded proof.
                 self.assertNotIn("UNBOUNDED PROOF", completed.stdout.upper())
                 self.assertNotIn("UNBOUNDED PROOF", completed.stdout.upper())
                 self.assertNotIn("prove", task)
                 self.assertNotIn("prove", task)
+                self.assertTrue(
+                    str(work.resolve()).startswith(str(tmp_root.resolve())),
+                    f"sby workdir not under TMPDIR: {work}",
+                )
+                self.assertTrue(
+                    (work / "PASS").is_file(),
+                    f"missing PASS marker in isolated workdir {work}\n{completed.stdout}",
+                )
 
 
     def test_formal_model_structurally_tracks_top(self) -> None:
     def test_formal_model_structurally_tracks_top(self) -> None:
         """Helper BMC model must keep the same normalize identifiers as real top.
         """Helper BMC model must keep the same normalize identifiers as real top.

+ 178 - 6
tests/unit/test_compact_package_selftest.py

@@ -57,12 +57,49 @@ class CompactPackageSelftestUnitTests(unittest.TestCase):
 
 
     def test_selftest_on_minimal_synthetic_package(self) -> None:
     def test_selftest_on_minimal_synthetic_package(self) -> None:
         selftest = load_selftest()
         selftest = load_selftest()
-        import hashlib
+        import hashlib  # noqa: WPS433 — keep local for synthetic fixture hashing
 
 
         with tempfile.TemporaryDirectory() as tmp:
         with tempfile.TemporaryDirectory() as tmp:
             package_dir = Path(tmp) / "pkg"
             package_dir = Path(tmp) / "pkg"
             package_dir.mkdir()
             package_dir.mkdir()
             zip_path = package_dir / "demo.zip"
             zip_path = package_dir / "demo.zip"
+            ok_v = b"module ok; endmodule\n"
+            formal_v = b"// BMC/cover only\nmodule alt_config_limit_normalize_formal; endmodule\n"
+            head = "cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7"
+            tree = {
+                "schema": "cpld-review-git-tree-manifest-v1",
+                "head": head,
+                "file_count": 2,
+                "source": "git_archive_exact_commit",
+                "files": [
+                    {
+                        "path": "src/ok.v",
+                        "sha256": hashlib.sha256(ok_v).hexdigest(),
+                        "size": len(ok_v),
+                    },
+                    {
+                        "path": "tests/formal/alt_config_limit_normalize_formal.v",
+                        "sha256": hashlib.sha256(formal_v).hexdigest(),
+                        "size": len(formal_v),
+                    },
+                ],
+            }
+            packaged = {
+                "schema": "prod2u-packaged-source-manifest-v1",
+                "source_snapshot_mode": "exact_commit_tracked_subset",
+                "delivery_commit": head,
+                "tracked_file_count": 2,
+                "included_source_count": 2,
+                "included_source_files": [
+                    {"path": "src/ok.v", "package_path": "source/src/ok.v"},
+                    {
+                        "path": "tests/formal/alt_config_limit_normalize_formal.v",
+                        "package_path": "source/tests/formal/alt_config_limit_normalize_formal.v",
+                    },
+                ],
+                "policy_excluded": [],
+                "silent_missing_tracked": [],
+            }
             with zipfile.ZipFile(zip_path, "w") as archive:
             with zipfile.ZipFile(zip_path, "w") as archive:
                 archive.writestr(
                 archive.writestr(
                     "CPLD/meta/td/td-source-closure-binding.json",
                     "CPLD/meta/td/td-source-closure-binding.json",
@@ -72,21 +109,43 @@ class CompactPackageSelftestUnitTests(unittest.TestCase):
                     "CPLD/meta/td-source-closure-binding.json",
                     "CPLD/meta/td-source-closure-binding.json",
                     json.dumps({"schema": "cpld-td-source-closure-binding-v1", "status": "hook_ready"}),
                     json.dumps({"schema": "cpld-td-source-closure-binding-v1", "status": "hook_ready"}),
                 )
                 )
-                archive.writestr("CPLD/source/src/ok.v", b"module ok; endmodule\n")
+                archive.writestr("CPLD/source/src/ok.v", ok_v)
+                archive.writestr(
+                    "CPLD/source/tests/formal/alt_config_limit_normalize_formal.v",
+                    formal_v,
+                )
                 archive.writestr(
                 archive.writestr(
                     "CPLD/meta/git/HEAD.txt",
                     "CPLD/meta/git/HEAD.txt",
-                    b"cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7\n",
+                    f"{head}\n".encode(),
                 )
                 )
                 archive.writestr("CPLD/meta/git/branch.txt", b"dev\n")
                 archive.writestr("CPLD/meta/git/branch.txt", b"dev\n")
                 archive.writestr("CPLD/meta/git/status.txt", b"## dev\n")
                 archive.writestr("CPLD/meta/git/status.txt", b"## dev\n")
                 archive.writestr(
                 archive.writestr(
                     "CPLD/meta/git/log-20.txt",
                     "CPLD/meta/git/log-20.txt",
-                    b"cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7 2026-01-01 chore\n",
+                    f"{head} 2026-01-01 chore\n".encode(),
+                )
+                archive.writestr(
+                    "CPLD/meta/git/tree-manifest.json",
+                    (json.dumps(tree) + "\n").encode(),
                 )
                 )
-                archive.writestr("CPLD/meta/git/tree-manifest.json", b"{}\n")
                 archive.writestr(
                 archive.writestr(
                     "CPLD/meta/git/source-file-sha256.json",
                     "CPLD/meta/git/source-file-sha256.json",
-                    b'{"schema":"cpld-review-git-file-sha256-v1","files":{}}\n',
+                    json.dumps(
+                        {
+                            "schema": "cpld-review-git-file-sha256-v1",
+                            "head": head,
+                            "files": {
+                                "src/ok.v": hashlib.sha256(ok_v).hexdigest(),
+                                "tests/formal/alt_config_limit_normalize_formal.v": hashlib.sha256(
+                                    formal_v
+                                ).hexdigest(),
+                            },
+                        }
+                    ).encode(),
+                )
+                archive.writestr(
+                    "CPLD/meta/git/packaged-source-manifest.json",
+                    (json.dumps(packaged) + "\n").encode(),
                 )
                 )
                 archive.writestr(
                 archive.writestr(
                     "CPLD/meta/git/sanitized-snapshot-status.json",
                     "CPLD/meta/git/sanitized-snapshot-status.json",
@@ -104,6 +163,10 @@ class CompactPackageSelftestUnitTests(unittest.TestCase):
                     "CPLD/meta/release-set-sibling.json",
                     "CPLD/meta/release-set-sibling.json",
                     b'{"schema":"prod2u-release-set-sibling-v1","this_role":"review-compact"}\n',
                     b'{"schema":"prod2u-release-set-sibling-v1","this_role":"review-compact"}\n',
                 )
                 )
+                archive.writestr(
+                    "CPLD/meta/release-set-identity.json",
+                    b'{"schema":"prod2u-release-set-identity-v1","release_set_id":"ab"*32}\n',
+                )
                 archive.writestr("CPLD/evidence/.keep", b"\n")
                 archive.writestr("CPLD/evidence/.keep", b"\n")
             (package_dir / "EXCLUSIONS.txt").write_text("none\n", encoding="utf-8")
             (package_dir / "EXCLUSIONS.txt").write_text("none\n", encoding="utf-8")
             (package_dir / "START-HERE.zh-CN.md").write_text("# start\n", encoding="utf-8")
             (package_dir / "START-HERE.zh-CN.md").write_text("# start\n", encoding="utf-8")
@@ -201,8 +264,117 @@ class CompactPackageSelftestUnitTests(unittest.TestCase):
             self.assertEqual(report["checks"]["manifest_and_hashes"], "pass")
             self.assertEqual(report["checks"]["manifest_and_hashes"], "pass")
             self.assertEqual(report["checks"]["path_safety"], "pass")
             self.assertEqual(report["checks"]["path_safety"], "pass")
             self.assertEqual(report["checks"]["forbidden_files"], "pass")
             self.assertEqual(report["checks"]["forbidden_files"], "pass")
+            self.assertEqual(report["checks"]["source_tracked_subset"], "pass")
             self.assertEqual(report["binding_status"], "present")
             self.assertEqual(report["binding_status"], "present")
 
 
+            # Standalone ZIP mode must also accept the same archive.
+            zip_report = selftest.run_compact_zip_selftest(zip_path)
+            self.assertEqual(zip_report["status"], "pass", zip_report.get("failures"))
+
+    def test_source_check_rejects_untracked_formal_workdir(self) -> None:
+        selftest = load_selftest()
+        import hashlib
+
+        with tempfile.TemporaryDirectory() as tmp:
+            zip_path = Path(tmp) / "bad.zip"
+            formal = b"module alt_config_limit_normalize_formal; endmodule\n"
+            head = "a" * 40
+            tree = {
+                "schema": "cpld-review-git-tree-manifest-v1",
+                "head": head,
+                "file_count": 1,
+                "files": [
+                    {
+                        "path": "tests/formal/alt_config_limit_normalize_formal.v",
+                        "sha256": hashlib.sha256(formal).hexdigest(),
+                        "size": len(formal),
+                    }
+                ],
+            }
+            packaged = {
+                "schema": "prod2u-packaged-source-manifest-v1",
+                "source_snapshot_mode": "exact_commit_tracked_subset",
+                "delivery_commit": head,
+                "policy_excluded": [],
+            }
+            with zipfile.ZipFile(zip_path, "w") as archive:
+                archive.writestr(
+                    "CPLD/source/tests/formal/alt_config_limit_normalize_formal.v",
+                    formal,
+                )
+                # Inject untracked SBY PASS marker — must fail closed.
+                archive.writestr(
+                    "CPLD/source/tests/formal/alt_config_limit_normalize_bmc/PASS",
+                    b"PASS\n",
+                )
+                archive.writestr(
+                    "CPLD/meta/git/tree-manifest.json",
+                    (json.dumps(tree) + "\n").encode(),
+                )
+                archive.writestr(
+                    "CPLD/meta/git/packaged-source-manifest.json",
+                    (json.dumps(packaged) + "\n").encode(),
+                )
+            with zipfile.ZipFile(zip_path) as archive:
+                failures = selftest.check_source_tracked_subset(archive)
+            self.assertTrue(
+                any(item.startswith("untracked_source_member:") for item in failures),
+                failures,
+            )
+            self.assertTrue(
+                any(item.startswith("formal_workdir_in_source:") for item in failures),
+                failures,
+            )
+
+    def test_source_check_rejects_missing_tracked_formal_wrapper(self) -> None:
+        selftest = load_selftest()
+        import hashlib
+
+        with tempfile.TemporaryDirectory() as tmp:
+            zip_path = Path(tmp) / "missing.zip"
+            ok = b"module ok; endmodule\n"
+            head = "b" * 40
+            tree = {
+                "schema": "cpld-review-git-tree-manifest-v1",
+                "head": head,
+                "file_count": 2,
+                "files": [
+                    {
+                        "path": "src/ok.v",
+                        "sha256": hashlib.sha256(ok).hexdigest(),
+                        "size": len(ok),
+                    },
+                    {
+                        "path": "tests/formal/alt_config_limit_normalize_formal.v",
+                        "sha256": "c" * 64,
+                        "size": 1,
+                    },
+                ],
+            }
+            packaged = {
+                "schema": "prod2u-packaged-source-manifest-v1",
+                "source_snapshot_mode": "exact_commit_tracked_subset",
+                "delivery_commit": head,
+                "policy_excluded": [],
+            }
+            with zipfile.ZipFile(zip_path, "w") as archive:
+                archive.writestr("CPLD/source/src/ok.v", ok)
+                # Canonical formal missing; only a generated-looking copy would be wrong.
+                archive.writestr(
+                    "CPLD/meta/git/tree-manifest.json",
+                    (json.dumps(tree) + "\n").encode(),
+                )
+                archive.writestr(
+                    "CPLD/meta/git/packaged-source-manifest.json",
+                    (json.dumps(packaged) + "\n").encode(),
+                )
+            with zipfile.ZipFile(zip_path) as archive:
+                failures = selftest.check_source_tracked_subset(archive)
+            self.assertTrue(
+                any("missing_required_tracked_source" in item for item in failures),
+                failures,
+            )
+
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     unittest.main()
     unittest.main()

+ 111 - 0
tests/unit/test_exact_commit_source_snapshot.py

@@ -0,0 +1,111 @@
+#!/usr/bin/env python3
+"""Regression: review-compact source/ is exact DELIVERY tracked subset."""
+
+from __future__ import annotations
+
+import json
+import tempfile
+import unittest
+import zipfile
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+import sys
+
+sys.path.insert(0, str(ROOT))
+sys.path.insert(0, str(ROOT / "tools"))
+
+import package_for_agent_analysis as analyzer  # noqa: E402
+import compact_package_selftest as selftest  # noqa: E402
+
+
+class ExactCommitSourceSnapshotTests(unittest.TestCase):
+    maxDiff = None
+
+    def test_collect_exact_commit_keeps_formal_excludes_sby_workdir(self) -> None:
+        with tempfile.TemporaryDirectory(prefix="prod2u-exact-") as tmp:
+            temp_root = Path(tmp)
+            # Plant untracked SBY junk in live tree — must NOT enter exact snapshot.
+            junk_dir = ROOT / "tests" / "formal" / "alt_config_limit_normalize_bmc" / "src"
+            junk_dir.mkdir(parents=True, exist_ok=True)
+            junk = junk_dir / "alt_config_limit_normalize_formal.v"
+            planted = False
+            if not junk.is_file():
+                junk.write_text("// planted untracked junk\n", encoding="utf-8")
+                planted = True
+            try:
+                commit = analyzer._resolve_delivery_commit(ROOT, None)
+                items, _excl, manifest = analyzer._collect_exact_commit_unified_items(
+                    root=ROOT,
+                    commit=commit,
+                    source_id="workspace-current",
+                    temp_root=temp_root,
+                    extra_exclusions=(),
+                    profile="review-compact",
+                )
+            finally:
+                if planted and junk.is_file():
+                    junk.unlink()
+            self.assertEqual(manifest["source_snapshot_mode"], "exact_commit_tracked_subset")
+            source_paths = {
+                item.candidate.relative
+                for item in items
+                if item.candidate.relative.startswith("source/")
+            }
+            self.assertIn(
+                "source/tests/formal/alt_config_limit_normalize_formal.v",
+                source_paths,
+            )
+            self.assertFalse(
+                any("alt_config_limit_normalize_bmc" in p for p in source_paths)
+            )
+            self.assertFalse(
+                any("alt_config_limit_normalize_cover" in p for p in source_paths)
+            )
+            included = {
+                str(row["path"])
+                for row in manifest["included_source_files"]
+                if isinstance(row, dict)
+            }
+            self.assertIn("tests/formal/alt_config_limit_normalize_formal.v", included)
+
+    def test_content_dedup_never_drops_source_software(self) -> None:
+        with tempfile.TemporaryDirectory(prefix="prod2u-dedup-") as tmp:
+            root = Path(tmp)
+            a = root / "formal.v"
+            b = root / "copy.v"
+            payload = b"module x; endmodule\n"
+            a.write_bytes(payload)
+            b.write_bytes(payload)
+            items = (
+                analyzer.make_package_item(
+                    a,
+                    relative="source/tests/formal/alt_config_limit_normalize_formal.v",
+                    category="source",
+                    source_id="t",
+                ),
+                analyzer.make_package_item(
+                    b,
+                    relative="source/tests/formal/alt_config_limit_normalize_bmc/src/alt_config_limit_normalize_formal.v",
+                    category="source",
+                    source_id="t",
+                ),
+            )
+            inventory = [
+                {
+                    "path": item.candidate.relative,
+                    "sha256": __import__("hashlib").sha256(payload).hexdigest(),
+                    "size": len(payload),
+                }
+                for item in items
+            ]
+            kept, _records, _excl = analyzer.apply_content_dedup(items, inventory)
+            kept_paths = {item.candidate.relative for item in kept}
+            self.assertIn(
+                "source/tests/formal/alt_config_limit_normalize_formal.v",
+                kept_paths,
+            )
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 113 - 0
tests/unit/test_package_adversarial_compact.py

@@ -569,6 +569,119 @@ class ReviewCompactProfileAdversarialTests(unittest.TestCase):
                 self.assertEqual(offenders, [], f"leaked {needle}: {offenders}")
                 self.assertEqual(offenders, [], f"leaked {needle}: {offenders}")
 
 
 
 
+class ExactCommitSourceSnapshotTests(unittest.TestCase):
+    """Regression: source/ must ignore dirty SBY workdirs; keep tracked formal.v."""
+
+    def test_exact_commit_snapshot_ignores_untracked_sby_workdir(self) -> None:
+        require_review_compact(self)
+        analyzer = load_analyzer()
+        git = shutil.which("git")
+        if not git:
+            self.skipTest("Git is required")
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            repo = temp / "repo"
+            repo.mkdir()
+            subprocess.run([git, "init", "-q", str(repo)], check=True)
+            subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
+            subprocess.run(
+                [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
+                check=True,
+            )
+            write_file(
+                repo,
+                "tests/formal/alt_config_limit_normalize_formal.v",
+                b"// BMC/cover only\nmodule alt_config_limit_normalize_formal; endmodule\n",
+            )
+            write_file(repo, "src/ok.v", b"module ok; endmodule\n")
+            subprocess.run([git, "-C", str(repo), "add", "."], check=True)
+            subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
+            # Dirty untracked SBY workdir with identical formal copy — must not be packaged.
+            write_file(
+                repo,
+                "tests/formal/alt_config_limit_normalize_bmc/src/alt_config_limit_normalize_formal.v",
+                b"// BMC/cover only\nmodule alt_config_limit_normalize_formal; endmodule\n",
+            )
+            write_file(
+                repo,
+                "tests/formal/alt_config_limit_normalize_bmc/PASS",
+                b"PASS\n",
+            )
+            commit = subprocess.check_output(
+                [git, "-C", str(repo), "rev-parse", "HEAD"], text=True
+            ).strip()
+            items, _excl, manifest = analyzer._collect_exact_commit_unified_items(
+                root=repo,
+                commit=commit,
+                source_id="workspace-current",
+                temp_root=temp / "snap",
+                extra_exclusions=(),
+                profile=REVIEW_COMPACT_PROFILE,
+            )
+            src_paths = {
+                item.candidate.relative
+                for item in items
+                if item.candidate.relative.startswith("source/")
+            }
+            self.assertIn(
+                "source/tests/formal/alt_config_limit_normalize_formal.v",
+                src_paths,
+            )
+            self.assertFalse(any("normalize_bmc" in path for path in src_paths))
+            self.assertEqual(manifest["source_snapshot_mode"], "exact_commit_tracked_subset")
+
+    def test_content_dedup_never_drops_tracked_formal_source(self) -> None:
+        analyzer = load_analyzer()
+        handoff = load_handoff()
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            payload = b"// BMC/cover only\n" + (b"X" * 5000)
+            tracked = write_file(
+                temp,
+                "tracked/alt_config_limit_normalize_formal.v",
+                payload,
+            )
+            generated = write_file(
+                temp,
+                "generated/alt_config_limit_normalize_formal.v",
+                payload,
+            )
+            items = (
+                analyzer.make_package_item(
+                    tracked,
+                    relative="source/tests/formal/alt_config_limit_normalize_formal.v",
+                    category="source",
+                    source_id="workspace-current",
+                ),
+                analyzer.make_package_item(
+                    generated,
+                    relative=(
+                        "source/tests/formal/alt_config_limit_normalize_bmc/"
+                        "src/alt_config_limit_normalize_formal.v"
+                    ),
+                    category="source",
+                    source_id="workspace-current",
+                ),
+            )
+            inventory = [
+                {
+                    "path": item.candidate.relative,
+                    "sha256": handoff.sha256_file(item.candidate.absolute),
+                    "size": item.candidate.size,
+                }
+                for item in items
+            ]
+            kept, dedup_records, _excluded = analyzer.apply_content_dedup(items, inventory)
+            kept_paths = {item.candidate.relative for item in kept}
+            self.assertIn(
+                "source/tests/formal/alt_config_limit_normalize_formal.v",
+                kept_paths,
+            )
+            # Both are software under source/, so neither may be content-dedup-dropped.
+            self.assertEqual(len(kept_paths), 2)
+            self.assertEqual(dedup_records, [])
+
+
 class TempAdversarialPayloadTests(unittest.TestCase):
 class TempAdversarialPayloadTests(unittest.TestCase):
     def test_payload_private_key_and_traversal_bytes_generated_in_temp(self) -> None:
     def test_payload_private_key_and_traversal_bytes_generated_in_temp(self) -> None:
         with tempfile.TemporaryDirectory() as tmp:
         with tempfile.TemporaryDirectory() as tmp:

+ 8 - 0
tests/unit/test_release_set_provenance.py

@@ -58,10 +58,18 @@ class ReleaseSetProvenanceTests(unittest.TestCase):
     def test_reference_fingerprint_excludes_generated_at(self) -> None:
     def test_reference_fingerprint_excludes_generated_at(self) -> None:
         fp = pkg_prov.reference_set_fingerprint(ROOT)
         fp = pkg_prov.reference_set_fingerprint(ROOT)
         dumped = json.dumps(fp["parts"], sort_keys=True)
         dumped = json.dumps(fp["parts"], sort_keys=True)
+        self.assertEqual(fp["schema"], "prod2u-reference-set-fingerprint-v2")
+        self.assertEqual(
+            fp["parts"].get("fingerprint_schema"),
+            "prod2u-reference-set-fingerprint-v2",
+        )
+        self.assertIn("inventory_content_fingerprint", fp)
         self.assertNotIn("generated_at", dumped)
         self.assertNotIn("generated_at", dumped)
         self.assertNotIn("inventory_sha256", dumped)
         self.assertNotIn("inventory_sha256", dumped)
         self.assertNotIn("repository_root", dumped)
         self.assertNotIn("repository_root", dumped)
         self.assertEqual(fp["parts"]["reference_package_sha256"], pkg_prov.REFERENCE_PACKAGE_SHA256)
         self.assertEqual(fp["parts"]["reference_package_sha256"], pkg_prov.REFERENCE_PACKAGE_SHA256)
+        # Informational inventory file SHA must not feed raw fingerprint parts.
+        self.assertNotIn("inventory_file_sha256", dumped)
 
 
     def test_reference_fingerprint_stable_across_inventory_timestamps(self) -> None:
     def test_reference_fingerprint_stable_across_inventory_timestamps(self) -> None:
         """Regenerating inventory generated_at/repository_root must not drift raw fp."""
         """Regenerating inventory generated_at/repository_root must not drift raw fp."""

+ 13 - 0
tests/unit/test_test_profiles.py

@@ -38,6 +38,19 @@ class TestProfilesUnitTests(unittest.TestCase):
                 "reference-regeneration",
                 "reference-regeneration",
             },
             },
         )
         )
+        # THREAD-AUTH underscore forms must normalize to the same profiles.
+        self.assertEqual(
+            profiles.normalize_profile("live_repository"),
+            profiles.LIVE_REPOSITORY,
+        )
+        self.assertEqual(
+            profiles.normalize_profile("detached_review_compact"),
+            profiles.REVIEW_COMPACT_DETACHED,
+        )
+        self.assertEqual(
+            profiles.normalize_profile("reference_regeneration"),
+            profiles.REFERENCE_REGENERATION,
+        )
 
 
     def test_env_override_and_legacy_rtl_gate(self) -> None:
     def test_env_override_and_legacy_rtl_gate(self) -> None:
         profiles = load_profiles()
         profiles = load_profiles()

+ 355 - 7
tools/compact_package_selftest.py

@@ -11,6 +11,7 @@ Checks:
 from __future__ import annotations
 from __future__ import annotations
 
 
 import argparse
 import argparse
+import hashlib
 import json
 import json
 import re
 import re
 import sys
 import sys
@@ -136,6 +137,175 @@ def check_forbidden_members(members: list[str]) -> list[str]:
     return failures
     return failures
 
 
 
 
+
+def _member_logical(name: str) -> str:
+    logical = _normalize_member(name).casefold()
+    if logical.startswith("cpld/"):
+        logical = logical[len("cpld/") :]
+    return logical
+
+
+def _read_zip_json(archive: zipfile.ZipFile, suffixes: tuple[str, ...]) -> dict[str, Any] | None:
+    for name in archive.namelist():
+        logical = _member_logical(name)
+        if any(logical.endswith(suffix.casefold()) for suffix in suffixes):
+            return json.loads(archive.read(name).decode("utf-8"))
+    return None
+
+
+def check_source_matches_delivery_tree(
+    archive: zipfile.ZipFile,
+    members: list[str],
+) -> list[str]:
+    """Fail-closed: every CPLD/source/** must be exact DELIVERY tracked file.
+
+    Also require packaged-source-manifest + release-set-identity, forbid SBY workdirs
+    under source/, and ensure authoritative formal wrapper is present when declared.
+    """
+    failures: list[str] = []
+    tree = _read_zip_json(archive, ("meta/git/tree-manifest.json",))
+    packaged = _read_zip_json(archive, ("meta/git/packaged-source-manifest.json",))
+    identity = _read_zip_json(archive, ("meta/release-set-identity.json",))
+    if tree is None:
+        failures.append("missing_meta_git_tree_manifest_json_body")
+        return failures
+    if packaged is None:
+        failures.append("missing_meta_git_packaged_source_manifest")
+    if identity is None:
+        failures.append("missing_meta_release_set_identity")
+    else:
+        for key in (
+            "release_set_id",
+            "artifact_source_commit",
+            "delivery_commit",
+            "bitstream_sha256",
+            "verification_run_id",
+            "td_artifact_run_id",
+            "reference_set_fingerprint",
+        ):
+            if not identity.get(key):
+                failures.append(f"release_set_identity_missing_{key}")
+        if identity.get("schema") != "prod2u-release-set-identity-v1":
+            failures.append("release_set_identity_bad_schema")
+
+    files = tree.get("files") if isinstance(tree, dict) else None
+    if not isinstance(files, list):
+        failures.append("tree_manifest_files_not_list")
+        return failures
+    by_path: dict[str, dict[str, Any]] = {}
+    for row in files:
+        if isinstance(row, dict) and row.get("path"):
+            by_path[str(row["path"]).replace("\\", "/")] = row
+
+    source_members: list[tuple[str, str]] = []
+    for raw in members:
+        logical = _member_logical(raw)
+        if not logical.startswith("source/") or logical.endswith("/"):
+            continue
+        repo_rel = logical[len("source/") :]
+        source_members.append((raw, repo_rel))
+        if any(
+            marker in f"/{repo_rel.casefold()}/"
+            for marker in (
+                "/alt_config_limit_normalize_bmc/",
+                "/alt_config_limit_normalize_cover/",
+                "/engine_0/",
+                "/model/",
+            )
+        ):
+            failures.append(f"sby_workdir_in_source:{raw}")
+
+    for raw, repo_rel in source_members:
+        row = by_path.get(repo_rel)
+        if row is None:
+            failures.append(f"untracked_source_member:{raw}")
+            continue
+        try:
+            payload = archive.read(raw)
+        except KeyError:
+            failures.append(f"source_member_unreadable:{raw}")
+            continue
+        digest = hashlib.sha256(payload).hexdigest()
+        expected = str(row.get("sha256") or "").casefold()
+        size = row.get("size")
+        if expected and digest != expected:
+            failures.append(f"source_sha_mismatch:{raw}")
+        if size is not None and int(size) != len(payload):
+            failures.append(f"source_size_mismatch:{raw}")
+
+    if packaged is not None:
+        mode = packaged.get("source_snapshot_mode")
+        if mode != "exact_commit_tracked_subset":
+            failures.append(f"bad_source_snapshot_mode:{mode}")
+        included = {
+            str(row.get("path"))
+            for row in (packaged.get("included_source_files") or [])
+            if isinstance(row, dict)
+        }
+        # Authoritative formal wrapper must be packaged when present in delivery tree.
+        formal = "tests/formal/alt_config_limit_normalize_formal.v"
+        if formal in by_path and formal not in included:
+            failures.append("missing_tracked_formal_wrapper_in_packaged_source")
+        present_repo = {repo for _raw, repo in source_members}
+        if formal in included and formal not in present_repo:
+            failures.append("missing_formal_wrapper_source_member")
+
+    return failures
+
+
+def run_compact_zip_selftest(
+    zip_path: Path,
+    *,
+    extract_root: Path | None = None,
+    skip_software: bool = False,
+) -> dict[str, Any]:
+    """Standalone single-ZIP selftest (no package-dir sidecars required)."""
+    zip_path = zip_path.expanduser().resolve(strict=True)
+    failures: list[str] = []
+    members: list[str] = []
+    with zipfile.ZipFile(zip_path, "r", allowZip64=True) as archive:
+        bad = archive.testzip()
+        if bad is not None:
+            failures.append(f"zip_crc_failed:{bad}")
+        members = list(archive.namelist())
+        failures.extend(check_path_safety(members))
+        failures.extend(check_forbidden_members(members))
+        failures.extend(check_source_matches_delivery_tree(archive, members))
+        # duplicate member names
+        seen: set[str] = set()
+        for name in members:
+            key = _normalize_member(name)
+            if key in seen:
+                failures.append(f"duplicate_member:{name}")
+            seen.add(key)
+
+    required_meta_suffixes = (
+        "meta/git/HEAD.txt",
+        "meta/git/tree-manifest.json",
+        "meta/git/packaged-source-manifest.json",
+        "meta/release-set-identity.json",
+        "meta/REFERENCE-POINTER.json",
+        "meta/release-set-sibling.json",
+    )
+    for suffix in required_meta_suffixes:
+        if not any(_member_logical(name).endswith(suffix) for name in members):
+            failures.append(f"missing_{suffix.replace('/', '_')}")
+
+    status = "pass" if not failures else "fail"
+    return {
+        "schema": "cpld-review-compact-zip-selftest-v1",
+        "generated_at_utc": datetime.now(timezone.utc).isoformat(),
+        "status": status,
+        "zip_path": str(zip_path),
+        "member_count": len(members),
+        "failures": failures,
+        "mode": "standalone_zip",
+        "hardware_validation": "not_run",
+        "skip_software": skip_software,
+        "extract_root": str(extract_root) if extract_root else None,
+    }
+
+
 def _find_primary_zip(package_dir: Path, index: dict[str, Any]) -> Path:
 def _find_primary_zip(package_dir: Path, index: dict[str, Any]) -> Path:
     volumes = index.get("volumes") or []
     volumes = index.get("volumes") or []
     for volume in volumes:
     for volume in volumes:
@@ -150,6 +320,160 @@ def _find_primary_zip(package_dir: Path, index: dict[str, Any]) -> Path:
     return zips[0]
     return zips[0]
 
 
 
 
+def _read_zip_json(archive: zipfile.ZipFile, logical_suffix: str) -> Any | None:
+    for name in archive.namelist():
+        norm = _normalize_member(name)
+        if norm.endswith(logical_suffix):
+            try:
+                return json.loads(archive.read(name).decode("utf-8"))
+            except (UnicodeDecodeError, json.JSONDecodeError):
+                return None
+    return None
+
+
+def check_source_tracked_subset(archive: zipfile.ZipFile) -> list[str]:
+    """Fail-closed: every CPLD/source/** member must be exact DELIVERY tracked."""
+    failures: list[str] = []
+    tree = _read_zip_json(archive, "meta/git/tree-manifest.json")
+    packaged = _read_zip_json(archive, "meta/git/packaged-source-manifest.json")
+    file_sha = _read_zip_json(archive, "meta/git/source-file-sha256.json")
+    if file_sha is None:
+        file_sha = _read_zip_json(archive, "meta/git/file-sha256.json")
+    if not isinstance(tree, dict):
+        return ["missing_or_invalid_tree_manifest_for_source_check"]
+    tree_files = tree.get("files") if isinstance(tree.get("files"), list) else []
+    tracked = {
+        str(row.get("path")): row
+        for row in tree_files
+        if isinstance(row, dict) and row.get("path")
+    }
+    hash_map = {}
+    if isinstance(file_sha, dict) and isinstance(file_sha.get("files"), dict):
+        hash_map = {str(k): str(v) for k, v in file_sha["files"].items()}
+
+    source_members: list[str] = []
+    for name in archive.namelist():
+        norm = _normalize_member(name)
+        if norm.endswith("/"):
+            continue
+        logical = norm[len("cpld/") :] if norm.lower().startswith("cpld/") else norm
+        if not logical.startswith("source/"):
+            continue
+        rel = logical[len("source/") :]
+        source_members.append(rel)
+        if rel not in tracked:
+            failures.append(f"untracked_source_member:{rel}")
+            continue
+        info = archive.getinfo(name)
+        row = tracked[rel]
+        expected_size = row.get("size")
+        if expected_size is not None and int(expected_size) != int(info.file_size):
+            failures.append(f"source_size_mismatch:{rel}")
+        digest = hashlib.sha256(archive.read(name)).hexdigest()
+        expected_sha = str(row.get("sha256") or hash_map.get(rel) or "")
+        if expected_sha and digest != expected_sha:
+            failures.append(f"source_sha_mismatch:{rel}")
+
+    # Required tracked Formal wrapper must be present unless explicitly excluded.
+    required = "tests/formal/alt_config_limit_normalize_formal.v"
+    if required not in source_members:
+        excluded = set()
+        if isinstance(packaged, dict):
+            for row in packaged.get("policy_excluded") or []:
+                if isinstance(row, dict) and row.get("path"):
+                    excluded.add(str(row["path"]))
+        if required not in excluded:
+            failures.append(f"missing_required_tracked_source:{required}")
+
+    if isinstance(packaged, dict):
+        mode = packaged.get("source_snapshot_mode")
+        if mode != "exact_commit_tracked_subset":
+            failures.append(f"bad_source_snapshot_mode:{mode}")
+        tree_head = str(tree.get("head") or "")
+        pkg_head = str(packaged.get("delivery_commit") or "")
+        if tree_head and pkg_head and tree_head.casefold() != pkg_head.casefold():
+            failures.append("packaged_source_delivery_mismatch_tree_head")
+        # SBY workdirs must never appear under source/.
+        for rel in source_members:
+            if "/alt_config_limit_normalize_bmc/" in f"/{rel}/" or (
+                "/alt_config_limit_normalize_cover/" in f"/{rel}/"
+            ):
+                failures.append(f"formal_workdir_in_source:{rel}")
+    else:
+        failures.append("missing_packaged_source_manifest")
+
+    return failures
+
+
+def run_compact_zip_selftest(
+    zip_path: Path,
+    *,
+    extract_root: Path | None = None,
+    skip_software: bool = True,
+) -> dict[str, Any]:
+    """Standalone single-ZIP selftest (no package-dir sidecars required)."""
+    zip_path = zip_path.expanduser().resolve(strict=True)
+    failures: list[str] = []
+    members: list[str] = []
+    with zipfile.ZipFile(zip_path, "r", allowZip64=True) as archive:
+        bad = archive.testzip()
+        if bad is not None:
+            failures.append(f"zip_crc_failed:{bad}")
+        members = list(archive.namelist())
+        if len(members) != len(set(members)):
+            failures.append("duplicate_zip_members")
+        failures.extend(check_path_safety(members))
+        failures.extend(check_forbidden_members(members))
+        failures.extend(check_source_tracked_subset(archive))
+
+    required_meta_suffixes = (
+        "meta/git/HEAD.txt",
+        "meta/git/branch.txt",
+        "meta/git/status.txt",
+        "meta/git/log-20.txt",
+        "meta/git/tree-manifest.json",
+        "meta/git/packaged-source-manifest.json",
+        "meta/REFERENCE-POINTER.json",
+        "meta/source-closure-relations.json",
+        "meta/release-set-sibling.json",
+        "meta/release-set-identity.json",
+    )
+    for suffix in required_meta_suffixes:
+        if not any(_normalize_member(name).endswith(suffix) for name in members):
+            failures.append(f"missing_{suffix.replace('/', '_')}")
+    if not any(
+        _normalize_member(name).endswith("meta/git/source-file-sha256.json")
+        or _normalize_member(name).endswith("meta/git/file-sha256.json")
+        for name in members
+    ):
+        failures.append("missing_meta_git_source_file_sha256")
+    binding_status = (
+        "present"
+        if any(
+            _normalize_member(name).endswith("meta/td/td-source-closure-binding.json")
+            or _normalize_member(name).endswith("meta/td-source-closure-binding.json")
+            for name in members
+        )
+        else "missing"
+    )
+    if binding_status == "missing":
+        failures.append("missing_td_source_closure_binding")
+
+    status = "pass" if not failures else "fail"
+    return {
+        "schema": "cpld-review-compact-zip-selftest-v1",
+        "generated_at_utc": datetime.now(timezone.utc).isoformat(),
+        "status": status,
+        "mode": "standalone_zip",
+        "zip_path": str(zip_path),
+        "member_count": len(members),
+        "binding_status": binding_status,
+        "failures": failures,
+        "extract_root": str(extract_root) if extract_root else None,
+        "skip_software": skip_software,
+    }
+
+
 def run_compact_package_selftest(
 def run_compact_package_selftest(
     package_dir: Path,
     package_dir: Path,
     *,
     *,
@@ -190,6 +514,7 @@ def run_compact_package_selftest(
 
 
     zip_path: Path | None = None
     zip_path: Path | None = None
     members: list[str] = []
     members: list[str] = []
+    source_check_failures: list[str] = []
     if "missing_handoff_index" not in failures and "missing_sha256sums" not in failures:
     if "missing_handoff_index" not in failures and "missing_sha256sums" not in failures:
         try:
         try:
             zip_path = _find_primary_zip(package_dir, index)
             zip_path = _find_primary_zip(package_dir, index)
@@ -201,8 +526,10 @@ def run_compact_package_selftest(
             if bad is not None:
             if bad is not None:
                 failures.append(f"zip_crc_failed:{bad}")
                 failures.append(f"zip_crc_failed:{bad}")
             members = list(archive.namelist())
             members = list(archive.namelist())
+            source_check_failures = check_source_tracked_subset(archive)
         failures.extend(check_path_safety(members))
         failures.extend(check_path_safety(members))
         failures.extend(check_forbidden_members(members))
         failures.extend(check_forbidden_members(members))
+        failures.extend(source_check_failures)
 
 
     binding_status = "missing"
     binding_status = "missing"
     if any(
     if any(
@@ -220,9 +547,11 @@ def run_compact_package_selftest(
         "meta/git/status.txt",
         "meta/git/status.txt",
         "meta/git/log-20.txt",
         "meta/git/log-20.txt",
         "meta/git/tree-manifest.json",
         "meta/git/tree-manifest.json",
+        "meta/git/packaged-source-manifest.json",
         "meta/REFERENCE-POINTER.json",
         "meta/REFERENCE-POINTER.json",
         "meta/source-closure-relations.json",
         "meta/source-closure-relations.json",
         "meta/release-set-sibling.json",
         "meta/release-set-sibling.json",
+        "meta/release-set-identity.json",
     )
     )
     for suffix in required_meta_suffixes:
     for suffix in required_meta_suffixes:
         if not any(_normalize_member(name).endswith(suffix) for name in members):
         if not any(_normalize_member(name).endswith(suffix) for name in members):
@@ -263,6 +592,7 @@ def run_compact_package_selftest(
         "schema": "cpld-review-compact-package-selftest-v1",
         "schema": "cpld-review-compact-package-selftest-v1",
         "generated_at_utc": datetime.now(timezone.utc).isoformat(),
         "generated_at_utc": datetime.now(timezone.utc).isoformat(),
         "status": status,
         "status": status,
+        "mode": "package_dir",
         "package_dir": str(package_dir),
         "package_dir": str(package_dir),
         "zip_path": str(zip_path) if zip_path is not None else None,
         "zip_path": str(zip_path) if zip_path is not None else None,
         "member_count": len(members),
         "member_count": len(members),
@@ -298,6 +628,9 @@ def run_compact_package_selftest(
                 for item in failures
                 for item in failures
             )
             )
             else "fail",
             else "fail",
+            "source_tracked_subset": "pass"
+            if not source_check_failures
+            else "fail",
             "detached_replay": (
             "detached_replay": (
                 "not_run"
                 "not_run"
                 if skip_software
                 if skip_software
@@ -322,7 +655,12 @@ def run_compact_package_selftest(
 
 
 def build_parser() -> argparse.ArgumentParser:
 def build_parser() -> argparse.ArgumentParser:
     parser = argparse.ArgumentParser(description=__doc__)
     parser = argparse.ArgumentParser(description=__doc__)
-    parser.add_argument("--package-dir", type=Path, required=True)
+    parser.add_argument("--package-dir", type=Path)
+    parser.add_argument(
+        "--zip",
+        type=Path,
+        help="standalone single-ZIP mode (no package-dir sidecars required)",
+    )
     parser.add_argument("--extract-dir", type=Path)
     parser.add_argument("--extract-dir", type=Path)
     parser.add_argument("--skip-software", action="store_true")
     parser.add_argument("--skip-software", action="store_true")
     parser.add_argument(
     parser.add_argument(
@@ -337,12 +675,22 @@ def build_parser() -> argparse.ArgumentParser:
 def main(argv: list[str] | None = None) -> int:
 def main(argv: list[str] | None = None) -> int:
     args = build_parser().parse_args(argv)
     args = build_parser().parse_args(argv)
     try:
     try:
-        report = run_compact_package_selftest(
-            args.package_dir,
-            extract_root=args.extract_dir,
-            skip_software=args.skip_software,
-            write_evidence=args.write_evidence,
-        )
+        if args.zip is not None:
+            report = run_compact_zip_selftest(
+                args.zip,
+                extract_root=args.extract_dir,
+                skip_software=True if args.skip_software else True,
+            )
+        elif args.package_dir is not None:
+            report = run_compact_package_selftest(
+                args.package_dir,
+                extract_root=args.extract_dir,
+                skip_software=args.skip_software,
+                write_evidence=args.write_evidence,
+            )
+        else:
+            print("error: require --package-dir or --zip", file=sys.stderr)
+            return 1
     except Exception as exc:  # noqa: BLE001
     except Exception as exc:  # noqa: BLE001
         print(f"error: {exc}", file=sys.stderr)
         print(f"error: {exc}", file=sys.stderr)
         return 1
         return 1

+ 17 - 4
tools/package_provenance.py

@@ -238,7 +238,7 @@ def stable_reference_inventory_semantics(inventory: dict[str, Any] | None) -> di
 
 
 
 
 def reference_set_fingerprint(repo_root: Path | None = None) -> dict[str, Any]:
 def reference_set_fingerprint(repo_root: Path | None = None) -> dict[str, Any]:
-    """Stable raw reference-set fingerprint (no generated_at / temp paths / inventory SHA)."""
+    """Stable raw reference-set fingerprint v2 (no generated_at / temp paths / inventory SHA)."""
     root = repo_root or ROOT
     root = repo_root or ROOT
     inventory_path = root / "docs" / "REFERENCE-INVENTORY.json"
     inventory_path = root / "docs" / "REFERENCE-INVENTORY.json"
     raw = load_reference_package_identity(root)
     raw = load_reference_package_identity(root)
@@ -246,9 +246,16 @@ def reference_set_fingerprint(repo_root: Path | None = None) -> dict[str, Any]:
     schematic_identity = stable_reference_inventory_semantics(
     schematic_identity = stable_reference_inventory_semantics(
         inventory if isinstance(inventory, dict) else {}
         inventory if isinstance(inventory, dict) else {}
     )
     )
-    # Raw fingerprint: ZIP identity + BRD + stable schematic semantics only.
-    # Do NOT mix in inventory file SHA / generated_at / repository_root.
+    # Normalized inventory content fingerprint (stable fields only; informational).
+    inventory_content_fingerprint = _sha256_bytes(
+        json.dumps(schematic_identity, sort_keys=True, separators=(",", ":")).encode(
+            "utf-8"
+        )
+    )
+    # Raw fingerprint v2: schema + ZIP identity + BRD + stable schematic semantics.
+    # Do NOT mix in inventory file SHA / generated_at / repository_root / abs paths.
     content_parts = {
     content_parts = {
+        "fingerprint_schema": "prod2u-reference-set-fingerprint-v2",
         "reference_package_filename": raw["filename"],
         "reference_package_filename": raw["filename"],
         "reference_package_sha256": raw["sha256"],
         "reference_package_sha256": raw["sha256"],
         "reference_package_size": raw["size"],
         "reference_package_size": raw["size"],
@@ -258,10 +265,16 @@ def reference_set_fingerprint(repo_root: Path | None = None) -> dict[str, Any]:
     fp = _sha256_bytes(
     fp = _sha256_bytes(
         json.dumps(content_parts, sort_keys=True, separators=(",", ":")).encode("utf-8")
         json.dumps(content_parts, sort_keys=True, separators=(",", ":")).encode("utf-8")
     )
     )
+    inventory_file_sha = (
+        _sha256_file(inventory_path) if inventory_path.is_file() else None
+    )
     return {
     return {
-        "schema": "prod2u-reference-set-fingerprint-v1",
+        "schema": "prod2u-reference-set-fingerprint-v2",
         "sha256": fp,
         "sha256": fp,
         "parts": content_parts,
         "parts": content_parts,
+        "inventory_content_fingerprint": inventory_content_fingerprint,
+        # Informational only — must not participate in raw fp / release_set_id.
+        "inventory_file_sha256_informational": inventory_file_sha,
         "canonical_brd_path": (
         "canonical_brd_path": (
             "reference/original/board/FCB_FPGA_MCU_V1.2_20260717/"
             "reference/original/board/FCB_FPGA_MCU_V1.2_20260717/"
             "FCB_FPGA+MCU_V1.2_20260717.brd"
             "FCB_FPGA+MCU_V1.2_20260717.brd"

+ 2 - 0
tools/test_profiles.py

@@ -57,6 +57,8 @@ def normalize_profile(value: str | None) -> str | None:
         "live-repository": LIVE_REPOSITORY,
         "live-repository": LIVE_REPOSITORY,
         "compact": REVIEW_COMPACT_DETACHED,
         "compact": REVIEW_COMPACT_DETACHED,
         "detached": REVIEW_COMPACT_DETACHED,
         "detached": REVIEW_COMPACT_DETACHED,
+        # Contract / THREAD-AUTH underscore form → hyphenated after normalize.
+        "detached-review-compact": REVIEW_COMPACT_DETACHED,
         "review-compact": REVIEW_COMPACT_DETACHED,
         "review-compact": REVIEW_COMPACT_DETACHED,
         "review-compact-detached": REVIEW_COMPACT_DETACHED,
         "review-compact-detached": REVIEW_COMPACT_DETACHED,
         "reference": REFERENCE_REGENERATION,
         "reference": REFERENCE_REGENERATION,