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

package: zipfile fallback for analysis packager and firmware provenance.

- package_for_agent_analysis.py now creates ZIP volumes via Python zipfile, no longer requires 7-Zip for core package creation.
- build_firmware_package.py now requires explicit --td-root, binds bitstream/report to TD root, generates SOURCE-CLOSURE-COMPARISON.json, TD-PROVENANCE.json, manifest v2, and external selftest sidecar.
- Tests updated for new APIs and negative cases.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Codex Resource Selftest 4 месяцев назад
Родитель
Сommit
3717c242e7

+ 166 - 59
package_for_agent_analysis.py

@@ -1017,6 +1017,109 @@ def _inspect_and_extract_unsupported_archive(
     return expanded_items, rebased_excluded, contains_sensitive
     return expanded_items, rebased_excluded, contains_sensitive
 
 
 
 
+def _inspect_and_extract_zip_archive(
+    item: PackageItem,
+    *,
+    temp_root: Path,
+    extra_exclusions: tuple[dict[str, str], ...],
+) -> tuple[list[PackageItem], list[dict[str, str]], bool]:
+    archive_label = item.candidate.relative
+    try:
+        with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
+            file_members: list[zipfile.ZipInfo] = []
+            expected_bytes = 0
+            for info in archive.infolist():
+                normalized = info.filename.replace("\\", "/")
+                if (
+                    not normalized
+                    or normalized.startswith("/")
+                    or re.match(r"^[A-Za-z]:", normalized)
+                ):
+                    raise PackagingError(
+                        f"unsafe archive member path in {archive_label}"
+                    )
+                handoff.normalize_relative(normalized.split("/"))
+                if info.flag_bits & 0x1:
+                    raise PackagingError(
+                        f"encrypted archive member is unsupported in {archive_label}"
+                    )
+                member_mode = (info.external_attr >> 16) & 0xFFFF
+                member_type = stat.S_IFMT(member_mode)
+                if info.is_dir():
+                    if (
+                        info.file_size != 0
+                        or info.compress_size != 0
+                        or member_type not in {0, stat.S_IFDIR}
+                    ):
+                        raise PackagingError(
+                            f"unsafe archive member type in {archive_label}"
+                        )
+                    continue
+                if member_type not in {0, stat.S_IFREG}:
+                    raise PackagingError(
+                        f"unsafe archive member type in {archive_label}"
+                    )
+                file_members.append(info)
+                expected_bytes += info.file_size
+    except (OSError, zipfile.BadZipFile) as exc:
+        raise PackagingError(
+            f"unable to inspect source archive: {archive_label}"
+        ) from exc
+
+    token = hashlib.sha256(archive_label.encode("utf-8")).hexdigest()[:16]
+    extract_root = temp_root / "expanded-archives" / token
+    extract_root.mkdir(parents=True, exist_ok=False)
+    actual_files: list[Path] = []
+    actual_bytes = 0
+    try:
+        with zipfile.ZipFile(item.candidate.absolute, "r") as archive:
+            for info in file_members:
+                parts = info.filename.replace("\\", "/").split("/")
+                target_path = extract_root / Path(*parts)
+                target_path.parent.mkdir(parents=True, exist_ok=True)
+                with archive.open(info, "r") as source, target_path.open("wb") as destination:
+                    shutil.copyfileobj(source, destination, length=1024 * 1024)
+                actual_files.append(target_path)
+                actual_bytes += target_path.stat().st_size
+    except (OSError, zipfile.BadZipFile) as exc:
+        raise PackagingError(
+            f"unable to extract source archive: {archive_label}"
+        ) from exc
+
+    if len(actual_files) != len(file_members) or actual_bytes != expected_bytes:
+        raise PackagingError(
+            f"archive extraction inventory mismatch: {archive_label} "
+            f"(files {len(actual_files)}/{len(file_members)}, bytes {actual_bytes}/{expected_bytes})"
+        )
+    expanded_candidates, expanded_excluded, _ = scan_analysis_root(
+        extract_root,
+        extra_exclusions=extra_exclusions,
+    )
+    handoff.audit_candidates(expanded_candidates)
+    expanded_prefix = f"{archive_label}.expanded"
+    expanded_items = [
+        PackageItem(
+            candidate=_rebase_candidate(candidate, expanded_prefix),
+            category=item.category,
+            source_id=item.source_id,
+            original_path=f"{item.original_path}!/{candidate.relative}",
+            scan_archive=True,
+        )
+        for candidate in expanded_candidates
+    ]
+    rebased_excluded = _rebase_exclusions(expanded_excluded, expanded_prefix)
+    sensitive_rules = {
+        "credential_or_license_file",
+        "credential_configuration_file",
+        "private_key_file",
+        "secret_environment_file",
+        "cloud_credential_file",
+        "container_registry_credential_file",
+    }
+    contains_sensitive = any(entry["rule"] in sensitive_rules for entry in expanded_excluded)
+    return expanded_items, rebased_excluded, contains_sensitive
+
+
 def prepare_unsupported_archives(
 def prepare_unsupported_archives(
     items: tuple[PackageItem, ...],
     items: tuple[PackageItem, ...],
     *,
     *,
@@ -1033,14 +1136,37 @@ def prepare_unsupported_archives(
         if archive_kind is None:
         if archive_kind is None:
             prepared.append(item)
             prepared.append(item)
             continue
             continue
-        if seven_zip is None:
-            raise PackagingError("7-Zip is required to inspect source archives")
-        expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
-            item,
-            temp_root=temp_root,
-            seven_zip=seven_zip,
-            extra_exclusions=extra_exclusions,
-        )
+        if archive_kind == "zip":
+            expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_zip_archive(
+                item,
+                temp_root=temp_root,
+                extra_exclusions=extra_exclusions,
+            )
+        elif seven_zip is None:
+            if _is_reference_item(item):
+                warnings.append(
+                    {
+                        "code": "unsupported_archive_without_7zip",
+                        "source_id": item.source_id,
+                        "path": item.candidate.relative,
+                        "message": "7-Zip is unavailable; unsupported archive kept unexpanded",
+                    }
+                )
+                prepared.append(item._replace(scan_archive=False))
+                continue
+            if item.candidate.absolute.is_file():
+                raise PackagingError(
+                    "7-Zip is required to inspect unsupported source archives"
+                )
+            prepared.append(item._replace(scan_archive=False))
+            continue
+        else:
+            expanded_items, expanded_excluded, contains_sensitive = _inspect_and_extract_unsupported_archive(
+                item,
+                temp_root=temp_root,
+                seven_zip=seven_zip,
+                extra_exclusions=extra_exclusions,
+            )
         has_filtered_members = bool(expanded_excluded)
         has_filtered_members = bool(expanded_excluded)
         if has_filtered_members:
         if has_filtered_members:
             prepared.extend(expanded_items)
             prepared.extend(expanded_items)
@@ -1241,57 +1367,40 @@ def _write_volume(
     )
     )
     manifest_name = "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json"
     manifest_name = "CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json"
     manifest_payload = handoff.json_bytes(manifest)
     manifest_payload = handoff.json_bytes(manifest)
-    seven_zip = find_7z()
-    if seven_zip is None:
-        raise PackagingError("7-Zip is required to create the analysis ZIP")
-    stage_path = Path(tempfile.mkdtemp(prefix=f".{path.stem}.", dir=path.parent))
     written_inventory: list[dict[str, object]] = []
     written_inventory: list[dict[str, object]] = []
-    archive_renames: list[tuple[str, str]] = []
     try:
     try:
-        staging_args = [(item_number, item) for item_number, item in enumerate(items)]
-
-        def _stage_one(args: tuple[int, PackageItem]) -> tuple[int, dict[str, object]]:
-            item_number, item = args
-            staging_name = f"candidate-{item_number:08d}"
-            return item_number, _stage_package_item(stage_path, item, staging_name)
-
-        max_workers = os.cpu_count() or 1
-        with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
-            staged = list(executor.map(_stage_one, staging_args))
-
-        for item_number, actual in staged:
-            item = items[item_number]
-            expected = inventory_by_path[item.candidate.relative]
-            if actual["size"] != expected["size"] or actual["sha256"] != expected["sha256"]:
-                raise PackagingError(f"source changed while writing ZIP: {item.candidate.relative}")
-            written_inventory.append(actual)
-            archive_renames.append(
-                (
-                    f"CPLD/candidate-{item_number:08d}",
-                    f"CPLD/{item.candidate.relative}",
-                )
-            )
-        manifest_staging_path = stage_path / "CPLD" / "metadata-manifest"
-        manifest_staging_path.parent.mkdir(parents=True, exist_ok=True)
-        manifest_staging_path.write_bytes(manifest_payload)
-        archive_renames.append(("CPLD/metadata-manifest", manifest_name))
-        _run_7z(
-            seven_zip,
-            build_7zip_create_command(path, stage_path),
-            cwd=stage_path,
-        )
-        _rename_archive_entries(seven_zip, path, archive_renames)
-
-        expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
-        expected_names.add(manifest_name)
-        handoff.verify_archive(
-            path,
-            expected_names=expected_names,
-            inventory=written_inventory,
-            expected_payloads={manifest_name: manifest_payload},
-        )
-    finally:
-        shutil.rmtree(stage_path, ignore_errors=True)
+        with zipfile.ZipFile(
+            path, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True
+        ) as archive:
+            for item in sorted(items, key=_item_sort_key):
+                expected = inventory_by_path[item.candidate.relative]
+                if item.scan_archive:
+                    actual = handoff.write_candidate(archive, item.candidate)
+                else:
+                    actual = _write_unscanned_candidate(archive, item)
+                if (
+                    actual["size"] != expected["size"]
+                    or actual["sha256"] != expected["sha256"]
+                ):
+                    raise PackagingError(
+                        f"source changed while writing ZIP: {item.candidate.relative}"
+                    )
+                written_inventory.append(actual)
+            with archive.open(
+                handoff.zip_info(manifest_name), "w", force_zip64=True
+            ) as target:
+                target.write(manifest_payload)
+    except (OSError, zipfile.BadZipFile) as exc:
+        raise PackagingError(f"unable to create ZIP volume: {exc}") from exc
+
+    expected_names = {f"CPLD/{item.candidate.relative}" for item in items}
+    expected_names.add(manifest_name)
+    handoff.verify_archive(
+        path,
+        expected_names=expected_names,
+        inventory=written_inventory,
+        expected_payloads={manifest_name: manifest_payload},
+    )
     return {
     return {
         "file": path.name,
         "file": path.name,
         "volume_number": number,
         "volume_number": number,
@@ -1924,8 +2033,6 @@ def main(argv: list[str] | None = None) -> int:
             payload = explain_analysis_path(args.explain, repo_root=source_root, config=config)
             payload = explain_analysis_path(args.explain, repo_root=source_root, config=config)
         else:
         else:
             seven_zip = find_7z()
             seven_zip = find_7z()
-            if seven_zip is None:
-                raise PackagingError("7-Zip is required for analysis packaging and archive inspection")
             _validate_package_name(package_name)
             _validate_package_name(package_name)
             output_root = _validate_output_root(args.output_dir, repo_root=source_root, config=config)
             output_root = _validate_output_root(args.output_dir, repo_root=source_root, config=config)
             with tempfile.TemporaryDirectory(prefix="ca-") as temporary:
             with tempfile.TemporaryDirectory(prefix="ca-") as temporary:

+ 141 - 35
tests/unit/test_build_firmware_package.py

@@ -5,6 +5,7 @@ from __future__ import annotations
 
 
 import json
 import json
 import shutil
 import shutil
+import subprocess
 import sys
 import sys
 import tempfile
 import tempfile
 import unittest
 import unittest
@@ -21,41 +22,78 @@ import build_firmware_package as builder
 ROOT = Path(__file__).resolve().parents[2]
 ROOT = Path(__file__).resolve().parents[2]
 
 
 
 
+def _write_report(path: Path, *, bitstream_sha256: str | None = None, project_sha: str | None = None) -> None:
+    project_sha = project_sha or "cb5c95298ea850740da82657bfaf9bc6dc8a220fac3700d3e05b0024a40a2d18"
+    if bitstream_sha256 is None:
+        bitstream_sha256 = "2ce6b1913b339453da963d4528ceb09ff93a26e61c9c14626d316bbd91f7243f"
+    report = {
+        "run_id": "td-run-123",
+        "verification_run_id": "88888888888888888888888888888888",
+        "commit_full": "fe1a0a2a19622b6f290905ec14795bb6cce6899d",
+        "project_config_sha256": project_sha,
+        "td_source_manifest_sha256": "8e0da456e865f3c3afa613d2660c1ed0ebf0e422ef51ec7acef223c2017a14bd",
+        "bitstream_sha256": bitstream_sha256,
+        "synthesis_input_manifest": {
+            "schema": "prod2u-simple-synthesis-inputs-v2",
+            "sha256": "aa9f59236f8ffb89df318eaa5ed5037523d7f46e8b838d45c1e3ab44b60bc423",
+            "inputs": {
+                "src/generated/prod2u_door_temp_params.vh": "ffcb0ffbaef92ef63f96ba7ed6a048cb85d3e9d8a1a5b553e458252446fc6950",
+                "projects/prod2u-door-temp/project.json": project_sha,
+                "src/generated/td-source-manifest.json": "8e0da456e865f3c3afa613d2660c1ed0ebf0e422ef51ec7acef223c2017a14bd",
+            },
+        },
+        "timing": {
+            "fmax_mhz": 90.49,
+            "worst_setup_slack_ns": 28.949,
+            "worst_hold_slack_ns": 0.046,
+        },
+        "resources": {
+            "utilization": {
+                "lut": {"used": 1113},
+                "reg": {"used": 677},
+                "bram": {"used": 0},
+                "dsp": {"used": 0},
+            },
+            "packing": {"total_slices": 570},
+        },
+    }
+    path.write_text(json.dumps(report), encoding="utf-8")
+
+
 class BuildFirmwarePackageTests(unittest.TestCase):
 class BuildFirmwarePackageTests(unittest.TestCase):
+    def _make_td_root(self, tmp_path: Path, *, bitstream_sha256: str | None = None, project_sha: str | None = None) -> tuple[Path, Path, Path]:
+        td_root = tmp_path / "td_root"
+        bitstream = td_root / "td" / "prod2u_p4_normal_v3" / "bitgen" / "prod2u_p4_normal_v3.bit"
+        bitstream.parent.mkdir(parents=True, exist_ok=True)
+        bitstream.write_bytes(b"FAKEBITS")
+        report = td_root / "report.json"
+        _write_report(report, bitstream_sha256=bitstream_sha256, project_sha=project_sha)
+        # Add a fake stage log to verify allowlist
+        (td_root / "td" / "prod2u_p4_normal_v3" / "syn").mkdir(parents=True, exist_ok=True)
+        (td_root / "td" / "prod2u_p4_normal_v3" / "syn" / "gate.qor").write_text("fake qor", encoding="utf-8")
+        return td_root, bitstream, report
+
+    def _commits(self) -> tuple[str, str, str]:
+        # Use the artifact commit for all three in tests so git comparison succeeds.
+        artifact = "fe1a0a2a19622b6f290905ec14795bb6cce6899d"
+        return (artifact, artifact, artifact)
+
     def test_build_with_fake_bitstream_and_report(self) -> None:
     def test_build_with_fake_bitstream_and_report(self) -> None:
         with tempfile.TemporaryDirectory() as tmp:
         with tempfile.TemporaryDirectory() as tmp:
             tmp_path = Path(tmp)
             tmp_path = Path(tmp)
-            bitstream = tmp_path / "fake.bit"
-            bitstream.write_bytes(b"FAKEBITS")
-            report = tmp_path / "report.json"
-            report.write_text(
-                json.dumps(
-                    {
-                        "utilization": {
-                            "lut": {"used": 1113},
-                            "reg": {"used": 677},
-                            "bram": {"used": 0},
-                            "dsp": {"used": 0},
-                        },
-                        "packing": {"total_slices": 570},
-                        "timing": {
-                            "fmax_mhz": 90.49,
-                            "worst_setup_slack_ns": 28.949,
-                            "worst_hold_slack_ns": 0.046,
-                        },
-                    }
-                ),
-                encoding="utf-8",
-            )
+            td_root, bitstream, report = self._make_td_root(tmp_path)
             output_dir = tmp_path / "dist"
             output_dir = tmp_path / "dist"
-            package = builder.build_firmware_package(
+            artifact, matrix, final_dev = self._commits()
+            package, sidecar = builder.build_firmware_package(
                 output_dir=output_dir,
                 output_dir=output_dir,
                 package_name="test-firmware-package",
                 package_name="test-firmware-package",
-                artifact_commit="fe1a0a2a19622b6f290905ec14795bb6cce6899d",
-                final_dev_commit="48defa6b591b3964fad9e4af637eb4ef4cc94110",
-                source_closure_unchanged=True,
+                td_root=td_root,
                 bitstream_path=bitstream,
                 bitstream_path=bitstream,
                 td_report_path=report,
                 td_report_path=report,
+                artifact_commit=artifact,
+                matrix_commit=matrix,
+                final_dev_commit=final_dev,
+                source_closure_unchanged=True,
             )
             )
             self.assertTrue(package.is_file())
             self.assertTrue(package.is_file())
             with zipfile.ZipFile(package, "r") as zipf:
             with zipfile.ZipFile(package, "r") as zipf:
@@ -64,29 +102,97 @@ class BuildFirmwarePackageTests(unittest.TestCase):
                 self.assertIn("BITSTREAM-SHA256.txt", names)
                 self.assertIn("BITSTREAM-SHA256.txt", names)
                 self.assertIn("PACKAGE-MANIFEST.json", names)
                 self.assertIn("PACKAGE-MANIFEST.json", names)
                 self.assertIn("SHA256SUMS.txt", names)
                 self.assertIn("SHA256SUMS.txt", names)
-                self.assertIn("project.json", names)
-                self.assertIn("SOURCE-CLOSURE-UNCHANGED.txt", names)
+                self.assertIn("td/original-final_td_report.json", names)
+                self.assertIn("td/TD-PROVENANCE.json", names)
+                self.assertIn("evidence/SOURCE-CLOSURE-COMPARISON.json", names)
+                self.assertIn("td/syn/gate.qor", names)
                 manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
                 manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
                 self.assertEqual(manifest["hardware_validation"], "not_run")
                 self.assertEqual(manifest["hardware_validation"], "not_run")
                 self.assertEqual(manifest["verification_scope"], "offline")
                 self.assertEqual(manifest["verification_scope"], "offline")
                 self.assertTrue(manifest["source_closure_unchanged"])
                 self.assertTrue(manifest["source_closure_unchanged"])
+                self.assertEqual(manifest["schema"], "prod2u-door-temp-final-package-manifest-v2")
                 sums = zipf.read("SHA256SUMS.txt").decode("utf-8")
                 sums = zipf.read("SHA256SUMS.txt").decode("utf-8")
                 self.assertIn("fw.bit", sums)
                 self.assertIn("fw.bit", sums)
 
 
+    def test_bitstream_report_mismatch_blocks(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            tmp_path = Path(tmp)
+            td_root, bitstream, report = self._make_td_root(tmp_path, bitstream_sha256="0" * 64)
+            artifact, matrix, final_dev = self._commits()
+            with self.assertRaises(builder.PackagingError):
+                builder.build_firmware_package(
+                    output_dir=tmp_path / "dist",
+                    package_name="mismatch",
+                    td_root=td_root,
+                    bitstream_path=bitstream,
+                    td_report_path=report,
+                    artifact_commit=artifact,
+                    matrix_commit=matrix,
+                    final_dev_commit=final_dev,
+                    source_closure_unchanged=True,
+                )
+
+    def test_report_outside_td_root_blocks(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            tmp_path = Path(tmp)
+            td_root, bitstream, _ = self._make_td_root(tmp_path)
+            other_report = tmp_path / "other_report.json"
+            _write_report(other_report)
+            artifact, matrix, final_dev = self._commits()
+            with self.assertRaises(builder.PackagingError):
+                builder.build_firmware_package(
+                    output_dir=tmp_path / "dist",
+                    package_name="bad-root",
+                    td_root=td_root,
+                    bitstream_path=bitstream,
+                    td_report_path=other_report,
+                    artifact_commit=artifact,
+                    matrix_commit=matrix,
+                    final_dev_commit=final_dev,
+                    source_closure_unchanged=True,
+                )
+
+    def test_stale_td_logs_not_in_package(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            tmp_path = Path(tmp)
+            td_root, bitstream, report = self._make_td_root(tmp_path)
+            # Place an old log in repo td/ that should not be included
+            (ROOT / "td" / "td_20260630_134648.log").write_text("stale", encoding="utf-8")
+            try:
+                artifact, matrix, final_dev = self._commits()
+                package, _ = builder.build_firmware_package(
+                    output_dir=tmp_path / "dist",
+                    package_name="no-stale",
+                    td_root=td_root,
+                    bitstream_path=bitstream,
+                    td_report_path=report,
+                    artifact_commit=artifact,
+                    matrix_commit=matrix,
+                    final_dev_commit=final_dev,
+                    source_closure_unchanged=True,
+                )
+                with zipfile.ZipFile(package, "r") as zipf:
+                    self.assertNotIn("td/td_20260630_134648.log", set(zipf.namelist()))
+            finally:
+                (ROOT / "td" / "td_20260630_134648.log").unlink(missing_ok=True)
+
     def test_missing_bitstream_blocks(self) -> None:
     def test_missing_bitstream_blocks(self) -> None:
         with tempfile.TemporaryDirectory() as tmp:
         with tempfile.TemporaryDirectory() as tmp:
             tmp_path = Path(tmp)
             tmp_path = Path(tmp)
-            report = tmp_path / "report.json"
-            report.write_text(json.dumps({"utilization": {}, "timing": {}}), encoding="utf-8")
+            td_root = tmp_path / "td_root"
+            td_root.mkdir(parents=True, exist_ok=True)
+            report = td_root / "report.json"
+            _write_report(report)
+            artifact, matrix, final_dev = self._commits()
             with self.assertRaises(FileNotFoundError):
             with self.assertRaises(FileNotFoundError):
                 builder.build_firmware_package(
                 builder.build_firmware_package(
                     output_dir=tmp_path / "dist",
                     output_dir=tmp_path / "dist",
-                    package_name="test",
-                    artifact_commit="a" * 40,
-                    final_dev_commit="b" * 40,
+                    package_name="missing",
+                    td_root=td_root,
+                    artifact_commit=artifact,
+                    matrix_commit=matrix,
+                    final_dev_commit=final_dev,
                     source_closure_unchanged=True,
                     source_closure_unchanged=True,
-                    bitstream_path=tmp_path / "missing.bit",
-                    td_report_path=report,
                 )
                 )
 
 
 
 

+ 110 - 10
tests/unit/test_package_for_agent_analysis.py

@@ -211,7 +211,7 @@ class PackageForAgentAnalysisTests(unittest.TestCase):
             )
             )
             self.assertEqual(excluded_by_path["unknown/evidence.bin"], "runtime_evidence_or_waveform")
             self.assertEqual(excluded_by_path["unknown/evidence.bin"], "runtime_evidence_or_waveform")
 
 
-    def test_7zip_is_required_for_package_creation(self) -> None:
+    def test_package_builds_without_7zip(self) -> None:
         analyzer = load_analyzer(self)
         analyzer = load_analyzer(self)
         with tempfile.TemporaryDirectory() as tmp:
         with tempfile.TemporaryDirectory() as tmp:
             temp = Path(tmp)
             temp = Path(tmp)
@@ -233,15 +233,115 @@ class PackageForAgentAnalysisTests(unittest.TestCase):
             )
             )
 
 
             with mock.patch.object(analyzer, "find_7z", return_value=None):
             with mock.patch.object(analyzer, "find_7z", return_value=None):
-                with self.assertRaisesRegex(analyzer.PackagingError, "7-Zip"):
-                    analyzer.create_analysis_package(
-                        collection=collection,
-                        output_root=temp / "output",
-                        package_name="requires-7z",
-                        max_zip_bytes=1_000_000,
-                        target_zip_bytes=800_000,
-                        force=False,
-                    )
+                result = analyzer.create_analysis_package(
+                    collection=collection,
+                    output_root=temp / "output",
+                    package_name="no-7z-fixture",
+                    max_zip_bytes=1_000_000,
+                    target_zip_bytes=800_000,
+                    force=False,
+                )
+
+            package_dir = Path(result["output_dir"])
+            self.assertEqual(result["status"], "pass")
+            self.assertEqual(len(result["volumes"]), 1)
+            volume = package_dir / result["volumes"][0]["file"]
+            self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
+            self.assertTrue((package_dir / "START-HERE.zh-CN.md").is_file())
+            self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
+            with zipfile.ZipFile(volume) as archive:
+                self.assertIsNone(archive.testzip())
+                names = archive.namelist()
+                self.assertIn("CPLD/workspace-current/src/core.v", names)
+                self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", names)
+                self.assertEqual(
+                    archive.read("CPLD/workspace-current/src/core.v"),
+                    b"module core; endmodule\n",
+                )
+
+    def test_zip_archive_expands_without_7zip(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            archive = temp / "vendor.zip"
+            with zipfile.ZipFile(archive, "w") as zf:
+                zf.writestr("docs/readme.txt", b"safe\n")
+                zf.writestr("build/demo.bit", b"bitstream\n")
+            item = analyzer.make_package_item(
+                archive,
+                relative="external/vendor/vendor.zip",
+                category="hardware",
+                source_id="vendor",
+            )
+
+            prepared = analyzer.prepare_unsupported_archives(
+                (item,),
+                temp_root=temp / "expanded",
+                seven_zip=None,
+                extra_exclusions=(),
+            )
+
+            paths = {it.candidate.relative for it in prepared.items}
+            self.assertIn("external/vendor/vendor.zip.expanded/docs/readme.txt", paths)
+            self.assertNotIn("external/vendor/vendor.zip.expanded/build/demo.bit", paths)
+            self.assertTrue(
+                any(
+                    entry["path"] == "external/vendor/vendor.zip"
+                    and entry["rule"] == "archive_contains_excluded_members"
+                    for entry in prepared.excluded
+                )
+            )
+
+    def test_unsupported_reference_archive_warns_without_7zip(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            archive = temp / "ref.7z"
+            archive.write_bytes(b"dummy")
+            item = analyzer.make_package_item(
+                archive,
+                relative="reference/original/ref.7z",
+                category="core",
+                source_id="ref",
+            )
+
+            prepared = analyzer.prepare_unsupported_archives(
+                (item,),
+                temp_root=temp / "expanded",
+                seven_zip=None,
+                extra_exclusions=(),
+            )
+
+            self.assertEqual(len(prepared.items), 1)
+            self.assertEqual(prepared.items[0].candidate.relative, "reference/original/ref.7z")
+            self.assertFalse(prepared.items[0].scan_archive)
+            self.assertTrue(
+                any(
+                    warning["code"] == "unsupported_archive_without_7zip"
+                    for warning in prepared.warnings
+                )
+            )
+
+    def test_unsupported_core_archive_raises_without_7zip(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            archive = temp / "core.7z"
+            archive.write_bytes(b"dummy")
+            item = analyzer.make_package_item(
+                archive,
+                relative="core/archive.7z",
+                category="core",
+                source_id="core",
+            )
+
+            with self.assertRaisesRegex(analyzer.PackagingError, "7-Zip"):
+                analyzer.prepare_unsupported_archives(
+                    (item,),
+                    temp_root=temp / "expanded",
+                    seven_zip=None,
+                    extra_exclusions=(),
+                )
 
 
     def test_7zip_creation_command_forces_standard_deflate_level_nine(self) -> None:
     def test_7zip_creation_command_forces_standard_deflate_level_nine(self) -> None:
         analyzer = load_analyzer(self)
         analyzer = load_analyzer(self)

+ 391 - 91
tools/build_firmware_package.py

@@ -1,13 +1,15 @@
 #!/usr/bin/env python3
 #!/usr/bin/env python3
 """Build the Prod2U door-temperature final firmware delivery package.
 """Build the Prod2U door-temperature final firmware delivery package.
 
 
-This is a thin deterministic wrapper that collects:
-- the canonical bitstream (reused when the production source closure is unchanged),
-- final TD reports,
+This is a deterministic wrapper that collects:
+- the canonical bitstream from an explicit TD root,
+- original and provenance-augmented TD reports,
+- source-closure comparison across artifact/matrix/final dev commits,
+- selected TD stage evidence (syn/phy/bitgen reports and logs),
 - source/contracts/TD inputs,
 - source/contracts/TD inputs,
 - generated host contract and golden vectors,
 - generated host contract and golden vectors,
 - verification receipts (when available),
 - verification receipts (when available),
-- package manifest and SHA-256 sums.
+- package manifest, SHA-256 sums, and an external selftest sidecar.
 
 
 It does not access COM/JTAG or program hardware.
 It does not access COM/JTAG or program hardware.
 """
 """
@@ -17,23 +19,29 @@ import argparse
 import hashlib
 import hashlib
 import json
 import json
 import shutil
 import shutil
+import subprocess
 import sys
 import sys
 import zipfile
 import zipfile
 from datetime import datetime, timezone
 from datetime import datetime, timezone
 from pathlib import Path
 from pathlib import Path
 from typing import Any
 from typing import Any
 
 
+
 ROOT = Path(__file__).resolve().parents[1]
 ROOT = Path(__file__).resolve().parents[1]
-TD_PRIMARY = Path.home() / "CodexTemp" / "cpld-td-primary2"
-BITSTREAM = TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "bitgen" / "prod2u_p4_normal_v3.bit"
-TD_REPORT = TD_PRIMARY / "report.json"
-REPORT_DIRS = [
-    ("syn", TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "syn"),
-    ("phy", TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "phy"),
-    ("bitgen", TD_PRIMARY / "td" / "prod2u_p4_normal_v3" / "bitgen"),
+
+TD_STAGE_SUFFIXES = {".rpt", ".timing", ".area", ".qor", ".log", ".logw"}
+REPO_TD_INPUTS = [
+    "td/prod2u_p4_normal_v3.prj",
+    "td/syn/prod2u_p4_normal_v3.tcl",
+    "td/phy/prod2u_p4_normal_v3.tcl",
+    "td/bitgen/prod2u_p4_normal_v3.tcl",
 ]
 ]
 
 
 
 
+class PackagingError(RuntimeError):
+    """Raised when the firmware package cannot be produced safely."""
+
+
 def _sha256_file(path: Path) -> str:
 def _sha256_file(path: Path) -> str:
     digest = hashlib.sha256()
     digest = hashlib.sha256()
     with path.open("rb") as stream:
     with path.open("rb") as stream:
@@ -42,63 +50,340 @@ def _sha256_file(path: Path) -> str:
     return digest.hexdigest()
     return digest.hexdigest()
 
 
 
 
+def _sha256_bytes(data: bytes) -> str:
+    return hashlib.sha256(data).hexdigest()
+
+
 def _read_json(path: Path) -> Any:
 def _read_json(path: Path) -> Any:
     return json.loads(path.read_text(encoding="utf-8-sig"))
     return json.loads(path.read_text(encoding="utf-8-sig"))
 
 
 
 
-def _copy_into(dst: Path, src: Path, rel: str) -> None:
-    target = dst / rel
-    target.parent.mkdir(parents=True, exist_ok=True)
-    shutil.copy2(src, target)
+def _git_show_file(repo_root: Path, commit: str, relative_path: str) -> bytes:
+    """Return the contents of a tracked path at a specific commit."""
+    completed = subprocess.run(
+        ["git", "-C", str(repo_root), "show", f"{commit}:{relative_path}"],
+        stdout=subprocess.PIPE,
+        stderr=subprocess.PIPE,
+        check=False,
+    )
+    if completed.returncode != 0:
+        raise PackagingError(
+            f"git show failed for {commit}:{relative_path}: {completed.stderr.decode('utf-8', errors='ignore').strip()}"
+        )
+    return completed.stdout
+
+
+def _resolve_path(path: Path) -> Path:
+    return Path(path).expanduser().resolve()
+
+
+def _inside(root: Path, candidate: Path) -> bool:
+    """Return True if candidate is root or under root."""
+    root = _resolve_path(root)
+    candidate = _resolve_path(candidate)
+    try:
+        candidate.relative_to(root)
+        return True
+    except ValueError:
+        return False
+
+
+def _validate_td_root(
+    *,
+    td_root: Path,
+    bitstream_path: Path,
+    td_report_path: Path,
+) -> None:
+    """Ensure bitstream and report belong to the selected TD root."""
+    if not _inside(td_root, bitstream_path):
+        raise PackagingError(f"bitstream {bitstream_path} is outside selected td_root {td_root}")
+    if not _inside(td_root, td_report_path):
+        raise PackagingError(f"td report {td_report_path} is outside selected td_root {td_root}")
+
+
+def _bitstream_path_from_td_root(td_root: Path) -> Path:
+    return _resolve_path(td_root / "td" / "prod2u_p4_normal_v3" / "bitgen" / "prod2u_p4_normal_v3.bit")
+
+
+def _report_path_from_td_root(td_root: Path) -> Path:
+    return _resolve_path(td_root / "report.json")
+
 
 
+def generate_source_closure_comparison(
+    *,
+    td_report: dict[str, Any],
+    artifact_commit: str,
+    matrix_commit: str,
+    final_dev_commit: str,
+    repo_root: Path = ROOT,
+) -> dict[str, Any]:
+    """Compare synthesis inputs across artifact, matrix, and final dev commits."""
+    inputs = td_report.get("synthesis_input_manifest", {}).get("inputs", {})
+    if not inputs:
+        raise PackagingError("TD report has no synthesis_input_manifest.inputs")
+
+    entries: list[dict[str, Any]] = []
+    production_changed_paths: list[str] = []
+    all_same = True
+
+    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"
+            all_same = False
+            if values[0] != values[2]:
+                production_changed_paths.append(relative_path)
+
+        entries.append(row)
+
+    comparison_text = json.dumps(
+        {
+            "artifact_source_commit": artifact_commit,
+            "matrix_commit": matrix_commit,
+            "final_dev_commit": final_dev_commit,
+            "source_closure_equal": all_same,
+            "production_changed_paths": production_changed_paths,
+            "entries": entries,
+        },
+        sort_keys=True,
+    )
+    source_set_sha256 = _sha256_bytes(comparison_text.encode("utf-8"))
+
+    return {
+        "schema": "prod2u-source-closure-comparison-v1",
+        "artifact_source_commit": artifact_commit,
+        "matrix_commit": matrix_commit,
+        "final_dev_commit": final_dev_commit,
+        "source_closure_equal": all_same,
+        "production_changed_paths": production_changed_paths,
+        "source_set_sha256": source_set_sha256,
+        "inputs": entries,
+    }
+
+
+def generate_td_provenance(
+    *,
+    original_report: dict[str, Any],
+    artifact_commit: str,
+    source_closure_comparison_sha256: str,
+    bitstream_sha256: str,
+    matrix_run_id: str | None,
+) -> dict[str, Any]:
+    """Bind the original TD run to the current matrix and source closure."""
+    return {
+        "schema": "prod2u-td-provenance-v1",
+        "status": "bound_by_source_closure_comparison",
+        "artifact_source_commit": artifact_commit,
+        "original_td_run_id": original_report.get("run_id"),
+        "original_placeholder_verification_run_id": original_report.get("verification_run_id"),
+        "matrix_run_id": matrix_run_id,
+        "source_closure_comparison_sha256": source_closure_comparison_sha256,
+        "bitstream_sha256": bitstream_sha256,
+        "original_report_path": "td/original-final_td_report.json",
+        "project_config_sha256": original_report.get("project_config_sha256"),
+        "td_source_manifest_sha256": original_report.get("td_source_manifest_sha256"),
+        "synthesis_input_manifest_sha256": original_report.get("synthesis_input_manifest", {}).get("sha256"),
+    }
 
 
-def _add_file(zipf: zipfile.ZipFile, src: Path, arcname: str) -> None:
+
+def _add_file(zipf: zipfile.ZipFile, src: Path, arcname: str, sha256_entries: list[str]) -> None:
     zipf.write(src, arcname)
     zipf.write(src, arcname)
+    sha256_entries.append(f"{_sha256_file(src)}  {arcname}")
+
+
+def _add_text(zipf: zipfile.ZipFile, text: str, arcname: str, sha256_entries: list[str]) -> None:
+    payload = text.encode("utf-8")
+    zipf.writestr(arcname, payload)
+    sha256_entries.append(f"{_sha256_bytes(payload)}  {arcname}")
 
 
 
 
-def _add_text(zipf: zipfile.ZipFile, text: str, arcname: str) -> None:
-    zipf.writestr(arcname, text.encode("utf-8"))
+def _collect_td_stage_files(td_root: Path) -> list[tuple[Path, str]]:
+    """Collect allowed evidence files from the selected TD build stages."""
+    collected: list[tuple[Path, str]] = []
+    stages = ["syn", "phy", "bitgen"]
+    for stage in stages:
+        stage_dir = _resolve_path(td_root / "td" / "prod2u_p4_normal_v3" / stage)
+        if not stage_dir.is_dir():
+            continue
+        for item in stage_dir.iterdir():
+            if item.is_file() and item.suffix.casefold() in TD_STAGE_SUFFIXES:
+                collected.append((item, f"td/{stage}/{item.name}"))
+    return collected
+
+
+def _selftest_package(
+    *,
+    zip_path: Path,
+    expected_manifest: dict[str, Any],
+    td_root: Path,
+) -> dict[str, Any]:
+    """Verify the built firmware package before writing the sidecar."""
+    failures: list[str] = []
+    with zipfile.ZipFile(zip_path, "r", allowZip64=True) as zipf:
+        names = set(zipf.namelist())
+        required = {
+            "fw.bit",
+            "BITSTREAM-SHA256.txt",
+            "ARTIFACT-SOURCE-COMMIT.txt",
+            "MATRIX-COMMIT.txt",
+            "FINAL-DEV-COMMIT.txt",
+            "SOURCE-CLOSURE-UNCHANGED.txt",
+            "PACKAGE-MANIFEST.json",
+            "SHA256SUMS.txt",
+            "td/original-final_td_report.json",
+            "td/TD-PROVENANCE.json",
+            "evidence/SOURCE-CLOSURE-COMPARISON.json",
+            "project.json",
+            "config/source_closure.json",
+        }
+        missing = sorted(required - names)
+        if missing:
+            failures.append(f"missing_required_files:{missing}")
+
+        bad = zipf.testzip()
+        if bad is not None:
+            failures.append(f"crc_failed:{bad}")
+
+        manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
+        if manifest["bitstream_sha256"] != expected_manifest["bitstream_sha256"]:
+            failures.append("bitstream_sha_manifest_mismatch")
+
+        # Detect stale repo TD logs from ROOT/td that should not be present
+        for name in names:
+            if name.startswith("td/") and "td_20260630" in name:
+                failures.append(f"stale_td_log_in_package:{name}")
+
+    return {
+        "status": "fail" if failures else "pass",
+        "failures": failures,
+        "package_path": str(zip_path),
+        "package_sha256": _sha256_file(zip_path),
+        "td_root": str(td_root),
+    }
 
 
 
 
 def build_firmware_package(
 def build_firmware_package(
     *,
     *,
     output_dir: Path,
     output_dir: Path,
     package_name: str | None,
     package_name: str | None,
+    td_root: Path,
     artifact_commit: str,
     artifact_commit: str,
+    matrix_commit: str,
     final_dev_commit: str,
     final_dev_commit: str,
     source_closure_unchanged: bool,
     source_closure_unchanged: bool,
-    bitstream_path: Path = BITSTREAM,
-    td_report_path: Path = TD_REPORT,
-    evidence_dir: Path | None = None,
-) -> Path:
+    bitstream_path: Path | None = None,
+    td_report_path: Path | None = None,
+    matrix_receipt_path: Path | None = None,
+    matrix_run_id: str | None = None,
+) -> tuple[Path, Path]:
+    """Build and selftest the final firmware ZIP."""
+    td_root = _resolve_path(td_root)
+    if bitstream_path is None:
+        bitstream_path = _bitstream_path_from_td_root(td_root)
+    if td_report_path is None:
+        td_report_path = _report_path_from_td_root(td_root)
+    bitstream_path = _resolve_path(bitstream_path)
+    td_report_path = _resolve_path(td_report_path)
+
+    _validate_td_root(td_root=td_root, bitstream_path=bitstream_path, td_report_path=td_report_path)
+
     if not bitstream_path.is_file():
     if not bitstream_path.is_file():
         raise FileNotFoundError(f"bitstream not found: {bitstream_path}")
         raise FileNotFoundError(f"bitstream not found: {bitstream_path}")
     if not td_report_path.is_file():
     if not td_report_path.is_file():
         raise FileNotFoundError(f"TD report not found: {td_report_path}")
         raise FileNotFoundError(f"TD report not found: {td_report_path}")
 
 
+    td_report = _read_json(td_report_path)
     bitstream_sha256 = _sha256_file(bitstream_path)
     bitstream_sha256 = _sha256_file(bitstream_path)
-    name = package_name or f"prod2u-door-temp-final-{artifact_commit[:8]}-{bitstream_sha256[:8]}"
-    output_dir = Path(output_dir).resolve()
-    output_dir.mkdir(parents=True, exist_ok=True)
-    zip_path = output_dir / f"{name}.zip"
-    if zip_path.exists():
-        zip_path.unlink()
 
 
-    td_report = _read_json(td_report_path)
+    # Strong binding checks
+    report_bitstream_sha = td_report.get("bitstream_sha256")
+    if report_bitstream_sha and report_bitstream_sha != bitstream_sha256:
+        raise PackagingError(
+            f"TD report bitstream_sha256 {report_bitstream_sha} does not match actual {bitstream_sha256}"
+        )
+
+    report_commit = td_report.get("commit_full") or td_report.get("commit")
+    if report_commit and report_commit != artifact_commit:
+        raise PackagingError(
+            f"TD report commit {report_commit} does not match artifact_source_commit {artifact_commit}"
+        )
+
+    report_project_sha = td_report.get("project_config_sha256")
+    current_project_sha = _sha256_file(ROOT / "projects" / "prod2u-door-temp" / "project.json")
+    if report_project_sha and report_project_sha != current_project_sha:
+        raise PackagingError(
+            f"TD report project_config_sha256 {report_project_sha} does not match current {current_project_sha}"
+        )
+
+    comparison = generate_source_closure_comparison(
+        td_report=td_report,
+        artifact_commit=artifact_commit,
+        matrix_commit=matrix_commit,
+        final_dev_commit=final_dev_commit,
+        repo_root=ROOT,
+    )
+    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"]:
+        raise PackagingError(
+            f"source_closure_unchanged requested but comparison differs: {comparison['production_changed_paths']}"
+        )
+
+    comparison_json = json.dumps(comparison, indent=2, sort_keys=True) + "\n"
+    comparison_sha256 = _sha256_bytes(comparison_json.encode("utf-8"))
+
+    provenance = generate_td_provenance(
+        original_report=td_report,
+        artifact_commit=artifact_commit,
+        source_closure_comparison_sha256=comparison_sha256,
+        bitstream_sha256=bitstream_sha256,
+        matrix_run_id=matrix_run_id,
+    )
+    provenance_json = json.dumps(provenance, indent=2, sort_keys=True) + "\n"
+    provenance_sha256 = _sha256_bytes(provenance_json.encode("utf-8"))
+
     timing = td_report.get("timing", {})
     timing = td_report.get("timing", {})
     resources_section = td_report.get("resources", {})
     resources_section = td_report.get("resources", {})
     utilization = resources_section.get("utilization", {})
     utilization = resources_section.get("utilization", {})
 
 
     manifest: dict[str, Any] = {
     manifest: dict[str, Any] = {
-        "schema": "prod2u-door-temp-final-package-manifest-v1",
-        "package_name": name,
+        "schema": "prod2u-door-temp-final-package-manifest-v2",
+        "package_name": package_name or f"prod2u-door-temp-final-{artifact_commit[:8]}-{bitstream_sha256[:8]}",
+        "status": "VERIFIED_OFFLINE",
         "created_at": datetime.now(timezone.utc).isoformat(),
         "created_at": datetime.now(timezone.utc).isoformat(),
-        "artifact_source_commit": artifact_commit,
-        "final_dev_commit": final_dev_commit,
-        "source_closure_unchanged": source_closure_unchanged,
         "verification_scope": "offline",
         "verification_scope": "offline",
         "hardware_validation": "not_run",
         "hardware_validation": "not_run",
+        "artifact_source_commit": artifact_commit,
+        "matrix_commit": matrix_commit,
+        "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"],
+        "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"),
+        "source_closure_comparison_sha256": comparison_sha256,
         "bitstream_sha256": bitstream_sha256,
         "bitstream_sha256": bitstream_sha256,
+        "matrix_receipt_sha256": _sha256_file(matrix_receipt_path) if matrix_receipt_path and matrix_receipt_path.is_file() else None,
+        "original_td_receipt_sha256": _sha256_file(td_report_path),
+        "td_provenance_sha256": provenance_sha256,
         "resources": {
         "resources": {
             "lut": utilization.get("lut", {}).get("used"),
             "lut": utilization.get("lut", {}).get("used"),
             "register": utilization.get("reg", {}).get("used"),
             "register": utilization.get("reg", {}).get("used"),
@@ -113,104 +398,119 @@ def build_firmware_package(
         },
         },
     }
     }
 
 
-    sha256_entries: list[str] = []
-
-    def add_and_hash(src: Path, arcname: str) -> None:
-        _add_file(zipf, src, arcname)
-        sha256_entries.append(f"{_sha256_file(src)}  {arcname}")
+    output_dir = _resolve_path(output_dir)
+    output_dir.mkdir(parents=True, exist_ok=True)
+    name = manifest["package_name"]
+    zip_path = output_dir / f"{name}.zip"
+    if zip_path.exists():
+        zip_path.unlink()
 
 
-    def add_text_and_hash(text: str, arcname: str) -> None:
-        _add_text(zipf, text, arcname)
-        sha256_entries.append(f"{hashlib.sha256(text.encode('utf-8')).hexdigest()}  {arcname}")
+    sha256_entries: list[str] = []
 
 
-    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
+    with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as zipf:
         # Bitstream and provenance
         # Bitstream and provenance
-        add_and_hash(bitstream_path, "fw.bit")
-        add_text_and_hash(bitstream_sha256, "BITSTREAM-SHA256.txt")
-        add_text_and_hash(artifact_commit, "ARTIFACT-SOURCE-COMMIT.txt")
-        add_text_and_hash(final_dev_commit, "FINAL-DEV-COMMIT.txt")
-        add_text_and_hash(
-            "true" if source_closure_unchanged else "false",
-            "SOURCE-CLOSURE-UNCHANGED.txt",
-        )
+        _add_file(zipf, bitstream_path, "fw.bit", sha256_entries)
+        _add_text(zipf, bitstream_sha256, "BITSTREAM-SHA256.txt", sha256_entries)
+        _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)
 
 
-        # Final TD report and selected report files
-        add_and_hash(td_report_path, "td/final_td_report.json")
-        for stage, stage_dir in REPORT_DIRS:
-            if stage_dir.is_dir():
-                for item in stage_dir.iterdir():
-                    if item.is_file() and item.suffix.casefold() in {
-                        ".rpt", ".timing", ".area", ".qor", ".log"
-                    }:
-                        add_and_hash(item, f"td/{stage}/{item.name}")
+        # Original TD report and provenance
+        _add_file(zipf, td_report_path, "td/original-final_td_report.json", sha256_entries)
+        _add_text(zipf, provenance_json, "td/TD-PROVENANCE.json", sha256_entries)
+
+        # Selected TD stage evidence from the explicit TD root
+        for src, arcname in _collect_td_stage_files(td_root):
+            _add_file(zipf, src, arcname, sha256_entries)
 
 
         # Project contract and protocol
         # Project contract and protocol
-        add_and_hash(ROOT / "projects" / "prod2u-door-temp" / "project.json", "project.json")
-        add_and_hash(ROOT / "projects" / "prod2u-door-temp" / "requirements.zh-CN.md", "requirements.zh-CN.md")
-        add_and_hash(ROOT / "docs" / "prod2u-door-temp-protocol.zh-CN.md", "docs/prod2u-door-temp-protocol.zh-CN.md")
+        _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "project.json", "project.json", sha256_entries)
+        _add_file(zipf, ROOT / "projects" / "prod2u-door-temp" / "requirements.zh-CN.md", "requirements.zh-CN.md", sha256_entries)
+        _add_file(zipf, ROOT / "docs" / "prod2u-door-temp-protocol.zh-CN.md", "docs/prod2u-door-temp-protocol.zh-CN.md", sha256_entries)
 
 
         # Generated artifacts
         # Generated artifacts
         for gen in (ROOT / "src" / "generated").iterdir():
         for gen in (ROOT / "src" / "generated").iterdir():
             if gen.is_file():
             if gen.is_file():
-                add_and_hash(gen, f"src/generated/{gen.name}")
+                _add_file(zipf, gen, f"src/generated/{gen.name}", sha256_entries)
 
 
-        # Constraints and TD inputs
+        # Constraints
         for adc in (ROOT / "constraints").iterdir():
         for adc in (ROOT / "constraints").iterdir():
             if adc.is_file():
             if adc.is_file():
-                add_and_hash(adc, f"constraints/{adc.name}")
-        for td_item in (ROOT / "td").rglob("*"):
-            if td_item.is_file():
-                rel = td_item.relative_to(ROOT / "td")
-                if rel.parts and rel.parts[0] == "build":
-                    continue
-                arcname = "td/" + "/".join(rel.parts)
-                add_and_hash(td_item, arcname)
+                _add_file(zipf, adc, f"constraints/{adc.name}", sha256_entries)
+
+        # Tracked TD inputs from the repo (not the build root)
+        for td_input in REPO_TD_INPUTS:
+            src = ROOT / td_input
+            if src.is_file():
+                _add_file(zipf, src, td_input, sha256_entries)
 
 
         # Source closure manifest
         # Source closure manifest
-        add_and_hash(ROOT / "config" / "source_closure.json", "config/source_closure.json")
+        _add_file(zipf, ROOT / "config" / "source_closure.json", "config/source_closure.json", sha256_entries)
 
 
-        # Optional verification/matrix evidence
-        if evidence_dir is not None and evidence_dir.is_dir():
-            for ev_file in evidence_dir.rglob("*"):
-                if ev_file.is_file():
-                    arcname = "evidence/" + "/".join(ev_file.relative_to(evidence_dir).parts)
-                    add_and_hash(ev_file, arcname)
+        # Source-closure comparison
+        _add_text(zipf, comparison_json, "evidence/SOURCE-CLOSURE-COMPARISON.json", sha256_entries)
+
+        # Optional matrix receipt
+        if matrix_receipt_path and matrix_receipt_path.is_file():
+            _add_file(zipf, matrix_receipt_path, "evidence/matrix-receipt.json", sha256_entries)
 
 
         # Manifest and SHA256SUMS
         # Manifest and SHA256SUMS
         manifest_text = json.dumps(manifest, indent=2, sort_keys=True) + "\n"
         manifest_text = json.dumps(manifest, indent=2, sort_keys=True) + "\n"
-        add_text_and_hash(manifest_text, "PACKAGE-MANIFEST.json")
-        add_text_and_hash("\n".join(sha256_entries) + "\n", "SHA256SUMS.txt")
+        _add_text(zipf, manifest_text, "PACKAGE-MANIFEST.json", sha256_entries)
+        _add_text(zipf, "\n".join(sha256_entries) + "\n", "SHA256SUMS.txt", sha256_entries)
+
+    selftest = _selftest_package(zip_path=zip_path, expected_manifest=manifest, td_root=td_root)
+    if selftest["status"] != "pass":
+        zip_path.unlink(missing_ok=True)
+        raise PackagingError(f"firmware package selftest failed: {selftest['failures']}")
 
 
-    return zip_path
+    selftest["package_selftest_status"] = "pass"
+    selftest["manifest"] = manifest
+
+    sidecar_path = output_dir / f"{name}.selftest.json"
+    sidecar_path.write_text(json.dumps(selftest, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+    return zip_path, sidecar_path
 
 
 
 
 def main(argv: list[str] | None = None) -> int:
 def main(argv: list[str] | None = None) -> int:
     parser = argparse.ArgumentParser(description=__doc__)
     parser = argparse.ArgumentParser(description=__doc__)
     parser.add_argument("--output-dir", type=Path, default=Path.home() / "Downloads" / "CPLD-firmware")
     parser.add_argument("--output-dir", type=Path, default=Path.home() / "Downloads" / "CPLD-firmware")
     parser.add_argument("--package-name", help="package base name (default from commit/bitstream)")
     parser.add_argument("--package-name", help="package base name (default from commit/bitstream)")
+    parser.add_argument("--td-root", type=Path, required=True)
+    parser.add_argument("--bitstream", type=Path, default=None)
+    parser.add_argument("--td-report", type=Path, default=None)
     parser.add_argument("--artifact-commit", required=True)
     parser.add_argument("--artifact-commit", required=True)
+    parser.add_argument("--matrix-commit", required=True)
     parser.add_argument("--final-dev-commit", required=True)
     parser.add_argument("--final-dev-commit", required=True)
     parser.add_argument("--source-closure-unchanged", action="store_true")
     parser.add_argument("--source-closure-unchanged", action="store_true")
-    parser.add_argument("--bitstream", type=Path, default=BITSTREAM)
-    parser.add_argument("--td-report", type=Path, default=TD_REPORT)
-    parser.add_argument("--evidence-dir", type=Path, default=None)
+    parser.add_argument("--matrix-receipt", type=Path, default=None)
+    parser.add_argument("--matrix-run-id", default=None)
     args = parser.parse_args(argv)
     args = parser.parse_args(argv)
 
 
     try:
     try:
-        path = build_firmware_package(
+        zip_path, sidecar_path = build_firmware_package(
             output_dir=args.output_dir,
             output_dir=args.output_dir,
             package_name=args.package_name,
             package_name=args.package_name,
+            td_root=args.td_root,
             artifact_commit=args.artifact_commit,
             artifact_commit=args.artifact_commit,
+            matrix_commit=args.matrix_commit,
             final_dev_commit=args.final_dev_commit,
             final_dev_commit=args.final_dev_commit,
             source_closure_unchanged=args.source_closure_unchanged,
             source_closure_unchanged=args.source_closure_unchanged,
             bitstream_path=args.bitstream,
             bitstream_path=args.bitstream,
             td_report_path=args.td_report,
             td_report_path=args.td_report,
-            evidence_dir=args.evidence_dir,
+            matrix_receipt_path=args.matrix_receipt,
+            matrix_run_id=args.matrix_run_id,
         )
         )
-    except FileNotFoundError as exc:
-        print(f"blocked: {exc}", file=sys.stderr)
+    except (FileNotFoundError, PackagingError) as exc:
+        print(f"error: {exc}", file=sys.stderr)
         return 1
         return 1
-    print(json.dumps({"status": "pass", "package": str(path), "bitstream": str(BITSTREAM)}, indent=2))
+    print(
+        json.dumps(
+            {"status": "pass", "package": str(zip_path), "selftest": str(sidecar_path)},
+            indent=2,
+        )
+    )
     return 0
     return 0