Переглянути джерело

fix: honest source-closure compare and full package layout

Avoid fake commit diffs when git show is unavailable; emit ZIP+tar.zst
sidecars with index/checksums/exclusions and UTF-8 path round-trip support.

Co-authored-by: Cursor <cursoragent@cursor.com>
root 3 місяців тому
батько
коміт
3a90ecec4f

+ 198 - 24
package_for_agent_analysis.py

@@ -791,6 +791,11 @@ def collect_analysis_inputs(
 ) -> AnalysisCollection:
     root = repo_root.resolve(strict=True)
     temp_root.mkdir(parents=True, exist_ok=True)
+    if profile == "full" and not include_git_bundle:
+        raise PackagingError(
+            "full inclusion-first packages require a git bundle so replay can restore "
+            "commit-to-commit source closure comparison"
+        )
     items: list[PackageItem] = []
     excluded: list[dict[str, str]] = []
     warnings: list[dict[str, str]] = []
@@ -1398,41 +1403,73 @@ def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[st
         raise PackagingError(f"replay extract root already exists: {extract_root}")
     index_path = package_dir / "HANDOFF-INDEX.json"
     sums_path = package_dir / "SHA256SUMS.txt"
+    exclusions_path = package_dir / "EXCLUSIONS.txt"
     if not index_path.is_file() or not sums_path.is_file():
         raise PackagingError("package directory is missing HANDOFF-INDEX.json or SHA256SUMS.txt")
     index = json.loads(index_path.read_text(encoding="utf-8"))
     extract_root.mkdir(parents=True, exist_ok=False)
+    zip_extract_root = extract_root / "from-zip"
+    tar_extract_root = extract_root / "from-tar-zst"
+    zip_extract_root.mkdir(parents=True, exist_ok=True)
     verified_volumes: list[dict[str, object]] = []
+    verified_sidecars: list[dict[str, object]] = []
+    tar_zst_name: str | None = None
     for line in sums_path.read_text(encoding="ascii").splitlines():
         line = line.strip()
-        if not line:
+        if not line or line.startswith("#"):
             continue
         digest, _, name = line.partition("  ")
         if not digest or not name:
             raise PackagingError(f"invalid SHA256SUMS line: {line}")
-        volume_path = package_dir / name
-        actual = handoff.sha256_file(volume_path)
+        member_path = package_dir / name
+        actual = handoff.sha256_file(member_path)
         if actual != digest:
             raise PackagingError(f"SHA256SUMS mismatch for {name}")
-        with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
-            archive.extractall(extract_root)
-        verified_volumes.append({"file": name, "sha256": actual})
+        lower = name.casefold()
+        if lower.endswith(".zip"):
+            with zipfile.ZipFile(member_path, "r", allowZip64=True) as archive:
+                archive.extractall(zip_extract_root)
+            verified_volumes.append({"file": name, "sha256": actual})
+        elif lower.endswith(".tar.zst"):
+            tar_zst_name = name
+            tar_extract_root.mkdir(parents=True, exist_ok=True)
+            completed = subprocess.run(
+                ["tar", "--zstd", "-xf", str(member_path), "-C", str(tar_extract_root)],
+                stdout=subprocess.PIPE,
+                stderr=subprocess.PIPE,
+                check=False,
+            )
+            if completed.returncode != 0:
+                raise PackagingError(
+                    f"unable to extract tar.zst during replay: {name}: "
+                    f"{completed.stderr.decode('utf-8', errors='replace').strip()}"
+                )
+            verified_sidecars.append({"file": name, "sha256": actual, "kind": "tar_zst"})
+        else:
+            verified_sidecars.append({"file": name, "sha256": actual, "kind": "sidecar"})
     checked_files = 0
     for item in index.get("files", []):
         relative = str(item["path"])
-        target = extract_root / "CPLD" / Path(*relative.split("/"))
+        target = zip_extract_root / "CPLD" / Path(*relative.split("/"))
         if not target.is_file():
             raise PackagingError(f"replay missing extracted file: {relative}")
         digest = handoff.sha256_file(target)
         if digest != item["sha256"] or target.stat().st_size != int(item["size"]):
             raise PackagingError(f"replay hash mismatch for {relative}")
+        if tar_zst_name is not None:
+            # tar.zst is created from ZIP extract roots, so the same CPLD tree must round-trip.
+            tar_target = tar_extract_root / "CPLD" / Path(*relative.split("/"))
+            if not tar_target.is_file():
+                raise PackagingError(f"tar.zst replay missing extracted file: {relative}")
+            if handoff.sha256_file(tar_target) != digest:
+                raise PackagingError(f"tar.zst replay hash mismatch for {relative}")
         checked_files += 1
     for record in index.get("content_dedup", []):
-        physical = extract_root / "CPLD" / Path(*str(record["physical_path"]).split("/"))
+        physical = zip_extract_root / "CPLD" / Path(*str(record["physical_path"]).split("/"))
         if not physical.is_file():
             raise PackagingError(f"replay missing dedup physical file: {record['physical_path']}")
         for alias in record.get("logical_paths", []):
-            alias_path = extract_root / "CPLD" / Path(*str(alias).split("/"))
+            alias_path = zip_extract_root / "CPLD" / Path(*str(alias).split("/"))
             if alias_path.exists():
                 raise PackagingError(f"replay found duplicated physical alias path: {alias}")
     return {
@@ -1441,6 +1478,9 @@ def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[st
         "package_dir": str(package_dir),
         "extract_root": str(extract_root),
         "volumes": verified_volumes,
+        "sidecars": verified_sidecars,
+        "exclusions_present": exclusions_path.is_file(),
+        "tar_zst": tar_zst_name,
         "checked_files": checked_files,
         "content_dedup_groups": len(index.get("content_dedup", [])),
         "derived_evidence_count": len(index.get("derived_evidence", [])),
@@ -1852,12 +1892,146 @@ def _assert_source_trees_unchanged(collection: AnalysisCollection, *, profile: s
 def _start_here_text(package_name: str, volume_count: int) -> str:
     return (
         f"# {package_name} 分析交付包\n\n"
-        f"本目录包含 {volume_count} 个互相独立的普通 ZIP。请先核对 `SHA256SUMS.txt`,"
-        "再把所有 ZIP 解压到同一个目录。\n\n"
+        f"本目录包含 {volume_count} 个互相独立的普通 ZIP,以及可选的 `.tar.zst` 同源归档。"
+        "请先核对 `SHA256SUMS.txt`,再把所有 ZIP 解压到同一个目录;"
+        "也可用 `tar --zstd -xf <package>.tar.zst` 还原。\n\n"
         "`HANDOFF-INDEX.json` 记录每个原始文件的来源、目标卷、大小和 SHA-256,"
+        "`EXCLUSIONS.txt` 列出排除路径与规则,"
         "以及 `excluded`(排除原因)、`derived_evidence`(由原始 BRD 派生的 board-viewer JSON/SVG,"
         "不是 RTL/TD source closure)和 `content_dedup`(相同大文件只保留一份物理副本时的逻辑归属)。\n"
+        "完整 full 包必须包含 `git-history/*.bundle`,以便在干净提取后用 commit-to-commit "
+        "恢复 source closure 比对。\n"
+    )
+
+
+def write_exclusions_text(excluded: list[dict[str, object]]) -> str:
+    """Render a portable EXCLUSIONS.txt for the package sidecar layout."""
+    lines = [
+        "# path<TAB>rule",
+        "# Inclusion-first package: only versioned recursive exclusions are listed.",
+    ]
+    for item in sorted(excluded, key=lambda row: handoff.windows_collision_key(str(row.get("path", "")))):
+        path = str(item.get("path", ""))
+        rule = str(item.get("rule", item.get("reason", "excluded")))
+        lines.append(f"{path}\t{rule}")
+    return "\n".join(lines) + "\n"
+
+
+def create_tar_zst_archive(source_dir: Path, archive_path: Path) -> str:
+    """Create a deterministic-enough tar.zst of source_dir contents; return SHA-256."""
+    source_dir = source_dir.resolve(strict=True)
+    archive_path = archive_path.resolve(strict=False)
+    if archive_path.exists():
+        archive_path.unlink()
+    zstd = shutil.which("zstd")
+    if zstd is None:
+        raise PackagingError("zstd is required to create .tar.zst package archives")
+    # Prefer GNU tar --zstd when available; fall back to compress-program.
+    command = [
+        "tar",
+        "--zstd",
+        "-cf",
+        str(archive_path),
+        "--sort=name",
+        "--mtime=UTC 1980-01-01",
+        "--owner=0",
+        "--group=0",
+        "--numeric-owner",
+        "-C",
+        str(source_dir),
+        ".",
+    ]
+    completed = subprocess.run(
+        command,
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+        check=False,
+    )
+    if completed.returncode != 0:
+        # Older tar without --zstd / --sort: use compress-program path.
+        fallback = [
+            "tar",
+            "-cf",
+            str(archive_path),
+            "-I",
+            zstd,
+            "-C",
+            str(source_dir),
+            ".",
+        ]
+        completed = subprocess.run(
+            fallback,
+            stdout=subprocess.PIPE,
+            stderr=subprocess.PIPE,
+            check=False,
+        )
+        if completed.returncode != 0:
+            detail = completed.stderr.decode("utf-8", errors="replace").strip()
+            raise PackagingError(f"unable to create tar.zst archive: {detail or 'tar failed'}")
+    return handoff.sha256_file(archive_path)
+
+
+def write_package_layout_sidecars(
+    staging: Path,
+    *,
+    index: dict[str, object],
+    excluded: list[dict[str, object]],
+    package_name: str,
+    include_tar_zst: bool = True,
+) -> list[dict[str, object]]:
+    """Write index/checksums/exclusions and optional tar.zst; return checksum rows."""
+    staging.mkdir(parents=True, exist_ok=True)
+    (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
+    (staging / "EXCLUSIONS.txt").write_text(
+        write_exclusions_text(excluded),
+        encoding="utf-8",
+        newline="\n",
+    )
+    (staging / "START-HERE.zh-CN.md").write_text(
+        _start_here_text(package_name, len(index.get("volumes", []))),
+        encoding="utf-8",
+        newline="\n",
+    )
+
+    checksum_rows: list[dict[str, object]] = []
+    for info in index.get("volumes", []):
+        name = str(info["file"])
+        checksum_rows.append({"file": name, "sha256": str(info["sha256"])})
+
+    if include_tar_zst:
+        # Stage CPLD tree from ZIP volumes into a temporary extract for tar.zst.
+        extract_root = staging / ".tar-zst-staging"
+        if extract_root.exists():
+            shutil.rmtree(extract_root)
+        extract_root.mkdir(parents=True, exist_ok=True)
+        for info in index.get("volumes", []):
+            volume_path = staging / str(info["file"])
+            with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
+                archive.extractall(extract_root)
+        tar_name = f"{package_name}.tar.zst"
+        tar_path = staging / tar_name
+        tar_sha = create_tar_zst_archive(extract_root, tar_path)
+        shutil.rmtree(extract_root)
+        checksum_rows.append({"file": tar_name, "sha256": tar_sha})
+        index["formats"] = {
+            "zip_volumes": [str(info["file"]) for info in index.get("volumes", [])],
+            "tar_zst": tar_name,
+            "tar_zst_sha256": tar_sha,
+        }
+        (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
+
+    for sidecar in ("HANDOFF-INDEX.json", "EXCLUSIONS.txt", "START-HERE.zh-CN.md"):
+        checksum_rows.append(
+            {"file": sidecar, "sha256": handoff.sha256_file(staging / sidecar)}
+        )
+
+    checksum_lines = [f"{row['sha256']}  {row['file']}" for row in checksum_rows]
+    (staging / "SHA256SUMS.txt").write_text(
+        "\n".join(checksum_lines) + "\n",
+        encoding="ascii",
+        newline="\n",
     )
+    return checksum_rows
 
 
 def _publish_directory_atomically(staging: Path, final: Path, *, force: bool) -> None:
@@ -2039,25 +2213,19 @@ def create_analysis_package(
                 encoding="utf-8",
                 newline="\n",
             )
-        (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
-        (staging / "START-HERE.zh-CN.md").write_text(
-            _start_here_text(package_name, len(volume_infos)),
-            encoding="utf-8",
-            newline="\n",
-        )
-        checksum_lines = [f"{info['sha256']}  {info['file']}" for info in volume_infos]
-        (staging / "SHA256SUMS.txt").write_text(
-            "\n".join(checksum_lines) + "\n",
-            encoding="ascii",
-            newline="\n",
-        )
-
         for info in volume_infos:
             volume_path = staging / str(info["file"])
             if volume_path.stat().st_size >= max_zip_bytes:
                 raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
             if handoff.sha256_file(volume_path) != info["sha256"]:
                 raise PackagingError(f"ZIP volume hash changed after verification: {volume_path.name}")
+        checksum_rows = write_package_layout_sidecars(
+            staging,
+            index=index,
+            excluded=package_excluded,
+            package_name=package_name,
+            include_tar_zst=True,
+        )
         full_inventory_by_path = {str(item["path"]): item for item in full_inventory}
         _assert_items_unchanged(collection.items, full_inventory_by_path)
         _assert_source_trees_unchanged(collection, profile=profile)
@@ -2068,6 +2236,10 @@ def create_analysis_package(
         if os.path.lexists(staging):
             shutil.rmtree(staging, ignore_errors=True)
         raise
+    formats = {}
+    index_path = final_dir / "HANDOFF-INDEX.json"
+    if index_path.is_file():
+        formats = json.loads(index_path.read_text(encoding="utf-8")).get("formats", {})
     return {
         "status": collection.status,
         "mode": "package",
@@ -2076,6 +2248,8 @@ def create_analysis_package(
         "run_id": run_id,
         "output_dir": str(final_dir),
         "volumes": volume_infos,
+        "formats": formats,
+        "checksum_entries": len(checksum_rows),
         "included_file_count": len(inventory),
         "included_bytes": sum(int(item["size"]) for item in inventory),
         "excluded_entry_count": len(package_excluded),

+ 25 - 0
schemas/agent_analysis_handoff_index.schema.json

@@ -48,6 +48,31 @@
     "delivery_policy": {
       "type": "string"
     },
+    "formats": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": [
+        "zip_volumes",
+        "tar_zst",
+        "tar_zst_sha256"
+      ],
+      "properties": {
+        "zip_volumes": {
+          "type": "array",
+          "items": {
+            "type": "string",
+            "minLength": 1
+          }
+        },
+        "tar_zst": {
+          "type": "string",
+          "minLength": 1
+        },
+        "tar_zst_sha256": {
+          "$ref": "#/$defs/sha256"
+        }
+      }
+    },
     "content_dedup": {
       "type": "array",
       "items": {

+ 69 - 0
tests/unit/test_build_firmware_package.py

@@ -199,6 +199,75 @@ class BuildFirmwarePackageTests(unittest.TestCase):
                     source_closure_unchanged=True,
                 )
 
+    def test_source_closure_unavailable_without_git_is_not_fake_diff(self) -> None:
+        td_report = {
+            "synthesis_input_manifest": {
+                "inputs": {
+                    "projects/prod2u-door-temp/project.json": "a" * 64,
+                    "src/generated/td-source-manifest.json": "b" * 64,
+                }
+            }
+        }
+        comparison = builder.generate_source_closure_comparison(
+            td_report=td_report,
+            artifact_commit="0" * 40,
+            matrix_commit="1" * 40,
+            final_dev_commit="2" * 40,
+            repo_root=ROOT,
+        )
+        self.assertEqual(comparison["mode"], "comparison_unavailable_without_git")
+        self.assertIsNone(comparison["source_closure_equal"])
+        self.assertEqual(comparison["production_changed_paths"], [])
+        self.assertTrue(all(entry["status"] == "unavailable" for entry in comparison["inputs"]))
+
+    def test_source_closure_snapshot_hash_mode(self) -> None:
+        project_sha = _current_project_sha()
+        td_report = {
+            "synthesis_input_manifest": {
+                "inputs": {
+                    "projects/prod2u-door-temp/project.json": project_sha,
+                }
+            }
+        }
+        snapshot = {
+            "artifact": {"projects/prod2u-door-temp/project.json": project_sha},
+            "matrix": {"projects/prod2u-door-temp/project.json": project_sha},
+            "final_dev": {"projects/prod2u-door-temp/project.json": project_sha},
+        }
+        comparison = builder.generate_source_closure_comparison(
+            td_report=td_report,
+            artifact_commit="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
+            matrix_commit="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
+            final_dev_commit="cccccccccccccccccccccccccccccccccccccccc",
+            snapshot_hashes=snapshot,
+        )
+        self.assertEqual(comparison["mode"], "snapshot_hash")
+        self.assertTrue(comparison["source_closure_equal"])
+        self.assertEqual(comparison["production_changed_paths"], [])
+
+    def test_source_closure_live_commit_compare(self) -> None:
+        head = subprocess.check_output(
+            ["git", "-C", str(ROOT), "rev-parse", "HEAD"],
+            text=True,
+        ).strip()
+        td_report = {
+            "synthesis_input_manifest": {
+                "inputs": {
+                    "projects/prod2u-door-temp/project.json": _current_project_sha(),
+                }
+            }
+        }
+        comparison = builder.generate_source_closure_comparison(
+            td_report=td_report,
+            artifact_commit=head,
+            matrix_commit=head,
+            final_dev_commit=head,
+            repo_root=ROOT,
+        )
+        self.assertEqual(comparison["mode"], "commit_compare")
+        self.assertTrue(comparison["source_closure_equal"])
+        self.assertEqual(comparison["inputs"][0]["status"], "same")
+
 
 if __name__ == "__main__":
     unittest.main()

+ 135 - 0
tests/unit/test_package_for_agent_analysis.py

@@ -1005,6 +1005,141 @@ class PackageForAgentAnalysisTests(unittest.TestCase):
                 ["backup-failure-fixture"],
             )
 
+    def test_package_layout_writes_exclusions_tar_zst_and_checksums(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            source = write_file(temp / "source", "src/core.v", b"module core; endmodule\n")
+            collection = analyzer.AnalysisCollection(
+                status="pass",
+                items=(
+                    analyzer.make_package_item(
+                        source,
+                        relative="workspace-current/src/core.v",
+                        category="core",
+                        source_id="workspace-current",
+                    ),
+                ),
+                excluded=(
+                    {"path": ".venv", "rule": "virtual_environment"},
+                    {"path": "tmp", "rule": "temporary_workspace_directory"},
+                ),
+                warnings=(),
+                sources=({"id": "workspace-current", "status": "pass"},),
+                git=(),
+            )
+            result = analyzer.create_analysis_package(
+                collection=collection,
+                output_root=temp / "output",
+                package_name="layout-fixture",
+                max_zip_bytes=1_000_000,
+                target_zip_bytes=800_000,
+                force=False,
+            )
+            package_dir = Path(result["output_dir"])
+            self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
+            self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
+            self.assertTrue((package_dir / "EXCLUSIONS.txt").is_file())
+            self.assertTrue((package_dir / "layout-fixture.tar.zst").is_file())
+            exclusions = (package_dir / "EXCLUSIONS.txt").read_text(encoding="utf-8")
+            self.assertIn(".venv\tvirtual_environment", exclusions)
+            sums = (package_dir / "SHA256SUMS.txt").read_text(encoding="ascii")
+            self.assertIn("layout-fixture.tar.zst", sums)
+            self.assertIn("EXCLUSIONS.txt", sums)
+            index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
+            self.assertEqual(index["formats"]["tar_zst"], "layout-fixture.tar.zst")
+            replay = analyzer.replay_analysis_package(
+                package_dir,
+                extract_root=temp / "replay",
+            )
+            self.assertEqual(replay["status"], "pass")
+            self.assertTrue(replay["exclusions_present"])
+            self.assertEqual(replay["tar_zst"], "layout-fixture.tar.zst")
+
+    def test_chinese_and_spaces_path_round_trip(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            relative = "workspace-current/docs/中文目录/file with spaces.txt"
+            source = write_file(
+                temp / "source",
+                "docs/中文目录/file with spaces.txt",
+                "中文内容与 spaces\n".encode("utf-8"),
+            )
+            collection = analyzer.AnalysisCollection(
+                status="pass",
+                items=(
+                    analyzer.make_package_item(
+                        source,
+                        relative=relative,
+                        category="core",
+                        source_id="workspace-current",
+                    ),
+                ),
+                excluded=(),
+                warnings=(),
+                sources=({"id": "workspace-current", "status": "pass"},),
+                git=(),
+            )
+            result = analyzer.create_analysis_package(
+                collection=collection,
+                output_root=temp / "output",
+                package_name="unicode-fixture",
+                max_zip_bytes=1_000_000,
+                target_zip_bytes=800_000,
+                force=False,
+            )
+            package_dir = Path(result["output_dir"])
+            volume = package_dir / result["volumes"][0]["file"]
+            with zipfile.ZipFile(volume) as archive:
+                names = archive.namelist()
+                self.assertIn(f"CPLD/{relative}", names)
+                info = archive.getinfo(f"CPLD/{relative}")
+                self.assertTrue(info.flag_bits & 0x800)
+                self.assertEqual(
+                    archive.read(f"CPLD/{relative}"),
+                    "中文内容与 spaces\n".encode("utf-8"),
+                )
+            replay = analyzer.replay_analysis_package(
+                package_dir,
+                extract_root=temp / "replay-unicode",
+            )
+            self.assertEqual(replay["status"], "pass")
+            self.assertEqual(replay["checked_files"], 1)
+
+    def test_full_profile_requires_git_bundle(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            repo = temp / "repo"
+            repo.mkdir()
+            git = shutil.which("git")
+            if not git:
+                self.skipTest("Git is required")
+            subprocess.run([git, "init", "-q", str(repo)], check=True)
+            subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
+            subprocess.run(
+                [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
+                check=True,
+            )
+            write_file(repo, "src/core.v", b"module core; endmodule\n")
+            subprocess.run([git, "-C", str(repo), "add", "src/core.v"], check=True)
+            subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
+            config = analyzer.HandoffConfig(
+                max_zip_bytes=1_000_000,
+                target_zip_bytes=800_000,
+                external_sources=(),
+                extra_exclusions=(),
+            )
+            with self.assertRaisesRegex(analyzer.PackagingError, "git bundle"):
+                analyzer.collect_analysis_inputs(
+                    repo_root=repo,
+                    config=config,
+                    temp_root=temp / "run",
+                    include_git_bundle=False,
+                    profile="full",
+                )
+
 
 if __name__ == "__main__":
     unittest.main()

+ 96 - 30
tools/build_firmware_package.py

@@ -116,8 +116,18 @@ def generate_source_closure_comparison(
     matrix_commit: str,
     final_dev_commit: str,
     repo_root: Path = ROOT,
+    snapshot_hashes: dict[str, dict[str, str]] | None = None,
 ) -> dict[str, Any]:
-    """Compare synthesis inputs across artifact, matrix, and final dev commits."""
+    """Compare synthesis inputs across artifact, matrix, and final dev commits.
+
+    Modes:
+    - ``commit_compare``: live repo ``git show`` commit-to-commit (default).
+    - ``snapshot_hash``: compare caller-supplied SHA-256 maps (no git required).
+    - ``comparison_unavailable_without_git``: every ``git show`` failed; do **not**
+      report ``source_closure_equal=false`` with an empty ``production_changed_paths``
+      as if that were a real commit diff. Full delivery packages must include a git
+      bundle so replay can restore commit-to-commit comparison.
+    """
     inputs = td_report.get("synthesis_input_manifest", {}).get("inputs", {})
     if not inputs:
         raise PackagingError("TD report has no synthesis_input_manifest.inputs")
@@ -125,39 +135,83 @@ def generate_source_closure_comparison(
     entries: list[dict[str, Any]] = []
     production_changed_paths: list[str] = []
     all_same = True
+    commit_keys = (
+        ("artifact_source_sha256", artifact_commit, "artifact"),
+        ("matrix_commit_sha256", matrix_commit, "matrix"),
+        ("final_dev_commit_sha256", final_dev_commit, "final_dev"),
+    )
 
-    for relative_path, artifact_sha in sorted(inputs.items()):
-        row: dict[str, Any] = {"path": relative_path, "artifact_expected_sha256": artifact_sha}
-        values: list[str | None] = []
-        for commit, key in [
-            (artifact_commit, "artifact_source_sha256"),
-            (matrix_commit, "matrix_commit_sha256"),
-            (final_dev_commit, "final_dev_commit_sha256"),
-        ]:
-            try:
-                content = _git_show_file(repo_root, commit, relative_path)
-                sha = _sha256_bytes(content)
-            except PackagingError:
-                sha = None
-            row[key] = sha
-            values.append(sha)
-
-        if values[0] == values[1] == values[2] and values[0] is not None:
-            row["status"] = "same"
-        else:
-            row["status"] = "different"
+    if snapshot_hashes is not None:
+        mode = "snapshot_hash"
+        for relative_path, artifact_sha in sorted(inputs.items()):
+            row: dict[str, Any] = {
+                "path": relative_path,
+                "artifact_expected_sha256": artifact_sha,
+            }
+            values: list[str | None] = []
+            for key, _commit, label in commit_keys:
+                sha = snapshot_hashes.get(label, {}).get(relative_path)
+                row[key] = sha
+                values.append(sha)
+            if any(value is None for value in values):
+                row["status"] = "unavailable"
+                all_same = False
+            elif values[0] == values[1] == values[2]:
+                row["status"] = "same"
+            else:
+                row["status"] = "different"
+                all_same = False
+                if values[0] != values[2]:
+                    production_changed_paths.append(relative_path)
+            entries.append(row)
+        source_closure_equal: bool | None = all_same and all(
+            entry["status"] == "same" for entry in entries
+        )
+    else:
+        mode = "commit_compare"
+        for relative_path, artifact_sha in sorted(inputs.items()):
+            row = {"path": relative_path, "artifact_expected_sha256": artifact_sha}
+            values = []
+            for key, commit, _label in commit_keys:
+                try:
+                    content = _git_show_file(repo_root, commit, relative_path)
+                    sha = _sha256_bytes(content)
+                except PackagingError:
+                    sha = None
+                row[key] = sha
+                values.append(sha)
+
+            if values[0] is None and values[1] is None and values[2] is None:
+                # git show failed for every commit: not a fake "different" commit diff
+                row["status"] = "unavailable"
+            elif values[0] == values[1] == values[2] and values[0] is not None:
+                row["status"] = "same"
+            else:
+                row["status"] = "different"
+                all_same = False
+                if values[0] != values[2]:
+                    production_changed_paths.append(relative_path)
+            entries.append(row)
+
+        if entries and all(entry["status"] == "unavailable" for entry in entries):
+            mode = "comparison_unavailable_without_git"
+            source_closure_equal = None
+            production_changed_paths = []
             all_same = False
-            if values[0] != values[2]:
-                production_changed_paths.append(relative_path)
-
-        entries.append(row)
+        else:
+            if any(entry["status"] == "unavailable" for entry in entries):
+                all_same = False
+            source_closure_equal = all_same and all(
+                entry["status"] == "same" for entry in entries
+            )
 
     comparison_text = json.dumps(
         {
             "artifact_source_commit": artifact_commit,
             "matrix_commit": matrix_commit,
             "final_dev_commit": final_dev_commit,
-            "source_closure_equal": all_same,
+            "mode": mode,
+            "source_closure_equal": source_closure_equal,
             "production_changed_paths": production_changed_paths,
             "entries": entries,
         },
@@ -167,10 +221,11 @@ def generate_source_closure_comparison(
 
     return {
         "schema": "prod2u-source-closure-comparison-v1",
+        "mode": mode,
         "artifact_source_commit": artifact_commit,
         "matrix_commit": matrix_commit,
         "final_dev_commit": final_dev_commit,
-        "source_closure_equal": all_same,
+        "source_closure_equal": source_closure_equal,
         "production_changed_paths": production_changed_paths,
         "source_set_sha256": source_set_sha256,
         "inputs": entries,
@@ -338,10 +393,15 @@ def build_firmware_package(
         final_dev_commit=final_dev_commit,
         repo_root=ROOT,
     )
+    if comparison["mode"] == "comparison_unavailable_without_git":
+        raise PackagingError(
+            "source closure comparison unavailable without git; "
+            "full packages require a git bundle so replay can restore commit-to-commit compare"
+        )
     if not source_closure_unchanged and comparison["source_closure_equal"]:
         # Caller claimed changed but comparison says same: trust explicit flag
         pass
-    if source_closure_unchanged and not comparison["source_closure_equal"]:
+    if source_closure_unchanged and comparison["source_closure_equal"] is not True:
         raise PackagingError(
             f"source_closure_unchanged requested but comparison differs: {comparison['production_changed_paths']}"
         )
@@ -375,7 +435,8 @@ def build_firmware_package(
         "final_dev_commit": final_dev_commit,
         "td_run_id": td_report.get("run_id"),
         "matrix_run_id": matrix_run_id,
-        "source_closure_unchanged": comparison["source_closure_equal"],
+        "source_closure_unchanged": bool(comparison["source_closure_equal"]),
+        "source_closure_comparison_mode": comparison["mode"],
         "project_config_sha256": current_project_sha,
         "td_source_manifest_sha256": td_report.get("td_source_manifest_sha256"),
         "synthesis_input_manifest_sha256": td_report.get("synthesis_input_manifest", {}).get("sha256"),
@@ -414,7 +475,12 @@ def build_firmware_package(
         _add_text(zipf, artifact_commit, "ARTIFACT-SOURCE-COMMIT.txt", sha256_entries)
         _add_text(zipf, matrix_commit, "MATRIX-COMMIT.txt", sha256_entries)
         _add_text(zipf, final_dev_commit, "FINAL-DEV-COMMIT.txt", sha256_entries)
-        _add_text(zipf, "true" if comparison["source_closure_equal"] else "false", "SOURCE-CLOSURE-UNCHANGED.txt", sha256_entries)
+        _add_text(
+            zipf,
+            "true" if comparison["source_closure_equal"] is True else "false",
+            "SOURCE-CLOSURE-UNCHANGED.txt",
+            sha256_entries,
+        )
 
         # Original TD report and provenance
         _add_file(zipf, td_report_path, "td/original-final_td_report.json", sha256_entries)