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

fix(packaging): emit live Git provenance for review-compact

Collect HEAD/branch/status/log-20/tree/source-file-sha256 from exact
DELIVERY via git CLI + git archive (linked worktrees), fail closed when
missing, stabilize raw reference fingerprint without inventory timestamps,
and separate detached/live test profiles plus CLI alt-config coverage.

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

+ 1 - 1
ACCEPTANCE_MATRIX.md

@@ -25,7 +25,7 @@
 | Full matrix @ ARTIFACT-SOURCE | 软件矩阵 + TD receipts 绑定本轮 run;DELIVERY-COMMIT 见包内 `FINAL-DEV-COMMIT.txt` / `meta/git/HEAD.txt` | pass(硬件除外) |
 | TD + bitstream | Linux `td2026` Release_2026.1_SP2 Build `6.2.2.200067` @ **`f23d6d4c57959071cd3886ea5503fbe903aee547`**;bit SHA-256 `eb275921a3c25dcd9440c02677ea9b910e2bf5e57517bbad4ee063afa93e760a`(RUN `20260806T112210Z-3f2f5f2f`;旧 bit `3143b87c…` 已取代) | pass |
 | 历史旁路 bit(非 tip) | `45f548ab…` built @ `bb515af` | historical only — **不是** current |
-| Package / replay | firmware + compact + reference 三卷绑定最终 tip | 打包阶段 |
+| Package / replay | review-compact 含 live Git provenance(`meta/git/HEAD.txt`/tree/source-file-sha256);firmware + release-set 交叉绑定;detached replay 用包内 manifest;raw reference 复用且不进默认 compact;Hardware NOT RUN | pass(本轮 selftest/release-set;Hardware 除外) |
 | Physical hardware | COM/JTAG/烧录未授权 | **`not_run`** |
 
 ## Physical / board notes

+ 1 - 0
FINAL_DELIVERY_REPORT.md

@@ -11,6 +11,7 @@
 - 权威工具链为 **Linux**(`td2026` + OSS CAD / Python 验证)。
 - 最终 tip TD / bitstream:**已绑定**(见下表)。历史旁路 bit `45f548ab…` @ `bb515af` **不是** tip。
 - Hardware **`NOT RUN`**。
+- Package:review-compact 必须含 live `meta/git/` provenance(HEAD/tree/source-file-sha256);raw reference 复用且不进默认 compact;firmware + release-set 外部交叉绑定。生产输入相对 ARTIFACT `f23d6d4c…` 未变时不重跑 TD,复用 bitstream `eb275921…`。
 
 ## 关键标识(活动)
 

+ 7 - 0
PACKAGE_FOR_AGENT_ANALYSIS.README.zh-CN.md

@@ -36,6 +36,13 @@ python3 package_for_agent_analysis.py \
 tools/package-review-compact.sh
 ```
 
+Git provenance(review-compact **强制**):
+
+- 必须从 exact DELIVERY 的 **live Git 工作树**(含 linked worktree)打包;在去除 `.git` 之前生成 `meta/git/HEAD.txt`、`branch.txt`、`status.txt`、`log-20.txt`、`tree-manifest.json`、`source-file-sha256.json`。
+- tree/逐文件 SHA-256 来自 `git archive <commit>`,不是脏工作区扫描。
+- 无 live Git 时 **fail closed**(不再静默只写 `sanitized-snapshot-status=not_applicable` 的“成功包”)。
+- 可选 `--include-sanitized-git-snapshot` 不能代替上述 provenance,也不能冒充原始 tip。
+
 可选:
 
 - `--include-sanitized-git-snapshot`:可选合成单 commit 快照(`meta/git/sanitized-snapshot.bundle` + mapping;明确 synthetic→original,不冒充原始 tip)

+ 3 - 0
PLAN.md

@@ -10,6 +10,8 @@
 - Contract/source baseline tip: `cdf9f76b22d75f1c2bc1e7ff99a49d2897a8dcb7` (docs/contract lane start)
 - Hardware validation: **`not_run`**
 - Active IO: CON104/105/106/120/12/129 — **not** solenoid / CON68 / CON34 / CON138–141; runtime limit **not** inert
+- Package / replay: review-compact live Git provenance + firmware/release-set closure;raw reference reused(不进默认 compact);ARTIFACT/bitstream 复用 `f23d6d4` / `eb275921`(生产输入未变,不重跑 TD)
+- 三种状态:默认生产离线固件闭包 PASS;逐轴编译期配置能力 PASS;Hardware NOT RUN
 
 ## Closure sequence
 
@@ -17,6 +19,7 @@
 2. ~~Exclusive `td2026` on clean tip; bind full bitstream SHA-256~~ done.
 3. Full matrix + three-volume package; activity docs identity filled.
 4. Independent read-only review session (parent launches).
+5. Git provenance / detached replay / stable reference fingerprint / release-set upload closure(本轮).
 
 ## Authority
 

+ 40 - 2
package_for_agent_analysis.py

@@ -1101,18 +1101,42 @@ def collect_analysis_inputs(
         items.append(bundle_item)
         git_metadata.append(bundle_metadata)
     elif unified:
+        # review-* must collect live Git provenance (linked worktrees OK via git CLI).
+        # Fail closed: never ship a "success" package with only sanitized-snapshot-status.
         provenance, provenance_artifacts = handoff.collect_review_git_provenance(
             root,
             include_sanitized_git_snapshot=include_sanitized_git_snapshot,
             meta_prefix="meta/git",
-            temp_root=temp_root / "sanitized-git",
+            temp_root=temp_root / "review-git",
+            require_clean=(profile == "review-compact"),
+            commit=binding_commit,
         )
+        if profile in {"review-compact", "review-debug"}:
+            prov_status = str(provenance.get("status") or "")
+            if prov_status != "pass":
+                raise PackagingError(
+                    "review package requires live Git provenance "
+                    f"(HEAD/branch/status/log-20/tree/source-file-sha256); "
+                    f"got status={prov_status!r}. "
+                    "Package from an exact DELIVERY Git worktree/repo — "
+                    "sanitized-snapshot-status alone is not sufficient."
+                )
+            prov_failures = handoff.validate_review_git_provenance_artifacts(
+                provenance_artifacts,
+                meta_prefix="meta/git",
+                expected_head=str(provenance.get("head") or "") or None,
+            )
+            if prov_failures:
+                raise PackagingError(
+                    "review Git provenance artifacts incomplete/inconsistent: "
+                    + ", ".join(prov_failures)
+                )
         binding = handoff.build_td_source_closure_binding(
             root,
             bitstream_path=bitstream_path,
             td_report_paths=td_report_paths,
             evidence_root=evidence_root,
-            commit=binding_commit,
+            commit=binding_commit or str(provenance.get("head") or "") or None,
             require_bitstream=require_bitstream_binding,
         )
         binding_bytes = handoff.json_bytes(binding)
@@ -1286,6 +1310,20 @@ def collect_analysis_inputs(
                 raise PackagingError(
                     f"source-closure relations inconsistent: {rel_check['failures']}"
                 )
+            # Explicit dual-commit fields (keep commit_full for compatibility).
+            binding["artifact_source_commit"] = artifact
+            binding["delivery_commit"] = delivery
+            binding["artifact_to_delivery_unchanged"] = bool(
+                art_to_del.get("source_closure_equal")
+            )
+            binding["td_run_id"] = td_run
+            if binding.get("commit_full") in {None, "", artifact} and delivery:
+                binding["commit_full"] = delivery
+                binding["commit_short"] = delivery[:8]
+            # Re-encode binding after enriching identity fields.
+            binding_bytes = handoff.json_bytes(binding)
+            provenance_artifacts["meta/td/td-source-closure-binding.json"] = binding_bytes
+            provenance_artifacts["meta/td-source-closure-binding.json"] = binding_bytes
             provenance_artifacts["meta/SOURCE-CLOSURE-COMPARISON-ART-TO-DEL.json"] = (
                 handoff.json_bytes(art_to_del)
             )

+ 27 - 23
tests/unit/test_alt_config_rtl_matrix.py

@@ -210,29 +210,6 @@ class AltConfigRtlMatrixTests(unittest.TestCase):
             close_limit_is_ls=[True, True, False],
         )
 
-    def test_public_cli_generates_alt_params_for_rtl(self) -> None:
-        """CLI path (not only Python API) must feed the same include layout."""
-        import sys
-
-        with tempfile.TemporaryDirectory(prefix="alt-cli-") as tmp:
-            tmp_path = Path(tmp)
-            pj = _write_alt_project(
-                tmp_path,
-                limit_active_high=[False, True, True],
-                dir_close_level=[1, 1, 1],
-                close_limit_is_ls=[True, True, True],
-            )
-            out = tmp_path / "out"
-            proc = subprocess.run(
-                [sys.executable, str(ROOT / "tools" / "generate_project.py"), str(pj), str(out)],
-                capture_output=True,
-                text=True,
-                check=False,
-            )
-            self.assertEqual(proc.returncode, 0, proc.stderr or proc.stdout)
-            params = (out / "generated" / "prod2u_door_temp_params.vh").read_text(encoding="ascii")
-            self.assertIn("`define P4_LIMIT_ACTIVE_HIGH_MASK 3'b110", params)
-
     # --- Startup 5000+500 behavioral matrix (public generate path) ---
 
     def test_startup_default(self) -> None:
@@ -276,6 +253,33 @@ class AltConfigRtlMatrixTests(unittest.TestCase):
         )
 
 
+class AltConfigPublicCliTests(unittest.TestCase):
+    """Python/CLI-only — must run even when Icarus is unavailable."""
+
+    def test_public_cli_generates_alt_params_for_rtl(self) -> None:
+        """CLI path (not only Python API) must feed the same include layout."""
+        import sys
+
+        with tempfile.TemporaryDirectory(prefix="alt-cli-") as tmp:
+            tmp_path = Path(tmp)
+            pj = _write_alt_project(
+                tmp_path,
+                limit_active_high=[False, True, True],
+                dir_close_level=[1, 1, 1],
+                close_limit_is_ls=[True, True, True],
+            )
+            out = tmp_path / "out"
+            proc = subprocess.run(
+                [sys.executable, str(ROOT / "tools" / "generate_project.py"), str(pj), str(out)],
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(proc.returncode, 0, proc.stderr or proc.stdout)
+            params = (out / "generated" / "prod2u_door_temp_params.vh").read_text(encoding="ascii")
+            self.assertIn("`define P4_LIMIT_ACTIVE_HIGH_MASK 3'b110", params)
+
+
 class AltConfigFormalNormalizeTests(unittest.TestCase):
     """BMC/cover only — never claim infinite prove for alt-config normalize."""
 

+ 20 - 1
tests/unit/test_evidence_canon.py

@@ -5,6 +5,8 @@ from __future__ import annotations
 
 import importlib.util
 import json
+import shutil
+import subprocess
 import sys
 import tempfile
 import unittest
@@ -36,6 +38,22 @@ def write_file(root: Path, relative: str, payload: bytes) -> Path:
     return path
 
 
+def init_git_repo(repo: Path) -> None:
+    """review-compact fail-closed requires live Git provenance."""
+    git = shutil.which("git")
+    if not git:
+        raise unittest.SkipTest("Git is required")
+    repo.mkdir(parents=True, exist_ok=True)
+    subprocess.run([git, "init", "-q", str(repo)], check=True)
+    subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
+    subprocess.run(
+        [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
+        check=True,
+    )
+    subprocess.run([git, "-C", str(repo), "add", "-A"], check=True)
+    subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
+
+
 class EvidenceCanonUnitTests(unittest.TestCase):
     def test_allowlist_loads_and_lists_compact_keys(self) -> None:
         allowlist = evidence_canon.load_allowlist()
@@ -206,7 +224,7 @@ class EvidenceCanonPackagerIntegrationTests(unittest.TestCase):
                 "receipts/deep-reviews/round-1-product-protocol.json",
                 b'{"round":1}\n',
             )
-            # Minimal git not required for collect when include_git_bundle forced off.
+            init_git_repo(repo)
             config = analyzer.HandoffConfig(
                 max_zip_bytes=5_000_000,
                 target_zip_bytes=4_000_000,
@@ -279,6 +297,7 @@ class EvidenceCanonPackagerIntegrationTests(unittest.TestCase):
                 "lane-status/lane-f-td.json",
                 b'{"status":"pass"}\n',
             )
+            init_git_repo(repo)
             config = analyzer.HandoffConfig(
                 max_zip_bytes=5_000_000,
                 target_zip_bytes=4_000_000,

+ 3 - 0
tests/unit/test_package_for_agent_analysis.py

@@ -499,8 +499,11 @@ class PackageForAgentAnalysisTests(unittest.TestCase):
             self.assertEqual(Path(sources_by_id["review-worktree"]["path"]), review.resolve())
             for item in collection.items:
                 if item.candidate.relative.startswith("git-history/"):
+                    # Verify inside a real Git repo cwd — never mis-blame tool
+                    # behavior when cwd is a non-repository (detached extract).
                     result = subprocess.run(
                         [git, "bundle", "verify", str(item.candidate.absolute)],
+                        cwd=str(repo),
                         capture_output=True,
                         text=True,
                         check=False,

+ 51 - 0
tests/unit/test_release_set_provenance.py

@@ -59,8 +59,59 @@ class ReleaseSetProvenanceTests(unittest.TestCase):
         fp = pkg_prov.reference_set_fingerprint(ROOT)
         dumped = json.dumps(fp["parts"], sort_keys=True)
         self.assertNotIn("generated_at", dumped)
+        self.assertNotIn("inventory_sha256", dumped)
+        self.assertNotIn("repository_root", dumped)
         self.assertEqual(fp["parts"]["reference_package_sha256"], pkg_prov.REFERENCE_PACKAGE_SHA256)
 
+    def test_reference_fingerprint_stable_across_inventory_timestamps(self) -> None:
+        """Regenerating inventory generated_at/repository_root must not drift raw fp."""
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            inv = {
+                "schema": "prod2u-reference-inventory-v1",
+                "generated_at_utc": "2026-01-01T00:00:00+00:00",
+                "repository_root": "/tmp/path-a",
+                "evidence_boundaries": {
+                    "v1_2_schematic_pdf": {"status": "not_provided"},
+                    "historical_schematic_side_evidence": "reference/original/schematics/x.pdf",
+                },
+                "board_viewer": {"generated_at": "2026-01-01T00:00:00+00:00"},
+            }
+            (root / "docs").mkdir(parents=True)
+            inv_path = root / "docs" / "REFERENCE-INVENTORY.json"
+            inv_path.write_text(json.dumps(inv) + "\n", encoding="utf-8")
+            fp1 = pkg_prov.reference_set_fingerprint(root)["sha256"]
+            inv["generated_at_utc"] = "2099-01-01T00:00:00+00:00"
+            inv["repository_root"] = "/tmp/totally-different-abs-path"
+            inv["board_viewer"]["generated_at"] = "2099-01-01T00:00:00+00:00"
+            inv_path.write_text(json.dumps(inv) + "\n", encoding="utf-8")
+            fp2 = pkg_prov.reference_set_fingerprint(root)["sha256"]
+            self.assertEqual(fp1, fp2)
+            # Semantic change must move fingerprint.
+            inv["evidence_boundaries"]["v1_2_schematic_pdf"]["status"] = "provided"
+            inv_path.write_text(json.dumps(inv) + "\n", encoding="utf-8")
+            fp3 = pkg_prov.reference_set_fingerprint(root)["sha256"]
+            self.assertNotEqual(fp1, fp3)
+
+    def test_reference_fingerprint_changes_with_raw_identity(self) -> None:
+        base = pkg_prov.reference_set_fingerprint(ROOT)
+        parts = dict(base["parts"])
+        parts["reference_package_sha256"] = "a" * 64
+        changed = pkg_prov._sha256_bytes(
+            json.dumps(parts, sort_keys=True, separators=(",", ":")).encode("utf-8")
+        )
+        self.assertNotEqual(base["sha256"], changed)
+        parts2 = dict(base["parts"])
+        parts2["canonical_brd_sha256"] = "b" * 64
+        changed2 = pkg_prov._sha256_bytes(
+            json.dumps(parts2, sort_keys=True, separators=(",", ":")).encode("utf-8")
+        )
+        self.assertNotEqual(base["sha256"], changed2)
+        # Derived fingerprint is independent of raw fp parts.
+        derived = pkg_prov.derived_board_viewer_identity(ROOT)
+        self.assertNotEqual(derived["sha256"], base["sha256"])
+        self.assertEqual(len(derived["sha256"]), 64)
+
     def test_relations_consistency_negatives(self) -> None:
         # unchanged=false + empty paths + commit_compare → FAIL
         bad_empty = pkg_prov.build_source_closure_relations(

+ 32 - 4
tests/unit/test_replay_review_compact.py

@@ -58,12 +58,32 @@ def load_replay() -> ModuleType:
 
 class GitWorktreeModeTests(unittest.TestCase):
     def test_detect_live_git_on_repo_root(self) -> None:
+        """Construct a real live Git fixture — do not assume arbitrary ROOT is live."""
         git_mode = load_git_mode()
-        # Clear override for this assertion.
+        git = shutil.which("git")
+        if not git:
+            self.skipTest("Git is required")
         old = os.environ.pop(git_mode.ENV_GIT_MODE, None)
         try:
-            mode = git_mode.detect_git_mode(ROOT)
-            self.assertEqual(mode, git_mode.LIVE_GIT)
+            with tempfile.TemporaryDirectory() as tmp:
+                repo = Path(tmp) / "live-repo"
+                repo.mkdir()
+                subprocess.run([git, "init", "-q", str(repo)], check=True)
+                subprocess.run(
+                    [git, "-C", str(repo), "config", "user.name", "Test"], check=True
+                )
+                subprocess.run(
+                    [git, "-C", str(repo), "config", "user.email", "t@example.invalid"],
+                    check=True,
+                )
+                write_file(repo, "tracked.txt", b"live\n")
+                subprocess.run([git, "-C", str(repo), "add", "tracked.txt"], check=True)
+                subprocess.run(
+                    [git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True
+                )
+                mode = git_mode.detect_git_mode(repo)
+                self.assertEqual(mode, git_mode.LIVE_GIT)
+                self.assertEqual(git_mode.live_only_status(repo), "pass")
         finally:
             if old is not None:
                 os.environ[git_mode.ENV_GIT_MODE] = old
@@ -112,8 +132,16 @@ class GitWorktreeModeTests(unittest.TestCase):
             old = os.environ.pop(git_mode.ENV_GIT_MODE, None)
             try:
                 probe = Probe()
-                with self.assertRaises(unittest.SkipTest):
+                with self.assertRaises(unittest.SkipTest) as raised:
                     git_mode.require_live_git(root, probe)
+                self.assertEqual(
+                    str(raised.exception),
+                    git_mode.NOT_APPLICABLE_BY_PACKAGE_POLICY,
+                )
+                self.assertEqual(
+                    git_mode.live_only_status(root),
+                    git_mode.NOT_APPLICABLE_BY_PACKAGE_POLICY,
+                )
             finally:
                 if old is not None:
                     os.environ[git_mode.ENV_GIT_MODE] = old

+ 236 - 0
tests/unit/test_review_git_provenance.py

@@ -0,0 +1,236 @@
+"""Positive/negative tests for review-compact live Git provenance (fail-closed)."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from types import ModuleType
+
+
+ROOT = Path(__file__).resolve().parents[2]
+TOOLS = ROOT / "tools"
+
+
+def load_handoff() -> ModuleType:
+    sys.path.insert(0, str(TOOLS))
+    path = TOOLS / "package_agent_handoff.py"
+    spec = importlib.util.spec_from_file_location("package_agent_handoff_prov", path)
+    assert spec is not None and spec.loader is not None
+    module = importlib.util.module_from_spec(spec)
+    sys.modules[spec.name] = module
+    spec.loader.exec_module(module)
+    return module
+
+
+def load_analyzer() -> ModuleType:
+    path = ROOT / "package_for_agent_analysis.py"
+    spec = importlib.util.spec_from_file_location("package_for_agent_analysis_prov", path)
+    assert spec is not None and spec.loader is not None
+    module = importlib.util.module_from_spec(spec)
+    sys.modules[spec.name] = module
+    spec.loader.exec_module(module)
+    return module
+
+
+def write_file(root: Path, relative: str, data: bytes = b"x\n") -> Path:
+    path = root / Path(relative)
+    path.parent.mkdir(parents=True, exist_ok=True)
+    path.write_bytes(data)
+    return path
+
+
+def init_repo(repo: Path) -> str:
+    git = shutil.which("git")
+    if not git:
+        raise unittest.SkipTest("Git is required")
+    repo.mkdir(parents=True, exist_ok=True)
+    subprocess.run([git, "init", "-q", str(repo)], check=True)
+    subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
+    subprocess.run(
+        [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
+        check=True,
+    )
+    write_file(repo, "src/core.v", b"module core; endmodule\n")
+    write_file(repo, "README.md", b"fixture\n")
+    subprocess.run([git, "-C", str(repo), "add", "-A"], check=True)
+    subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
+    return git
+
+
+class ReviewGitProvenanceTests(unittest.TestCase):
+    def test_live_repo_emits_required_meta_git_files(self) -> None:
+        handoff = load_handoff()
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            repo = temp / "repo"
+            init_repo(repo)
+            provenance, artifacts = handoff.collect_review_git_provenance(
+                repo,
+                temp_root=temp / "prov",
+                require_clean=True,
+            )
+            self.assertEqual(provenance["status"], "pass")
+            self.assertTrue(handoff.COMMIT_FULL_RE.fullmatch(str(provenance["head"])))
+            for key in (
+                "meta/git/HEAD.txt",
+                "meta/git/branch.txt",
+                "meta/git/status.txt",
+                "meta/git/log-20.txt",
+                "meta/git/tree-manifest.json",
+                "meta/git/source-file-sha256.json",
+            ):
+                self.assertIn(key, artifacts, key)
+            failures = handoff.validate_review_git_provenance_artifacts(
+                artifacts, expected_head=str(provenance["head"])
+            )
+            self.assertEqual(failures, [])
+
+    def test_linked_worktree_is_live_for_provenance(self) -> None:
+        handoff = load_handoff()
+        git = shutil.which("git")
+        if not git:
+            self.skipTest("Git is required")
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            repo = temp / "repo"
+            init_repo(repo)
+            wt = temp / "linked-wt"
+            subprocess.run(
+                [git, "-C", str(repo), "worktree", "add", "--detach", str(wt), "HEAD"],
+                check=True,
+                capture_output=True,
+            )
+            # Security resolver still rejects external gitdir…
+            self.assertIsNone(handoff.resolve_git_dir(wt))
+            # …but CLI-based collector must succeed.
+            self.assertTrue(handoff.live_git_cli_usable(wt))
+            provenance, artifacts = handoff.collect_review_git_provenance(
+                wt, temp_root=temp / "prov", require_clean=True
+            )
+            self.assertEqual(provenance["status"], "pass", provenance)
+            self.assertIn("meta/git/HEAD.txt", artifacts)
+
+    def test_gitless_source_returns_not_a_git_worktree(self) -> None:
+        handoff = load_handoff()
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp) / "plain"
+            write_file(root, "src/core.v", b"module core; endmodule\n")
+            provenance, artifacts = handoff.collect_review_git_provenance(root)
+            self.assertEqual(provenance["status"], "not_a_git_worktree")
+            self.assertNotIn("meta/git/HEAD.txt", artifacts)
+            self.assertIn("meta/git/sanitized-snapshot-status.json", artifacts)
+
+    def test_review_compact_fail_closed_without_git(self) -> None:
+        analyzer = load_analyzer()
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            repo = temp / "plain"
+            write_file(repo, "src/core.v", b"module core; endmodule\n")
+            config = analyzer.HandoffConfig(
+                max_zip_bytes=5_000_000,
+                target_zip_bytes=4_000_000,
+                external_sources=(),
+                extra_exclusions=(),
+            )
+            with self.assertRaises(analyzer.PackagingError) as raised:
+                analyzer.collect_analysis_inputs(
+                    repo_root=repo,
+                    config=config,
+                    temp_root=temp / "run",
+                    include_git_bundle=False,
+                    profile="review-compact",
+                    package_name="fail-closed",
+                )
+            self.assertIn("live Git provenance", str(raised.exception))
+
+    def test_dirty_tracked_source_fails_when_require_clean(self) -> None:
+        handoff = load_handoff()
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            repo = temp / "repo"
+            init_repo(repo)
+            write_file(repo, "src/core.v", b"module dirty; endmodule\n")
+            provenance, _artifacts = handoff.collect_review_git_provenance(
+                repo, temp_root=temp / "prov", require_clean=True
+            )
+            self.assertEqual(provenance["status"], "fail_dirty_worktree")
+
+    def test_tree_manifest_validation_negatives(self) -> None:
+        handoff = load_handoff()
+        head = "a" * 40
+        good_tree = {
+            "schema": "cpld-review-git-tree-manifest-v1",
+            "head": head,
+            "file_count": 1,
+            "files": [{"path": "src/core.v", "sha256": "b" * 64, "size": 1}],
+        }
+        good_files = {
+            "schema": "cpld-review-git-file-sha256-v1",
+            "head": head,
+            "files": {"src/core.v": "b" * 64},
+        }
+        base = {
+            "meta/git/HEAD.txt": f"{head}\n".encode(),
+            "meta/git/branch.txt": b"dev\n",
+            "meta/git/status.txt": b"## dev\n",
+            "meta/git/log-20.txt": f"{head} msg\n".encode(),
+            "meta/git/tree-manifest.json": json.dumps(good_tree).encode(),
+            "meta/git/source-file-sha256.json": json.dumps(good_files).encode(),
+        }
+        self.assertEqual(handoff.validate_review_git_provenance_artifacts(base), [])
+
+        missing = dict(base)
+        del missing["meta/git/HEAD.txt"]
+        self.assertTrue(
+            any("missing_" in f for f in handoff.validate_review_git_provenance_artifacts(missing))
+        )
+
+        wrong_head = dict(base)
+        wrong_head["meta/git/HEAD.txt"] = b"c" * 40 + b"\n"
+        self.assertIn(
+            "HEAD_tree_file_sha_inconsistent",
+            handoff.validate_review_git_provenance_artifacts(wrong_head),
+        )
+
+        short_tree = dict(base)
+        short_tree["meta/git/tree-manifest.json"] = json.dumps(
+            {**good_tree, "file_count": 0, "files": []}
+        ).encode()
+        short_tree["meta/git/source-file-sha256.json"] = json.dumps(
+            {**good_files, "files": {}}
+        ).encode()
+        fails = handoff.validate_review_git_provenance_artifacts(short_tree)
+        self.assertTrue(any("empty" in f or "count" in f for f in fails), fails)
+
+        tampered = dict(base)
+        tampered_files = {**good_files, "files": {"src/core.v": "d" * 64}}
+        tampered["meta/git/source-file-sha256.json"] = json.dumps(tampered_files).encode()
+        self.assertTrue(
+            any(
+                "file_hash_mismatch" in f or "path_mismatch" in f
+                for f in handoff.validate_review_git_provenance_artifacts(tampered)
+            )
+        )
+
+    def test_wrong_commit_argument_fails(self) -> None:
+        handoff = load_handoff()
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            repo = temp / "repo"
+            init_repo(repo)
+            provenance, _ = handoff.collect_review_git_provenance(
+                repo,
+                temp_root=temp / "prov",
+                commit="0" * 40,
+            )
+            self.assertEqual(provenance["status"], "fail_invalid_commit")
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 14 - 7
tools/git_worktree_mode.py

@@ -28,6 +28,7 @@ DETACHED = "detached"
 GIT_MODES = frozenset({LIVE_GIT, SNAPSHOT, DETACHED})
 
 ENV_GIT_MODE = "PRODU2_GIT_MODE"
+NOT_APPLICABLE_BY_PACKAGE_POLICY = "not_applicable_by_package_policy"
 
 
 def _tools_dir() -> Path:
@@ -133,23 +134,29 @@ def detect_git_mode(root: Path | None = None) -> str:
 
 
 def require_live_git(root: Path, testcase: Any | None = None) -> str:
-    """Assert or skip unless ``root`` is in ``live_git`` mode.
+    """Assert live_git, or mark detached/snapshot as policy-not-applicable.
 
-    When ``testcase`` is a unittest.TestCase, skips instead of raising so
-    compact/detached replay hosts stay green. Live worktrees remain strict.
+    Live repository lanes stay strict (commit-compare required). Detached
+    review-compact lanes must not fake ``.git``; they report
+    ``not_applicable_by_package_policy`` (exact token — not a vague skip).
     """
     mode = detect_git_mode(root)
     if mode == LIVE_GIT:
         return mode
-    message = (
-        f"requires live_git (raw .git); current mode={mode} under {root}. "
-        "Compact/detached packages are Git-optional by policy."
-    )
+    message = NOT_APPLICABLE_BY_PACKAGE_POLICY
     if testcase is not None and hasattr(testcase, "skipTest"):
         testcase.skipTest(message)
     raise RuntimeError(message)
 
 
+def live_only_status(root: Path | None = None) -> str:
+    """Return ``pass`` when live_git, else ``not_applicable_by_package_policy``."""
+    mode = detect_git_mode(root or Path.cwd())
+    if mode == LIVE_GIT:
+        return "pass"
+    return NOT_APPLICABLE_BY_PACKAGE_POLICY
+
+
 def git_optional_ok(root: Path | None = None) -> bool:
     """True when software checks may run without raw ``.git``."""
     return detect_git_mode(root) in {SNAPSHOT, DETACHED, LIVE_GIT}

+ 285 - 37
tools/package_agent_handoff.py

@@ -1785,22 +1785,147 @@ def create_sanitized_git_snapshot(
     return status, artifacts
 
 
+def live_git_cli_usable(root: Path) -> bool:
+    """True when ``git -C root`` reports an inside-work-tree checkout.
+
+    Unlike ``resolve_git_dir``, this accepts linked worktrees whose ``gitdir:``
+    points outside the worktree root (required for clean DELIVERY worktrees).
+    """
+    git = shutil.which("git")
+    if not git:
+        return False
+    code, payload = run_capture(
+        [git, "rev-parse", "--is-inside-work-tree"],
+        cwd=root,
+    )
+    return code == 0 and payload.decode("ascii", errors="replace").strip() == "true"
+
+
+def _hash_exact_commit_tree(
+    git: str,
+    root: Path,
+    commit: str,
+    *,
+    temp_root: Path,
+) -> tuple[list[dict[str, object]], dict[str, str], list[str]]:
+    """SHA-256 tracked files from exact commit via ``git archive`` (not dirty WT)."""
+    work = temp_root / f"commit-tree-{commit[:12]}"
+    if work.exists():
+        shutil.rmtree(work)
+    work.mkdir(parents=True, exist_ok=True)
+    tar_path = temp_root / f"commit-tree-{commit[:12]}.tar"
+    code, err = run_capture(
+        [git, "archive", "--format=tar", "-o", str(tar_path), commit],
+        cwd=root,
+        timeout=600,
+    )
+    if code != 0 or not tar_path.is_file():
+        detail = err.decode("utf-8", errors="replace")[:500]
+        raise PackagingError(
+            f"git archive {commit} failed for review provenance: {detail}"
+        )
+    with tarfile.open(tar_path, "r:") as archive:
+        # filter='data' avoids 3.14 deprecation and blocks unsafe paths.
+        try:
+            archive.extractall(work, filter="data")
+        except TypeError:
+            archive.extractall(work)
+    tree_rows: list[dict[str, object]] = []
+    file_hashes: dict[str, str] = {}
+    file_rels: list[str] = []
+    for path in sorted(work.rglob("*")):
+        if not path.is_file():
+            continue
+        rel = path.relative_to(work).as_posix()
+        digest = sha256_file(path)
+        file_rels.append(rel)
+        file_hashes[rel] = digest
+        tree_rows.append({"path": rel, "sha256": digest, "size": path.stat().st_size})
+    return tree_rows, file_hashes, file_rels
+
+
+def validate_review_git_provenance_artifacts(
+    artifacts: dict[str, bytes],
+    *,
+    meta_prefix: str = "meta/git",
+    expected_head: str | None = None,
+) -> list[str]:
+    """Fail-closed checks for review-compact Git provenance members."""
+    failures: list[str] = []
+    required = (
+        f"{meta_prefix}/HEAD.txt",
+        f"{meta_prefix}/branch.txt",
+        f"{meta_prefix}/status.txt",
+        f"{meta_prefix}/log-20.txt",
+        f"{meta_prefix}/tree-manifest.json",
+        f"{meta_prefix}/source-file-sha256.json",
+    )
+    for key in required:
+        if key not in artifacts:
+            failures.append(f"missing_{key.replace('/', '_')}")
+    head_raw = artifacts.get(f"{meta_prefix}/HEAD.txt", b"").decode("utf-8", errors="replace").strip()
+    if not COMMIT_FULL_RE.fullmatch(head_raw.casefold()):
+        failures.append("invalid_HEAD")
+    if expected_head and head_raw.casefold() != expected_head.casefold():
+        failures.append("HEAD_mismatch_expected")
+    try:
+        tree = json.loads(artifacts.get(f"{meta_prefix}/tree-manifest.json", b"{}"))
+        files = json.loads(
+            artifacts.get(
+                f"{meta_prefix}/source-file-sha256.json",
+                artifacts.get(f"{meta_prefix}/file-sha256.json", b"{}"),
+            )
+        )
+    except (TypeError, json.JSONDecodeError):
+        failures.append("invalid_tree_or_file_sha_json")
+        return failures
+    tree_head = str(tree.get("head") or "")
+    files_head = str(files.get("head") or "")
+    if tree_head.casefold() != head_raw.casefold() or files_head.casefold() != head_raw.casefold():
+        failures.append("HEAD_tree_file_sha_inconsistent")
+    tree_files = tree.get("files") if isinstance(tree.get("files"), list) else []
+    hash_map = files.get("files") if isinstance(files.get("files"), dict) else {}
+    if int(tree.get("file_count") or 0) != len(tree_files):
+        failures.append("tree_manifest_count_mismatch")
+    if len(tree_files) == 0:
+        failures.append("tree_manifest_empty")
+    tree_paths = {str(row.get("path")) for row in tree_files if isinstance(row, dict)}
+    if tree_paths != set(hash_map):
+        failures.append("tree_manifest_hash_map_path_mismatch")
+    for row in tree_files:
+        if not isinstance(row, dict):
+            continue
+        path = str(row.get("path") or "")
+        digest = str(row.get("sha256") or "")
+        if path and hash_map.get(path) != digest:
+            failures.append(f"file_hash_mismatch:{path}")
+            break
+    return failures
+
+
 def collect_review_git_provenance(
     root: Path,
     *,
     include_sanitized_git_snapshot: bool = False,
     meta_prefix: str = "meta/git",
     temp_root: Path | None = None,
+    require_clean: bool = False,
+    commit: str | None = None,
 ) -> tuple[dict[str, object], dict[str, bytes]]:
-    """Git provenance for review-* packages: no full bundle; commit/status/log/tree/hashes."""
-    git_dir = resolve_git_dir(root)
+    """Git provenance for review-* packages: no full bundle; commit/status/log/tree/hashes.
+
+    Uses the live ``git`` CLI so linked DELIVERY worktrees work even when
+    ``resolve_git_dir`` rejects an external ``gitdir:``. Tree/file SHA-256 are
+    taken from the exact commit via ``git archive``, never from a dirty WT scan.
+    """
     artifacts: dict[str, bytes] = {}
-    if git_dir is None:
+    git = shutil.which("git")
+    if not git or not live_git_cli_usable(root):
         metadata: dict[str, object] = {
             "status": "not_a_git_worktree",
             "branch": None,
             "head": None,
-            "tool": None,
+            "tool": None if not git else "git",
             "full_bundle": False,
             "sanitized_git_snapshot": {
                 "requested": include_sanitized_git_snapshot,
@@ -1812,13 +1937,11 @@ def collect_review_git_provenance(
         )
         return metadata, artifacts
 
-    branch, head = read_head_metadata(git_dir)
-    git = shutil.which("git")
     if not git:
         return {
             "status": "blocked_missing_git_tool",
-            "branch": branch,
-            "head": head,
+            "branch": None,
+            "head": None,
             "tool": None,
             "full_bundle": False,
             "sanitized_git_snapshot": {
@@ -1834,6 +1957,80 @@ def collect_review_git_provenance(
             )
         }
 
+    rev_parse = _git_bytes(git, ["rev-parse", "HEAD"], cwd=root)
+    head = (
+        rev_parse.decode("utf-8", errors="replace").strip()
+        if rev_parse is not None
+        else None
+    )
+    if commit:
+        # Format-check alone is insufficient — commit must exist in this repo.
+        verified = _git_bytes(
+            git,
+            ["rev-parse", "--verify", f"{commit}^{{commit}}"],
+            cwd=root,
+        )
+        if verified is None:
+            return {
+                "status": "fail_invalid_commit",
+                "branch": None,
+                "head": head,
+                "tool": "git",
+                "full_bundle": False,
+                "sanitized_git_snapshot": {
+                    "requested": include_sanitized_git_snapshot,
+                    "status": "not_applicable",
+                },
+            }, {
+                f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(
+                    {
+                        "requested": include_sanitized_git_snapshot,
+                        "status": "not_applicable",
+                    }
+                )
+            }
+        head = verified.decode("utf-8", errors="replace").strip().casefold()
+    if not head or not COMMIT_FULL_RE.fullmatch(head.casefold()):
+        return {
+            "status": "fail_missing_HEAD",
+            "branch": None,
+            "head": head,
+            "tool": "git",
+            "full_bundle": False,
+            "sanitized_git_snapshot": {
+                "requested": include_sanitized_git_snapshot,
+                "status": "not_applicable",
+            },
+        }, {
+            f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(
+                {
+                    "requested": include_sanitized_git_snapshot,
+                    "status": "not_applicable",
+                }
+            )
+        }
+    head = head.casefold()
+
+    branch_raw = _git_bytes(git, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
+    branch = (
+        branch_raw.decode("utf-8", errors="replace").strip()
+        if branch_raw is not None
+        else None
+    )
+    if branch == "HEAD":
+        # Detached HEAD at exact DELIVERY — record detached + commit, not fake branch.
+        branch = f"detached:{head}"
+
+    # Prefer embedded .git metadata when packager-safe; CLI remains authority.
+    git_dir = resolve_git_dir(root)
+    if git_dir is not None:
+        meta_branch, meta_head = read_head_metadata(git_dir)
+        if meta_branch and not str(branch).startswith("detached:"):
+            branch = meta_branch
+        if meta_head and COMMIT_FULL_RE.fullmatch(meta_head.casefold()) and not commit:
+            # Keep CLI HEAD (exact tip) as authority when packing current tip.
+            pass
+
     status_payload = _git_bytes(
         git,
         [
@@ -1849,34 +2046,77 @@ def collect_review_git_provenance(
         ],
         cwd=root,
     )
+    # Dirty = modified/staged tracked files vs HEAD. Untracked-only noise does not
+    # affect git-archive commit snapshots; still recorded for status.txt honesty.
+    porcelain = _git_bytes(
+        git,
+        [
+            "--no-optional-locks",
+            "-c",
+            "core.fsmonitor=false",
+            "status",
+            "--porcelain=v1",
+            "--untracked-files=no",
+        ],
+        cwd=root,
+    )
+    dirty = bool(porcelain and porcelain.strip())
+    if require_clean and dirty:
+        return {
+            "status": "fail_dirty_worktree",
+            "branch": branch,
+            "head": head,
+            "tool": "git",
+            "full_bundle": False,
+            "dirty": True,
+            "sanitized_git_snapshot": {
+                "requested": include_sanitized_git_snapshot,
+                "status": "not_applicable",
+            },
+        }, {
+            f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(
+                {
+                    "requested": include_sanitized_git_snapshot,
+                    "status": "not_applicable",
+                }
+            )
+        }
+
     log_payload = _git_bytes(
         git,
-        ["log", "-20", "--format=%H %ad %s", "--date=iso-strict"],
+        ["log", "-20", "--format=%H %ad %s", "--date=iso-strict", head],
         cwd=root,
     )
-    rev_parse = _git_bytes(git, ["rev-parse", "HEAD"], cwd=root)
-    if rev_parse is not None:
-        head = rev_parse.decode("utf-8", errors="replace").strip() or head
-    ls_files = _git_bytes(git, ["ls-files", "-z"], cwd=root)
 
-    tree_rows: list[dict[str, object]] = []
-    file_hashes: dict[str, str] = {}
-    file_rels: list[str] = []
-    if ls_files is not None:
-        for raw in ls_files.split(b"\0"):
-            if not raw:
-                continue
-            rel = raw.decode("utf-8", errors="surrogateescape")
-            file_rels.append(rel)
-            path = root / Path(*rel.split("/"))
-            if not path.is_file():
-                continue
-            digest = sha256_file(path)
-            file_hashes[rel] = digest
-            tree_rows.append({"path": rel, "sha256": digest, "size": path.stat().st_size})
-    tree_rows.sort(key=lambda row: str(row["path"]))
+    snap_temp = temp_root if temp_root is not None else Path(
+        tempfile.mkdtemp(prefix="prod2u-review-git-", dir=os.environ.get("TMPDIR", "/tmp"))
+    )
+    snap_temp.mkdir(parents=True, exist_ok=True)
+    try:
+        tree_rows, file_hashes, file_rels = _hash_exact_commit_tree(
+            git, root, head, temp_root=snap_temp
+        )
+    except PackagingError:
+        return {
+            "status": "fail_commit_tree_archive",
+            "branch": branch,
+            "head": head,
+            "tool": "git",
+            "full_bundle": False,
+            "sanitized_git_snapshot": {
+                "requested": include_sanitized_git_snapshot,
+                "status": "not_applicable",
+            },
+        }, {
+            f"{meta_prefix}/sanitized-snapshot-status.json": json_bytes(
+                {
+                    "requested": include_sanitized_git_snapshot,
+                    "status": "not_applicable",
+                }
+            )
+        }
 
-    artifacts[f"{meta_prefix}/HEAD.txt"] = f"{head or ''}\n".encode("utf-8")
+    artifacts[f"{meta_prefix}/HEAD.txt"] = f"{head}\n".encode("utf-8")
     if branch:
         artifacts[f"{meta_prefix}/branch.txt"] = f"{branch}\n".encode("utf-8")
     if status_payload is not None:
@@ -1888,6 +2128,7 @@ def collect_review_git_provenance(
             "schema": "cpld-review-git-tree-manifest-v1",
             "head": head,
             "file_count": len(tree_rows),
+            "source": "git_archive_exact_commit",
             "files": tree_rows,
         }
     )
@@ -1895,6 +2136,7 @@ def collect_review_git_provenance(
         {
             "schema": "cpld-review-git-file-sha256-v1",
             "head": head,
+            "source": "git_archive_exact_commit",
             "files": file_hashes,
         }
     )
@@ -1903,10 +2145,6 @@ def collect_review_git_provenance(
     artifacts[f"{meta_prefix}/file-sha256.json"] = file_sha_payload
 
     if include_sanitized_git_snapshot:
-        snap_temp = temp_root if temp_root is not None else Path(
-            tempfile.mkdtemp(prefix="prod2u-sanitized-git-", dir=os.environ.get("TMPDIR", "/tmp"))
-        )
-        snap_temp.mkdir(parents=True, exist_ok=True)
         snapshot_status, snap_artifacts = create_sanitized_git_snapshot(
             root,
             git=git,
@@ -1924,25 +2162,35 @@ def collect_review_git_provenance(
             "note": (
                 "Optional sanitized synthetic single-commit snapshot via "
                 "--include-sanitized-git-snapshot. When present it records "
-                "synthetic→original mapping and must not impersonate the original tip."
+                "synthetic→original mapping and must not impersonate the original tip. "
+                "It cannot replace HEAD/tree/per-file SHA-256 live provenance."
             ),
         }
         artifacts[f"{meta_prefix}/sanitized-snapshot-status.json"] = json_bytes(
             snapshot_status
         )
 
+    validation_failures = validate_review_git_provenance_artifacts(
+        artifacts, meta_prefix=meta_prefix, expected_head=head
+    )
     capture_status = "pass"
-    if status_payload is None or log_payload is None or ls_files is None:
-        capture_status = "partial"
+    if status_payload is None or log_payload is None or validation_failures:
+        capture_status = "partial" if not validation_failures else "fail_provenance_incomplete"
+    if validation_failures:
+        capture_status = "fail_provenance_incomplete"
+
     return {
         "status": capture_status,
         "branch": branch,
         "head": head,
         "tool": "git",
         "full_bundle": False,
+        "dirty": dirty,
         "status_captured": status_payload is not None,
         "log20_captured": log_payload is not None,
         "tree_manifest_files": len(tree_rows),
+        "tree_source": "git_archive_exact_commit",
+        "validation_failures": validation_failures,
         "sanitized_git_snapshot": snapshot_status,
     }, artifacts
 

+ 19 - 10
tools/package_provenance.py

@@ -224,27 +224,36 @@ def derived_board_viewer_identity(repo_root: Path | None = None) -> dict[str, An
     }
 
 
+def stable_reference_inventory_semantics(inventory: dict[str, Any] | None) -> dict[str, Any]:
+    """Extract stable semantic fields only (no generated_at / abs paths / file SHA)."""
+    inv = inventory if isinstance(inventory, dict) else {}
+    boundaries = inv.get("evidence_boundaries") if isinstance(inv.get("evidence_boundaries"), dict) else {}
+    v12 = boundaries.get("v1_2_schematic_pdf") if isinstance(boundaries.get("v1_2_schematic_pdf"), dict) else {}
+    return {
+        "v1_2_schematic_pdf_status": v12.get("status", "unknown"),
+        "historical_schematic_side_evidence": boundaries.get(
+            "historical_schematic_side_evidence"
+        ),
+    }
+
+
 def reference_set_fingerprint(repo_root: Path | None = None) -> dict[str, Any]:
-    """Stable raw reference-set fingerprint (no generated_at / temp paths)."""
+    """Stable raw reference-set fingerprint (no generated_at / temp paths / inventory SHA)."""
     root = repo_root or ROOT
     inventory_path = root / "docs" / "REFERENCE-INVENTORY.json"
     raw = load_reference_package_identity(root)
     inventory = _read_json(inventory_path) if inventory_path.is_file() else {}
-    schematic_identity = {
-        "v1_2_schematic_pdf_status": inventory.get("evidence_boundaries", {})
-        .get("v1_2_schematic_pdf", {})
-        .get("status", "unknown"),
-        "historical_schematic_side_evidence": inventory.get("evidence_boundaries", {}).get(
-            "historical_schematic_side_evidence"
-        ),
-    }
+    schematic_identity = stable_reference_inventory_semantics(
+        inventory if isinstance(inventory, dict) else {}
+    )
+    # Raw fingerprint: ZIP identity + BRD + stable schematic semantics only.
+    # Do NOT mix in inventory file SHA / generated_at / repository_root.
     content_parts = {
         "reference_package_filename": raw["filename"],
         "reference_package_sha256": raw["sha256"],
         "reference_package_size": raw["size"],
         "canonical_brd_sha256": raw["canonical_brd_sha256"],
         "schematic_identity": schematic_identity,
-        "inventory_sha256": _sha256_file(inventory_path) if inventory_path.is_file() else None,
     }
     fp = _sha256_bytes(
         json.dumps(content_parts, sort_keys=True, separators=(",", ":")).encode("utf-8")