Pārlūkot izejas kodu

feat(evidence): canonicalize compact receipts and aliases

Keep one physical copy of each final evidence kind under evidence/,
record logical aliases in HANDOFF-INDEX, apply result-sensitive PASS/FAIL
log retention, and gate process lane/matrix-rerun evidence behind
review-debug or --include-process-evidence.

Co-authored-by: Cursor <cursoragent@cursor.com>
root 3 mēneši atpakaļ
vecāks
revīzija
65a405eba9

+ 17 - 3
PACKAGE_FOR_AGENT_ANALYSIS.README.zh-CN.md

@@ -39,20 +39,34 @@ tools/package-review-compact.sh
 可选:
 可选:
 
 
 - `--include-sanitized-git-snapshot`:预留 P2 合成单 commit 快照钩子(当前写入 `meta/git/sanitized-snapshot-status.json`,不冒充原始 tip)
 - `--include-sanitized-git-snapshot`:预留 P2 合成单 commit 快照钩子(当前写入 `meta/git/sanitized-snapshot-status.json`,不冒充原始 tip)
+- `--evidence-root DIR`:把交付/跑批证据树收口到 canonical `evidence/`(见下)
+- `--include-process-evidence`:额外收入 lane receipts / matrix rerun 等过程证据(`review-debug` 默认开启)
 - `--audit-only`:只扫描不写 ZIP
 - `--audit-only`:只扫描不写 ZIP
 - `--explain PATH`:解释某路径是否收入
 - `--explain PATH`:解释某路径是否收入
 
 
+## Evidence canonicalization(review-compact)
+
+默认 compact **每种最终证据只保留一份物理副本**;逻辑别名写入 `HANDOFF-INDEX.json` 的 `evidence_aliases` / `evidence_canon.aliases`。允许清单见 `config/review_compact_evidence_allowlist.json`:
+
+- final matrix、Formal receipt、TD receipt、tip binding、source closure、bitstream
+- firmware selftest、compact package selftest、deep-review **summary**
+- IO evidence、hardware bring-up notes
+
+过程型证据(lane receipts、多个 matrix rerun、deep-review round 文件、完整过程日志)仅在 `review-debug` 或 `--include-process-evidence` 中保留。
+
+结果敏感日志策略:PASS / `not_run` → 摘要;FAIL / BLOCKED / TIMEOUT / CRASH → 完整证据。
+
 ## 收入与排除(review-*)
 ## 收入与排除(review-*)
 
 
-**保留**:活动源码/测试/协议/项目合同、board-viewer 六件派生资产(`board-data.json` / `build-info.json` / `import-report.json` / 三张 SVG)、`tests/board_viewer/fixtures` 小 fixture、最终收据类 evidence。
+**保留**:活动源码/测试/协议/项目合同、board-viewer 六件派生资产(`board-data.json` / `build-info.json` / `import-report.json` / 三张 SVG)、`tests/board_viewer/fixtures` 小 fixture、上表最终收据类 evidence。
 
 
-**排除**:`reference/original/{board,schematics,diagrams,local_archives}`、PDF/BRD/DSN 原件、vendor installer zip、license、旧 run log、`.run_id*`、venv、`node_modules`、完整 Git bundle(非 archive-local)。
+**排除**:`reference/original/{board,schematics,diagrams,local_archives}`、PDF/BRD/DSN 原件、vendor installer zip、license、旧 run log、`.run_id*`、venv、`node_modules`、完整 Git bundle(非 archive-local)、默认 profile 下的过程型 evidence。
 
 
 ## 包目录内容
 ## 包目录内容
 
 
 - 一个(或少数)普通 `.zip` + 同源 `.tar.zst`
 - 一个(或少数)普通 `.zip` + 同源 `.tar.zst`
 - `PACKAGE-PURPOSE.txt`:上传意图
 - `PACKAGE-PURPOSE.txt`:上传意图
-- `HANDOFF-INDEX.json`:来源、卷、SHA-256、`member_count`(ZIP 业务成员 vs 自引用控制文件)、`size_budget`、`content_dedup` aliases、`derived_evidence`
+- `HANDOFF-INDEX.json`:来源、卷、SHA-256、`member_count`(ZIP 业务成员 vs 自引用控制文件)、`size_budget`、`content_dedup` / `evidence_aliases`、`evidence_canon`、`derived_evidence`
 - `size-budget.json`:≥256KiB 或 >1% 体积成员表
 - `size-budget.json`:≥256KiB 或 >1% 体积成员表
 - `EXCLUSIONS.txt` / `START-HERE.zh-CN.md` / `SHA256SUMS.txt`
 - `EXCLUSIONS.txt` / `START-HERE.zh-CN.md` / `SHA256SUMS.txt`
 
 

+ 138 - 0
config/review_compact_evidence_allowlist.json

@@ -0,0 +1,138 @@
+{
+  "schema": "cpld-review-compact-evidence-allowlist-v1",
+  "description": "Default review-compact keeps one physical copy of each final evidence kind; process evidence is review-debug / --include-process-evidence only.",
+  "canonical_entries": [
+    {
+      "key": "final_matrix",
+      "canonical_path": "evidence/matrix/verification-matrix-final.json",
+      "match_basenames": [
+        "verification-matrix-final.json",
+        "matrix-receipt.json"
+      ]
+    },
+    {
+      "key": "formal_receipt",
+      "canonical_path": "evidence/formal/formal-receipt.json",
+      "match_basenames": [
+        "formal-receipt.json"
+      ]
+    },
+    {
+      "key": "td_receipt",
+      "canonical_path": "evidence/td/td-primary-receipt.json",
+      "match_basenames": [
+        "td-primary-receipt.json"
+      ]
+    },
+    {
+      "key": "tip_binding",
+      "canonical_path": "evidence/td/td-tip-bind-receipt.json",
+      "match_basenames": [
+        "td-tip-bind-receipt.json"
+      ]
+    },
+    {
+      "key": "source_closure",
+      "canonical_path": "evidence/td/source-closure.json",
+      "match_basenames": [
+        "source-closure.json"
+      ],
+      "match_workspace_paths": [
+        "config/source_closure.json"
+      ]
+    },
+    {
+      "key": "bitstream",
+      "canonical_path": "evidence/bitstream/prod2u_p4_normal_v3.bit",
+      "match_basenames": [
+        "prod2u_p4_normal_v3.bit"
+      ]
+    },
+    {
+      "key": "bitstream_sha256",
+      "canonical_path": "evidence/bitstream/BITSTREAM-SHA256.txt",
+      "match_basenames": [
+        "bitstream-sha256.txt",
+        "prod2u_p4_normal_v3.bit.sha256"
+      ]
+    },
+    {
+      "key": "firmware_selftest",
+      "canonical_path": "evidence/selftest/firmware-selftest.json",
+      "match_basenames": [
+        "firmware-selftest.json"
+      ]
+    },
+    {
+      "key": "package_selftest",
+      "canonical_path": "evidence/selftest/compact-package-selftest.json",
+      "match_basenames": [
+        "compact-package-selftest.json",
+        "fresh-extraction-replay.json"
+      ]
+    },
+    {
+      "key": "deep_review_summary",
+      "canonical_path": "evidence/deep-reviews/summary.json",
+      "match_basenames": [
+        "summary.json"
+      ],
+      "match_path_contains": [
+        "deep-reviews/summary.json",
+        "deep-review/summary.json"
+      ]
+    },
+    {
+      "key": "io_evidence",
+      "canonical_path": "evidence/io/IO_EVIDENCE_MATRIX.zh-CN.md",
+      "match_basenames": [
+        "io_evidence_matrix.zh-cn.md"
+      ],
+      "match_workspace_paths": [
+        "docs/IO_EVIDENCE_MATRIX.zh-CN.md"
+      ]
+    },
+    {
+      "key": "hardware_bringup",
+      "canonical_path": "evidence/hardware/HARDWARE_BRINGUP_NOTES.zh-CN.md",
+      "match_basenames": [
+        "hardware_bringup_notes.zh-cn.md"
+      ]
+    }
+  ],
+  "process_evidence": {
+    "path_prefixes": [
+      "lane-status/",
+      "evidence/lane-status/",
+      "status/"
+    ],
+    "basename_globs": [
+      "verification-matrix-rerun*.json",
+      "verification-matrix-oss*.json",
+      "verification-matrix-verilator*.json",
+      "board-lanes-*.json",
+      "lane-*.json",
+      "integrate-batch-*.json",
+      "phase0-*.json",
+      "round-*.json"
+    ],
+    "notes": "Lane receipts, matrix reruns, and deep-review round files are process evidence."
+  },
+  "log_policy": {
+    "schema": "cpld-result-sensitive-log-policy-v1",
+    "pass_retention": "summary",
+    "fail_retention": "full",
+    "summary_statuses": ["pass", "passed", "ok", "success", "not_run"],
+    "full_statuses": ["fail", "failed", "blocked", "timeout", "crash", "error"],
+    "pass_summary_fields": [
+      "command",
+      "tool_version",
+      "duration_seconds",
+      "exit_code",
+      "test_counts",
+      "result_summary",
+      "artifact_hashes",
+      "warning_summary"
+    ]
+  }
+}

+ 197 - 16
package_for_agent_analysis.py

@@ -27,6 +27,7 @@ if str(TOOLS) not in sys.path:
     sys.path.insert(0, str(TOOLS))
     sys.path.insert(0, str(TOOLS))
 
 
 import package_agent_handoff as handoff  # noqa: E402
 import package_agent_handoff as handoff  # noqa: E402
+import package_evidence_canon as evidence_canon  # noqa: E402
 
 
 
 
 PackagingError = handoff.PackagingError
 PackagingError = handoff.PackagingError
@@ -217,6 +218,7 @@ class AnalysisCollection(NamedTuple):
     sources: tuple[dict[str, object], ...]
     sources: tuple[dict[str, object], ...]
     git: tuple[dict[str, object], ...]
     git: tuple[dict[str, object], ...]
     source_snapshots: tuple[SourceSnapshot, ...] = ()
     source_snapshots: tuple[SourceSnapshot, ...] = ()
+    evidence_canon: dict[str, object] | None = None
 
 
 
 
 def _is_reference_path(item: PackageItem) -> bool:
 def _is_reference_path(item: PackageItem) -> bool:
@@ -752,6 +754,8 @@ def _run_git(command: list[str], *, cwd: Path, timeout: int = 300) -> str:
 
 
 def _is_evidence_source_path(relative: str) -> bool:
 def _is_evidence_source_path(relative: str) -> bool:
     lower = relative.casefold()
     lower = relative.casefold()
+    if evidence_canon.workspace_canonical_path(relative) is not None:
+        return True
     if handoff.is_under(lower, "receipts"):
     if handoff.is_under(lower, "receipts"):
         return True
         return True
     if handoff.is_under(lower, "tools/board-viewer/generated"):
     if handoff.is_under(lower, "tools/board-viewer/generated"):
@@ -762,16 +766,23 @@ def _is_evidence_source_path(relative: str) -> bool:
     return False
     return False
 
 
 
 
-def _unified_layout_prefix(
+def _unified_item_placement(
     *,
     *,
     source_id: str,
     source_id: str,
     original_relative: str,
     original_relative: str,
     profile: str,
     profile: str,
 ) -> tuple[str, str]:
 ) -> tuple[str, str]:
-    """Return (archive_prefix, category) for unified review layouts."""
+    """Return (package_relative_or_prefix, category) for unified review layouts.
+
+    When the workspace path matches the compact evidence allowlist, the first
+    element is the full canonical package path (not merely a directory prefix).
+    """
     del profile
     del profile
     if source_id == "board-viewer-generated" or source_id.startswith("board-viewer"):
     if source_id == "board-viewer-generated" or source_id.startswith("board-viewer"):
         return "evidence/board-viewer", "evidence"
         return "evidence/board-viewer", "evidence"
+    canon = evidence_canon.workspace_canonical_path(original_relative)
+    if canon is not None and source_id in {"workspace-current", "source"}:
+        return canon, "evidence"
     if source_id != "workspace-current" and source_id != "source":
     if source_id != "workspace-current" and source_id != "source":
         if _is_evidence_source_path(original_relative):
         if _is_evidence_source_path(original_relative):
             return f"evidence/external/{source_id}", "evidence"
             return f"evidence/external/{source_id}", "evidence"
@@ -781,6 +792,44 @@ def _unified_layout_prefix(
     return "source", "source"
     return "source", "source"
 
 
 
 
+def _unified_layout_prefix(
+    *,
+    source_id: str,
+    original_relative: str,
+    profile: str,
+) -> tuple[str, str]:
+    """Compatibility wrapper: directory prefix + category for unified layouts."""
+    placed, category = _unified_item_placement(
+        source_id=source_id,
+        original_relative=original_relative,
+        profile=profile,
+    )
+    if placed.startswith("evidence/") and placed.count("/") >= 2 and not placed.endswith("/"):
+        # Full canonical path — expose parent as prefix for exclusion rewriting.
+        if evidence_canon.workspace_canonical_path(original_relative) == placed:
+            parent = placed.rsplit("/", 1)[0]
+            return parent, category
+    return placed, category
+
+
+def _package_relative_for_unified(
+    *,
+    source_id: str,
+    original_relative: str,
+    profile: str,
+) -> tuple[str, str]:
+    placed, category = _unified_item_placement(
+        source_id=source_id,
+        original_relative=original_relative,
+        profile=profile,
+    )
+    if evidence_canon.workspace_canonical_path(original_relative) == placed:
+        return placed, category
+    if original_relative in {".", ""}:
+        return placed, category
+    return f"{placed}/{original_relative}", category
+
+
 def _materialize_bytes_items(
 def _materialize_bytes_items(
     payloads: dict[str, bytes],
     payloads: dict[str, bytes],
     *,
     *,
@@ -871,6 +920,8 @@ def collect_analysis_inputs(
     profile: str = "full",
     profile: str = "full",
     include_sanitized_git_snapshot: bool = False,
     include_sanitized_git_snapshot: bool = False,
     package_name: str = "pending",
     package_name: str = "pending",
+    evidence_root: Path | None = None,
+    include_process_evidence: bool = False,
 ) -> AnalysisCollection:
 ) -> AnalysisCollection:
     root = repo_root.resolve(strict=True)
     root = repo_root.resolve(strict=True)
     temp_root.mkdir(parents=True, exist_ok=True)
     temp_root.mkdir(parents=True, exist_ok=True)
@@ -906,24 +957,21 @@ def collect_analysis_inputs(
         remapped: list[PackageItem] = []
         remapped: list[PackageItem] = []
         for item in root_items:
         for item in root_items:
             original = item.original_path
             original = item.original_path
-            prefix, category = _unified_layout_prefix(
+            package_relative, category = _package_relative_for_unified(
                 source_id=primary_source_id,
                 source_id=primary_source_id,
                 original_relative=original,
                 original_relative=original,
                 profile=profile,
                 profile=profile,
             )
             )
             remapped.append(
             remapped.append(
                 PackageItem(
                 PackageItem(
-                    candidate=_rebase_candidate(
-                        handoff.Candidate(
-                            absolute=item.candidate.absolute,
-                            relative=original,
-                            size=item.candidate.size,
-                            mtime_ns=item.candidate.mtime_ns,
-                            device=item.candidate.device,
-                            inode=item.candidate.inode,
-                            mode=item.candidate.mode,
-                        ),
-                        prefix,
+                    candidate=handoff.Candidate(
+                        absolute=item.candidate.absolute,
+                        relative=package_relative,
+                        size=item.candidate.size,
+                        mtime_ns=item.candidate.mtime_ns,
+                        device=item.candidate.device,
+                        inode=item.candidate.inode,
+                        mode=item.candidate.mode,
                     ),
                     ),
                     category=category,
                     category=category,
                     source_id=primary_source_id,
                     source_id=primary_source_id,
@@ -938,7 +986,7 @@ def collect_analysis_inputs(
                 original_excluded = original_excluded[len("__workspace__/") :]
                 original_excluded = original_excluded[len("__workspace__/") :]
             elif original_excluded == "__workspace__":
             elif original_excluded == "__workspace__":
                 original_excluded = "."
                 original_excluded = "."
-            prefix, _category = _unified_layout_prefix(
+            package_relative, _category = _package_relative_for_unified(
                 source_id=primary_source_id,
                 source_id=primary_source_id,
                 original_relative=original_excluded,
                 original_relative=original_excluded,
                 profile=profile,
                 profile=profile,
@@ -948,7 +996,7 @@ def collect_analysis_inputs(
                     "path": (
                     "path": (
                         original_excluded
                         original_excluded
                         if original_excluded == "."
                         if original_excluded == "."
-                        else f"{prefix}/{original_excluded}"
+                        else package_relative
                     ),
                     ),
                     "rule": entry["rule"],
                     "rule": entry["rule"],
                 }
                 }
@@ -1174,6 +1222,90 @@ def collect_analysis_inputs(
             items.append(external_bundle)
             items.append(external_bundle)
             git_metadata.append(external_git)
             git_metadata.append(external_git)
 
 
+    evidence_canon_fields: dict[str, object] | None = None
+    include_process = include_process_evidence or profile == "review-debug"
+    if unified:
+        if evidence_root is not None:
+            staged = evidence_canon.stage_evidence_root(
+                evidence_root,
+                staging_root=temp_root / "canonical-evidence",
+                include_process_evidence=include_process,
+            )
+            for staged_file in staged.staged:
+                items.append(
+                    PackageItem(
+                        candidate=_candidate_from_path(
+                            staged_file.absolute,
+                            staged_file.relative,
+                        ),
+                        category="evidence",
+                        source_id="evidence-root",
+                        original_path=staged_file.original_path,
+                        scan_archive=False,
+                    )
+                )
+            excluded.extend(staged.excluded)
+            sources.append(
+                {
+                    "id": "evidence-root",
+                    "category": "evidence",
+                    "kind": "directory",
+                    "path": str(evidence_root.resolve()),
+                    "status": "pass",
+                }
+            )
+            evidence_canon_fields = evidence_canon.build_evidence_canon_index_fields(
+                catalog=staged.catalog,
+                aliases=staged.aliases,
+                log_policy_actions=staged.log_policy_actions,
+                include_process_evidence=include_process,
+                profile=profile,
+            )
+        kept_items, filter_excluded, _remaps = evidence_canon.filter_package_items_for_compact(
+            items,
+            profile=profile,
+            include_process_evidence=include_process,
+        )
+        items = list(kept_items)
+        excluded.extend(filter_excluded)
+        if evidence_canon_fields is None:
+            evidence_canon_fields = evidence_canon.build_evidence_canon_index_fields(
+                catalog=[
+                    {
+                        "key": key,
+                        "canonical_path": evidence_canon.load_allowlist().by_key[key].canonical_path,
+                        "role": "compact_default",
+                        "source_original": None,
+                    }
+                    for key in evidence_canon.compact_default_key_list()
+                ],
+                aliases=[],
+                log_policy_actions=[],
+                include_process_evidence=include_process,
+                profile=profile,
+            )
+        # Record workspace allowlisted evidence that survived filtering.
+        present = {item.candidate.relative.casefold() for item in items}
+        catalog = list(evidence_canon_fields.get("catalog", []))  # type: ignore[arg-type]
+        allowlist = evidence_canon.load_allowlist()
+        for entry in allowlist.canonical_entries:
+            if entry.canonical_path.casefold() in present and not any(
+                str(row.get("canonical_path", "")).casefold() == entry.canonical_path.casefold()
+                for row in catalog
+            ):
+                catalog.append(
+                    {
+                        "key": entry.key,
+                        "canonical_path": entry.canonical_path,
+                        "role": "compact_default",
+                        "source_original": "workspace",
+                    }
+                )
+        evidence_canon_fields["catalog"] = sorted(catalog, key=lambda row: str(row["key"]))
+        evidence_canon_fields["compact_default_keys"] = sorted(
+            {str(row["key"]) for row in catalog if row.get("role") == "compact_default"}
+        )
+
     items.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
     items.sort(key=lambda item: handoff.windows_collision_key(item.candidate.relative))
     excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
     excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
     return AnalysisCollection(
     return AnalysisCollection(
@@ -1184,6 +1316,7 @@ def collect_analysis_inputs(
         sources=tuple(sources),
         sources=tuple(sources),
         git=tuple(git_metadata),
         git=tuple(git_metadata),
         source_snapshots=tuple(source_snapshots),
         source_snapshots=tuple(source_snapshots),
+        evidence_canon=evidence_canon_fields,
     )
     )
 
 
 
 
@@ -1580,6 +1713,14 @@ def _is_reference_original_path(relative: str) -> bool:
 
 
 
 
 def _dedup_canonical_path(paths: list[str]) -> str:
 def _dedup_canonical_path(paths: list[str]) -> str:
+    # Prefer compact evidence allowlist canonical paths first (P4).
+    try:
+        preferred = evidence_canon.prefer_canonical_path(paths)
+        if evidence_canon.is_compact_allowlisted(preferred):
+            return preferred
+    except ValueError:
+        pass
+
     def rank(path: str) -> tuple[int, int, str]:
     def rank(path: str) -> tuple[int, int, str]:
         name = _path_basename(path)
         name = _path_basename(path)
         in_reference = _is_reference_original_path(path)
         in_reference = _is_reference_original_path(path)
@@ -1597,6 +1738,8 @@ def _should_content_dedup(size: int, relative: str) -> bool:
     name = _path_basename(relative)
     name = _path_basename(relative)
     if name in DERIVED_BOARD_VIEWER_ASSETS or name.endswith((".brd", ".pdf")):
     if name in DERIVED_BOARD_VIEWER_ASSETS or name.endswith((".brd", ".pdf")):
         return True
         return True
+    if evidence_canon.is_compact_allowlisted(relative):
+        return True
     return size >= CONTENT_DEDUP_MIN_BYTES
     return size >= CONTENT_DEDUP_MIN_BYTES
 
 
 
 
@@ -2437,6 +2580,22 @@ def create_analysis_package(
         package_excluded = list(collection.excluded) + dedup_excluded
         package_excluded = list(collection.excluded) + dedup_excluded
         package_excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
         package_excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
         derived_evidence = classify_derived_evidence(physical_items)
         derived_evidence = classify_derived_evidence(physical_items)
+        evidence_canon_fields = dict(collection.evidence_canon or {})
+        # Merge content_dedup logical aliases into evidence_canon.aliases for HANDOFF-INDEX.
+        evidence_aliases = list(evidence_canon_fields.get("aliases", []))  # type: ignore[arg-type]
+        for record in content_dedup:
+            evidence_aliases.append(
+                {
+                    "key": None,
+                    "sha256": record["sha256"],
+                    "size": record["size"],
+                    "physical_path": record["physical_path"],
+                    "logical_paths": record["logical_paths"],
+                    "reason": record["reason"],
+                }
+            )
+        if evidence_canon_fields:
+            evidence_canon_fields["aliases"] = evidence_aliases
         package_items = physical_items
         package_items = physical_items
         package_inventory = inventory
         package_inventory = inventory
         package_inventory_by_path = inventory_by_path
         package_inventory_by_path = inventory_by_path
@@ -2544,6 +2703,8 @@ def create_analysis_package(
             "excluded": package_excluded,
             "excluded": package_excluded,
             "content_dedup": content_dedup,
             "content_dedup": content_dedup,
             "derived_evidence": derived_evidence,
             "derived_evidence": derived_evidence,
+            "evidence_canon": evidence_canon_fields if evidence_canon_fields else None,
+            "evidence_aliases": evidence_aliases,
             "member_count": member_count,
             "member_count": member_count,
             "size_budget": size_budget,
             "size_budget": size_budget,
             "volumes": volume_infos,
             "volumes": volume_infos,
@@ -2805,6 +2966,22 @@ def build_parser() -> argparse.ArgumentParser:
         action="store_true",
         action="store_true",
         help="request sanitized synthetic git snapshot hook (P2 extension; records reserved status)",
         help="request sanitized synthetic git snapshot hook (P2 extension; records reserved status)",
     )
     )
+    parser.add_argument(
+        "--evidence-root",
+        type=Path,
+        help=(
+            "optional delivery/run evidence tree to stage into canonical evidence/ paths "
+            "(final matrix, Formal/TD receipts, bitstream, selftests, deep-review summary, IO/hardware notes)"
+        ),
+    )
+    parser.add_argument(
+        "--include-process-evidence",
+        action="store_true",
+        help=(
+            "include lane receipts, matrix reruns, and other process evidence "
+            "(implied by review-debug; off by default for review-compact)"
+        ),
+    )
     parser.add_argument(
     parser.add_argument(
         "--profile",
         "--profile",
         choices=sorted(handoff.HANDOFF_PROFILES),
         choices=sorted(handoff.HANDOFF_PROFILES),
@@ -2874,6 +3051,10 @@ def main(argv: list[str] | None = None) -> int:
                     profile=args.profile,
                     profile=args.profile,
                     include_sanitized_git_snapshot=args.include_sanitized_git_snapshot,
                     include_sanitized_git_snapshot=args.include_sanitized_git_snapshot,
                     package_name=package_name,
                     package_name=package_name,
+                    evidence_root=args.evidence_root.expanduser().resolve(strict=True)
+                    if args.evidence_root is not None
+                    else None,
+                    include_process_evidence=args.include_process_evidence,
                 )
                 )
                 preparation = prepare_unsupported_archives(
                 preparation = prepare_unsupported_archives(
                     collection.items,
                     collection.items,

+ 77 - 0
schemas/agent_analysis_handoff_index.schema.json

@@ -139,6 +139,50 @@
         }
         }
       }
       }
     },
     },
+    "evidence_canon": {
+      "type": ["object", "null"],
+      "additionalProperties": true,
+      "properties": {
+        "schema": {
+          "const": "cpld-evidence-canon-v1"
+        },
+        "profile": {
+          "type": "string"
+        },
+        "include_process_evidence": {
+          "type": "boolean"
+        },
+        "compact_default_keys": {
+          "type": "array",
+          "items": {
+            "type": "string"
+          }
+        },
+        "catalog": {
+          "type": "array",
+          "items": {
+            "type": "object",
+            "additionalProperties": true
+          }
+        },
+        "aliases": {
+          "type": "array",
+          "items": {
+            "$ref": "#/$defs/evidence_alias"
+          }
+        },
+        "log_policy": {
+          "type": "object",
+          "additionalProperties": true
+        }
+      }
+    },
+    "evidence_aliases": {
+      "type": "array",
+      "items": {
+        "$ref": "#/$defs/evidence_alias"
+      }
+    },
     "member_count": {
     "member_count": {
       "type": "object",
       "type": "object",
       "additionalProperties": false,
       "additionalProperties": false,
@@ -271,6 +315,39 @@
       "type": "string",
       "type": "string",
       "pattern": "^[0-9a-f]{64}$"
       "pattern": "^[0-9a-f]{64}$"
     },
     },
+    "evidence_alias": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": [
+        "physical_path",
+        "logical_paths",
+        "reason"
+      ],
+      "properties": {
+        "key": {
+          "type": ["string", "null"]
+        },
+        "sha256": {
+          "$ref": "#/$defs/sha256"
+        },
+        "size": {
+          "type": "integer",
+          "minimum": 0
+        },
+        "physical_path": {
+          "type": "string"
+        },
+        "logical_paths": {
+          "type": "array",
+          "items": {
+            "type": "string"
+          }
+        },
+        "reason": {
+          "type": "string"
+        }
+      }
+    },
     "excluded": {
     "excluded": {
       "type": "object",
       "type": "object",
       "additionalProperties": false,
       "additionalProperties": false,

+ 320 - 0
tests/unit/test_evidence_canon.py

@@ -0,0 +1,320 @@
+#!/usr/bin/env python3
+"""Focused tests for Lane P4 evidence canonicalization."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+TOOLS = ROOT / "tools"
+if str(TOOLS) not in sys.path:
+    sys.path.insert(0, str(TOOLS))
+
+import package_evidence_canon as evidence_canon  # noqa: E402
+
+
+def load_analyzer():
+    path = ROOT / "package_for_agent_analysis.py"
+    spec = importlib.util.spec_from_file_location("package_for_agent_analysis", 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, payload: bytes) -> Path:
+    path = root / Path(*relative.split("/"))
+    path.parent.mkdir(parents=True, exist_ok=True)
+    path.write_bytes(payload)
+    return path
+
+
+class EvidenceCanonUnitTests(unittest.TestCase):
+    def test_allowlist_loads_and_lists_compact_keys(self) -> None:
+        allowlist = evidence_canon.load_allowlist()
+        keys = evidence_canon.compact_default_key_list(allowlist)
+        for required in (
+            "final_matrix",
+            "formal_receipt",
+            "td_receipt",
+            "tip_binding",
+            "source_closure",
+            "bitstream",
+            "firmware_selftest",
+            "package_selftest",
+            "deep_review_summary",
+            "io_evidence",
+            "hardware_bringup",
+        ):
+            self.assertIn(required, keys)
+
+    def test_workspace_canonical_placement(self) -> None:
+        self.assertEqual(
+            evidence_canon.workspace_canonical_path("docs/IO_EVIDENCE_MATRIX.zh-CN.md"),
+            "evidence/io/IO_EVIDENCE_MATRIX.zh-CN.md",
+        )
+        self.assertEqual(
+            evidence_canon.workspace_canonical_path("config/source_closure.json"),
+            "evidence/td/source-closure.json",
+        )
+        self.assertEqual(
+            evidence_canon.workspace_canonical_path(
+                "receipts/verification-matrix-final.json"
+            ),
+            "evidence/matrix/verification-matrix-final.json",
+        )
+
+    def test_process_evidence_detection(self) -> None:
+        self.assertTrue(evidence_canon.is_process_evidence("lane-status/lane-a-docs.json"))
+        self.assertTrue(
+            evidence_canon.is_process_evidence(
+                "receipts/verification-matrix-rerun3.json"
+            )
+        )
+        self.assertTrue(
+            evidence_canon.is_process_evidence("deep-reviews/round-1-product-protocol.json")
+        )
+        self.assertFalse(
+            evidence_canon.is_process_evidence("deep-reviews/summary.json")
+        )
+        self.assertFalse(
+            evidence_canon.is_process_evidence(
+                "evidence/matrix/verification-matrix-final.json"
+            )
+        )
+
+    def test_log_policy_pass_summary_fail_full(self) -> None:
+        self.assertEqual(evidence_canon.log_retention_for_status("pass"), "summary")
+        self.assertEqual(evidence_canon.log_retention_for_status("not_run"), "summary")
+        self.assertEqual(evidence_canon.log_retention_for_status("FAIL"), "full")
+        self.assertEqual(evidence_canon.log_retention_for_status("blocked"), "full")
+        self.assertEqual(evidence_canon.log_retention_for_status("timeout"), "full")
+        summary = evidence_canon.build_pass_log_summary(
+            source_path="formal.log",
+            status="pass",
+            metadata={
+                "command": ["sby", "run"],
+                "exit_code": 0,
+                "duration_seconds": 12.5,
+                "warning_summary": [],
+            },
+        )
+        self.assertEqual(summary["retention"], "summary")
+        self.assertEqual(summary["exit_code"], 0)
+        self.assertIn("full stdout/stderr is omitted", summary["note"])
+
+    def test_stage_evidence_root_dedup_and_aliases(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            evid = root / "delivery"
+            # Duplicate final matrix under two discovery paths (same bytes).
+            payload = b'{"status":"pass","lanes":{"python":{"status":"pass"}}}\n'
+            write_file(evid, "evidence/matrix-receipt.json", payload)
+            write_file(evid, "receipts/verification-matrix-final.json", payload)
+            write_file(
+                evid,
+                "evidence/td-primary-receipt.json",
+                b'{"status":"pass","tool":"td2026"}\n',
+            )
+            write_file(
+                evid,
+                "lane-status/lane-a-docs.json",
+                b'{"status":"pass","lane":"A"}\n',
+            )
+            write_file(
+                evid,
+                "receipts/verification-matrix-rerun3.json",
+                b'{"status":"fail"}\n',
+            )
+            # PASS log should collapse to summary only.
+            write_file(evid, "evidence/td-primary.log", b"INFO built ok\n" * 50)
+            result = evidence_canon.stage_evidence_root(
+                evid,
+                staging_root=root / "stage",
+                include_process_evidence=False,
+            )
+            rels = {item.relative for item in result.staged}
+            self.assertIn("evidence/matrix/verification-matrix-final.json", rels)
+            self.assertIn("evidence/td/td-primary-receipt.json", rels)
+            self.assertNotIn("evidence/process/lane-status/lane-a-docs.json", rels)
+            self.assertTrue(any(row.get("key") == "final_matrix" for row in result.aliases))
+            rules = {row["rule"] for row in result.excluded}
+            self.assertIn(evidence_canon.PROCESS_EXCLUDE_RULE, rules)
+
+            debug = evidence_canon.stage_evidence_root(
+                evid,
+                staging_root=root / "stage-debug",
+                include_process_evidence=True,
+            )
+            debug_rels = {item.relative for item in debug.staged}
+            self.assertTrue(
+                any(path.startswith("evidence/process/") for path in debug_rels)
+            )
+
+    def test_prefer_canonical_path(self) -> None:
+        chosen = evidence_canon.prefer_canonical_path(
+            [
+                "evidence/from/matrix-receipt.json",
+                "evidence/matrix/verification-matrix-final.json",
+                "source/receipts/verification-matrix-final.json",
+            ]
+        )
+        self.assertEqual(chosen, "evidence/matrix/verification-matrix-final.json")
+
+
+class EvidenceCanonPackagerIntegrationTests(unittest.TestCase):
+    def test_review_compact_filters_process_and_places_io_evidence(self) -> None:
+        analyzer = load_analyzer()
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            repo = temp / "repo"
+            write_file(repo, "src/core.v", b"module core; endmodule\n")
+            write_file(
+                repo,
+                "docs/IO_EVIDENCE_MATRIX.zh-CN.md",
+                b"# IO evidence\n",
+            )
+            write_file(
+                repo,
+                "config/source_closure.json",
+                b'{"schema":"fixture","files":[]}\n',
+            )
+            write_file(
+                repo,
+                "receipts/verification-matrix-final.json",
+                b'{"status":"pass"}\n',
+            )
+            write_file(
+                repo,
+                "receipts/verification-matrix-rerun3.json",
+                b'{"status":"fail"}\n',
+            )
+            write_file(
+                repo,
+                "receipts/deep-reviews/summary.json",
+                b'{"status":"closed","rounds":5}\n',
+            )
+            write_file(
+                repo,
+                "receipts/deep-reviews/round-1-product-protocol.json",
+                b'{"round":1}\n',
+            )
+            # Minimal git not required for collect when include_git_bundle forced off.
+            config = analyzer.HandoffConfig(
+                max_zip_bytes=5_000_000,
+                target_zip_bytes=4_000_000,
+                external_sources=(),
+                extra_exclusions=(),
+            )
+            collection = analyzer.collect_analysis_inputs(
+                repo_root=repo,
+                config=config,
+                temp_root=temp / "run",
+                include_git_bundle=False,
+                profile="review-compact",
+                package_name="evidence-canon-smoke",
+            )
+            paths = {item.candidate.relative for item in collection.items}
+            self.assertIn("evidence/io/IO_EVIDENCE_MATRIX.zh-CN.md", paths)
+            self.assertIn("evidence/td/source-closure.json", paths)
+            self.assertIn("evidence/matrix/verification-matrix-final.json", paths)
+            self.assertIn("evidence/deep-reviews/summary.json", paths)
+            self.assertNotIn("evidence/receipts/verification-matrix-rerun3.json", paths)
+            self.assertFalse(any("round-1-product-protocol" in path for path in paths))
+            self.assertIsNotNone(collection.evidence_canon)
+            assert collection.evidence_canon is not None
+            self.assertEqual(collection.evidence_canon["schema"], "cpld-evidence-canon-v1")
+            self.assertFalse(collection.evidence_canon["include_process_evidence"])
+            self.assertIn("final_matrix", collection.evidence_canon["compact_default_keys"])
+
+            excluded_rules = {row["rule"] for row in collection.excluded}
+            self.assertTrue(
+                evidence_canon.PROCESS_EXCLUDE_RULE in excluded_rules
+                or evidence_canon.NON_ALLOWLIST_RECEIPT_RULE in excluded_rules
+            )
+
+    def test_evidence_root_staging_into_package_index(self) -> None:
+        analyzer = load_analyzer()
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            repo = temp / "repo"
+            write_file(repo, "src/core.v", b"module core; endmodule\n")
+            evid = temp / "evid"
+            write_file(
+                evid,
+                "evidence/formal-receipt.json",
+                b'{"status":"pass","tool":"sby"}\n',
+            )
+            write_file(
+                evid,
+                "HARDWARE_BRINGUP_NOTES.zh-CN.md",
+                b"# bring-up\n",
+            )
+            write_file(
+                evid,
+                "bitstream/prod2u_p4_normal_v3.bit",
+                b"BITSTREAM",
+            )
+            write_file(
+                evid,
+                "lane-status/lane-f-td.json",
+                b'{"status":"pass"}\n',
+            )
+            config = analyzer.HandoffConfig(
+                max_zip_bytes=5_000_000,
+                target_zip_bytes=4_000_000,
+                external_sources=(),
+                extra_exclusions=(),
+            )
+            collection = analyzer.collect_analysis_inputs(
+                repo_root=repo,
+                config=config,
+                temp_root=temp / "run",
+                include_git_bundle=False,
+                profile="review-compact",
+                package_name="evidence-root-smoke",
+                evidence_root=evid,
+            )
+            paths = {item.candidate.relative for item in collection.items}
+            self.assertIn("evidence/formal/formal-receipt.json", paths)
+            self.assertIn("evidence/hardware/HARDWARE_BRINGUP_NOTES.zh-CN.md", paths)
+            self.assertIn("evidence/bitstream/prod2u_p4_normal_v3.bit", paths)
+            self.assertFalse(any("lane-f-td" in path for path in paths))
+
+            result = analyzer.create_analysis_package(
+                collection=collection,
+                output_root=temp / "output",
+                package_name="evidence-root-smoke",
+                max_zip_bytes=5_000_000,
+                target_zip_bytes=4_000_000,
+                force=False,
+                profile="review-compact",
+            )
+            index = json.loads(
+                (Path(result["output_dir"]) / "HANDOFF-INDEX.json").read_text(
+                    encoding="utf-8"
+                )
+            )
+            self.assertIn("evidence_canon", index)
+            self.assertIn("evidence_aliases", index)
+            self.assertEqual(index["evidence_canon"]["schema"], "cpld-evidence-canon-v1")
+            self.assertIn("formal_receipt", index["evidence_canon"]["compact_default_keys"])
+            schema = json.loads(
+                (ROOT / "schemas" / "agent_analysis_handoff_index.schema.json").read_text(
+                    encoding="utf-8"
+                )
+            )
+            import jsonschema
+
+            jsonschema.validate(index, schema)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 11 - 4
tests/unit/test_package_for_agent_analysis.py

@@ -1156,13 +1156,20 @@ class ReviewCompactProfileSmokeTests(unittest.TestCase):
             check=True,
             check=True,
         )
         )
         write_file(repo, "src/core.v", b"module core; endmodule\n")
         write_file(repo, "src/core.v", b"module core; endmodule\n")
-        write_file(repo, "receipts/final.json", b'{"status":"pass"}\n')
+        write_file(
+            repo,
+            "receipts/verification-matrix-final.json",
+            b'{"status":"pass","schema":"fixture"}\n',
+        )
         write_file(repo, "reference/original/board/main.brd", b"BOARD")
         write_file(repo, "reference/original/board/main.brd", b"BOARD")
         write_file(repo, "reference/original/schematics/main.pdf", b"%PDF")
         write_file(repo, "reference/original/schematics/main.pdf", b"%PDF")
         write_file(repo, "tests/board_viewer/fixtures/tiny.dsn", b"fixture-dsn\n")
         write_file(repo, "tests/board_viewer/fixtures/tiny.dsn", b"fixture-dsn\n")
         write_file(repo, ".run_id_stale", b"stale\n")
         write_file(repo, ".run_id_stale", b"stale\n")
         write_file(repo, "node_modules/pkg/index.js", b"nope\n")
         write_file(repo, "node_modules/pkg/index.js", b"nope\n")
-        subprocess.run([git, "-C", str(repo), "add", "src/core.v", "receipts/final.json"], check=True)
+        subprocess.run(
+            [git, "-C", str(repo), "add", "src/core.v", "receipts/verification-matrix-final.json"],
+            check=True,
+        )
         subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
         subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
         return git
         return git
 
 
@@ -1223,7 +1230,7 @@ class ReviewCompactProfileSmokeTests(unittest.TestCase):
             paths = {item.candidate.relative for item in collection.items}
             paths = {item.candidate.relative for item in collection.items}
             self.assertTrue(any(path.startswith("source/") for path in paths))
             self.assertTrue(any(path.startswith("source/") for path in paths))
             self.assertIn("source/src/core.v", paths)
             self.assertIn("source/src/core.v", paths)
-            self.assertIn("evidence/receipts/final.json", paths)
+            self.assertIn("evidence/matrix/verification-matrix-final.json", paths)
             self.assertIn("evidence/board-viewer/board-data.json", paths)
             self.assertIn("evidence/board-viewer/board-data.json", paths)
             self.assertTrue(any(path.startswith("meta/git/") for path in paths))
             self.assertTrue(any(path.startswith("meta/git/") for path in paths))
             self.assertFalse(any(path.endswith(".bundle") for path in paths))
             self.assertFalse(any(path.endswith(".bundle") for path in paths))
@@ -1251,7 +1258,7 @@ class ReviewCompactProfileSmokeTests(unittest.TestCase):
             with zipfile.ZipFile(volume) as archive:
             with zipfile.ZipFile(volume) as archive:
                 names = set(archive.namelist())
                 names = set(archive.namelist())
             self.assertIn("CPLD/source/src/core.v", names)
             self.assertIn("CPLD/source/src/core.v", names)
-            self.assertIn("CPLD/evidence/receipts/final.json", names)
+            self.assertIn("CPLD/evidence/matrix/verification-matrix-final.json", names)
             self.assertIn("CPLD/meta/git/log-20.txt", names)
             self.assertIn("CPLD/meta/git/log-20.txt", names)
             self.assertIn("CPLD/meta/td-source-closure-binding.json", names)
             self.assertIn("CPLD/meta/td-source-closure-binding.json", names)
             self.assertFalse(any(name.endswith(".bundle") for name in names))
             self.assertFalse(any(name.endswith(".bundle") for name in names))

+ 4 - 2
tools/package_agent_handoff.py

@@ -1496,9 +1496,11 @@ def package_purpose_text(profile: str, *, package_name: str) -> str:
         lines.extend(
         lines.extend(
             [
             [
                 "Default remote-agent upload package.",
                 "Default remote-agent upload package.",
-                "Layout: source/ (active code+tests) + evidence/ (receipts, derived board-viewer) + meta/.",
+                "Layout: source/ (active code+tests) + evidence/ (canonical final receipts, derived board-viewer) + meta/.",
                 "Does NOT include a full Git bundle, PDF/BRD/DSN originals, vendor installer zips, or license material.",
                 "Does NOT include a full Git bundle, PDF/BRD/DSN originals, vendor installer zips, or license material.",
                 "Git provenance is commit/status/log-20/tree manifest/per-file SHA-256 plus TD source-closure binding hooks.",
                 "Git provenance is commit/status/log-20/tree manifest/per-file SHA-256 plus TD source-closure binding hooks.",
+                "Evidence is physically deduplicated; process lane receipts / matrix reruns require review-debug or --include-process-evidence.",
+                "Result-sensitive logs: PASS/not_run keep summaries; FAIL/BLOCKED/TIMEOUT/CRASH keep full evidence.",
                 "Hardware validation remains not_run unless a future task authorizes it.",
                 "Hardware validation remains not_run unless a future task authorizes it.",
             ]
             ]
         )
         )
@@ -1506,7 +1508,7 @@ def package_purpose_text(profile: str, *, package_name: str) -> str:
         lines.extend(
         lines.extend(
             [
             [
                 "Debug-oriented review package (unified layout).",
                 "Debug-oriented review package (unified layout).",
-                "Same heavy-original exclusions as review-compact; may carry additional debug evidence.",
+                "Same heavy-original exclusions as review-compact; includes process evidence by default.",
                 "Still omits full Git history bundles by default.",
                 "Still omits full Git history bundles by default.",
             ]
             ]
         )
         )

+ 608 - 0
tools/package_evidence_canon.py

@@ -0,0 +1,608 @@
+#!/usr/bin/env python3
+"""Canonical evidence selection for review-compact / review-debug packages.
+
+Owns:
+- compact default receipt allowlist
+- canonical placement under evidence/
+- logical alias records (one physical copy)
+- result-sensitive PASS/FAIL log retention policy
+
+Process lane receipts and matrix reruns stay out of review-compact unless
+``include_process_evidence`` is set (review-debug enables that by default).
+"""
+
+from __future__ import annotations
+
+import fnmatch
+import hashlib
+import json
+import os
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Callable, Iterable
+
+
+ROOT = Path(__file__).resolve().parents[1]
+DEFAULT_ALLOWLIST_PATH = ROOT / "config" / "review_compact_evidence_allowlist.json"
+EVIDENCE_CANON_SCHEMA = "cpld-evidence-canon-v1"
+EVIDENCE_ALIAS_REASON = "canonical_evidence_single_physical_copy"
+PROCESS_EXCLUDE_RULE = "process_evidence_not_in_compact_allowlist"
+NON_ALLOWLIST_RECEIPT_RULE = "receipt_not_on_compact_allowlist"
+LOG_SUMMARY_SUFFIX = ".pass-summary.json"
+
+PackageItemFactory = Callable[..., Any]
+
+
+@dataclass(frozen=True)
+class CanonicalEntry:
+    key: str
+    canonical_path: str
+    match_basenames: tuple[str, ...]
+    match_workspace_paths: tuple[str, ...]
+    match_path_contains: tuple[str, ...]
+
+
+@dataclass(frozen=True)
+class EvidenceAllowlist:
+    canonical_entries: tuple[CanonicalEntry, ...]
+    process_path_prefixes: tuple[str, ...]
+    process_basename_globs: tuple[str, ...]
+    summary_statuses: frozenset[str]
+    full_statuses: frozenset[str]
+    pass_summary_fields: tuple[str, ...]
+    raw: dict[str, Any]
+
+    @property
+    def by_key(self) -> dict[str, CanonicalEntry]:
+        return {entry.key: entry for entry in self.canonical_entries}
+
+    @property
+    def canonical_paths(self) -> frozenset[str]:
+        return frozenset(entry.canonical_path.casefold() for entry in self.canonical_entries)
+
+
+def load_allowlist(path: Path | None = None) -> EvidenceAllowlist:
+    allowlist_path = path or DEFAULT_ALLOWLIST_PATH
+    payload = json.loads(allowlist_path.read_text(encoding="utf-8"))
+    if payload.get("schema") != "cpld-review-compact-evidence-allowlist-v1":
+        raise ValueError(f"unsupported evidence allowlist schema: {payload.get('schema')}")
+    entries: list[CanonicalEntry] = []
+    for row in payload.get("canonical_entries", []):
+        entries.append(
+            CanonicalEntry(
+                key=str(row["key"]),
+                canonical_path=str(row["canonical_path"]),
+                match_basenames=tuple(
+                    str(item).casefold() for item in row.get("match_basenames", [])
+                ),
+                match_workspace_paths=tuple(
+                    str(item).casefold() for item in row.get("match_workspace_paths", [])
+                ),
+                match_path_contains=tuple(
+                    str(item).casefold() for item in row.get("match_path_contains", [])
+                ),
+            )
+        )
+    process = payload.get("process_evidence", {})
+    log_policy = payload.get("log_policy", {})
+    return EvidenceAllowlist(
+        canonical_entries=tuple(entries),
+        process_path_prefixes=tuple(
+            str(item).casefold() for item in process.get("path_prefixes", [])
+        ),
+        process_basename_globs=tuple(
+            str(item).casefold() for item in process.get("basename_globs", [])
+        ),
+        summary_statuses=frozenset(
+            str(item).casefold() for item in log_policy.get("summary_statuses", [])
+        ),
+        full_statuses=frozenset(
+            str(item).casefold() for item in log_policy.get("full_statuses", [])
+        ),
+        pass_summary_fields=tuple(
+            str(item) for item in log_policy.get("pass_summary_fields", [])
+        ),
+        raw=payload,
+    )
+
+
+def _basename(relative: str) -> str:
+    return relative.casefold().rsplit("/", 1)[-1]
+
+
+def _strip_layout_prefix(relative: str) -> str:
+    lower = relative.casefold()
+    for prefix in ("evidence/", "source/", "meta/", "workspace-current/"):
+        if lower.startswith(prefix):
+            return relative[len(prefix) :]
+    return relative
+
+
+def match_canonical_entry(
+    relative: str,
+    allowlist: EvidenceAllowlist,
+    *,
+    workspace_original: str | None = None,
+) -> CanonicalEntry | None:
+    original = (workspace_original or _strip_layout_prefix(relative)).casefold()
+    name = _basename(original)
+    package_lower = relative.casefold()
+    for entry in allowlist.canonical_entries:
+        if original in entry.match_workspace_paths:
+            return entry
+        if package_lower == entry.canonical_path.casefold():
+            return entry
+        if entry.match_path_contains and any(
+            token in package_lower or token in original for token in entry.match_path_contains
+        ):
+            # Avoid matching unrelated summary.json files.
+            if entry.key == "deep_review_summary" and "deep-review" not in original and "deep-review" not in package_lower:
+                continue
+            return entry
+        if name in entry.match_basenames:
+            if entry.key == "deep_review_summary" and "deep-review" not in original and "deep-review" not in package_lower:
+                continue
+            return entry
+    return None
+
+
+def workspace_canonical_path(
+    original_relative: str,
+    allowlist: EvidenceAllowlist | None = None,
+) -> str | None:
+    """Map a workspace-relative path onto its compact canonical evidence path."""
+    allowlist = allowlist or load_allowlist()
+    entry = match_canonical_entry(original_relative, allowlist, workspace_original=original_relative)
+    if entry is None:
+        return None
+    return entry.canonical_path
+
+
+def is_process_evidence(relative: str, allowlist: EvidenceAllowlist | None = None) -> bool:
+    allowlist = allowlist or load_allowlist()
+    lower = relative.casefold()
+    original = _strip_layout_prefix(relative).casefold()
+    name = _basename(original)
+    for prefix in allowlist.process_path_prefixes:
+        if lower.startswith(prefix) or original.startswith(prefix):
+            return True
+        if f"/{prefix.rstrip('/')}/" in f"/{lower}/" or f"/{prefix.rstrip('/')}/" in f"/{original}/":
+            return True
+    for pattern in allowlist.process_basename_globs:
+        if fnmatch.fnmatch(name, pattern):
+            return True
+    # Deep-review rounds are process; summary is canonical.
+    if ("deep-review" in original or "deep-review" in lower) and name.startswith("round-"):
+        return True
+    return False
+
+
+def is_compact_allowlisted(relative: str, allowlist: EvidenceAllowlist | None = None) -> bool:
+    allowlist = allowlist or load_allowlist()
+    return match_canonical_entry(relative, allowlist) is not None
+
+
+def normalize_result_status(status: str | None) -> str:
+    if status is None:
+        return "unknown"
+    return str(status).strip().casefold()
+
+
+def log_retention_for_status(
+    status: str | None,
+    allowlist: EvidenceAllowlist | None = None,
+) -> str:
+    """PASS/not_run → summary; FAIL/BLOCKED/TIMEOUT/CRASH → full."""
+    allowlist = allowlist or load_allowlist()
+    normalized = normalize_result_status(status)
+    if normalized in allowlist.full_statuses:
+        return "full"
+    if normalized in allowlist.summary_statuses:
+        return "summary"
+    # Heuristic for compound statuses like pass_with_warnings.
+    if any(token in normalized for token in ("fail", "blocked", "timeout", "crash", "error")):
+        return "full"
+    if normalized.startswith("pass") or normalized in {"ok", "success", "not_run"}:
+        return "summary"
+    return "full"
+
+
+def build_pass_log_summary(
+    *,
+    source_path: str,
+    status: str,
+    metadata: dict[str, Any] | None = None,
+    allowlist: EvidenceAllowlist | None = None,
+) -> dict[str, Any]:
+    allowlist = allowlist or load_allowlist()
+    metadata = dict(metadata or {})
+    summary: dict[str, Any] = {
+        "schema": "cpld-pass-log-summary-v1",
+        "source_log": source_path,
+        "status": normalize_result_status(status),
+        "retention": "summary",
+        "note": (
+            "PASS/not_run lanes keep a summary only in review-compact; "
+            "full stdout/stderr is omitted by result-sensitive log policy."
+        ),
+    }
+    for field in allowlist.pass_summary_fields:
+        if field in metadata:
+            summary[field] = metadata[field]
+    return summary
+
+
+def extract_status_from_receipt(path: Path) -> str | None:
+    try:
+        payload = json.loads(path.read_text(encoding="utf-8"))
+    except (OSError, UnicodeError, json.JSONDecodeError):
+        return None
+    if not isinstance(payload, dict):
+        return None
+    for key in ("status", "result", "overall_status", "matrix_status"):
+        value = payload.get(key)
+        if isinstance(value, str) and value.strip():
+            return value
+    lanes = payload.get("lanes")
+    if isinstance(lanes, dict):
+        statuses = [
+            normalize_result_status(str(item.get("status")))
+            for item in lanes.values()
+            if isinstance(item, dict) and item.get("status") is not None
+        ]
+        for bad in ("fail", "failed", "blocked", "timeout", "crash", "error"):
+            if bad in statuses:
+                return bad
+        if statuses and all(item in {"pass", "passed", "ok", "success", "not_run"} for item in statuses):
+            return "pass"
+    return None
+
+
+def _sha256_file(path: Path) -> str:
+    digest = hashlib.sha256()
+    with path.open("rb") as handle:
+        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+            digest.update(chunk)
+    return digest.hexdigest()
+
+
+def _sha256_bytes(payload: bytes) -> str:
+    return hashlib.sha256(payload).hexdigest()
+
+
+def prefer_canonical_path(paths: Iterable[str], allowlist: EvidenceAllowlist | None = None) -> str:
+    """Choose the allowlisted canonical path when present among duplicates."""
+    allowlist = allowlist or load_allowlist()
+    path_list = list(paths)
+    if not path_list:
+        raise ValueError("prefer_canonical_path requires at least one path")
+
+    def rank(path: str) -> tuple[int, int, str]:
+        entry = match_canonical_entry(path, allowlist)
+        if entry is not None and path.casefold() == entry.canonical_path.casefold():
+            return (0, 0, path.casefold())
+        if entry is not None:
+            return (1, 0, path.casefold())
+        lower = path.casefold()
+        under_evidence = 0 if lower.startswith("evidence/") else 1
+        return (2, under_evidence, lower)
+
+    return sorted(path_list, key=rank)[0]
+
+
+@dataclass
+class StagedEvidenceFile:
+    absolute: Path
+    relative: str
+    key: str | None
+    original_path: str
+    retention: str | None = None
+
+
+@dataclass
+class EvidenceCanonResult:
+    staged: list[StagedEvidenceFile]
+    aliases: list[dict[str, Any]]
+    excluded: list[dict[str, str]]
+    log_policy_actions: list[dict[str, Any]]
+    catalog: list[dict[str, Any]]
+
+
+def _candidate_status_for_log(log_path: Path) -> str | None:
+    stem = log_path.name
+    parent = log_path.parent
+    # Prefer sibling *-receipt.json / *.json with matching stem prefix.
+    patterns = [
+        f"{log_path.stem}-receipt.json",
+        f"{log_path.stem}.json",
+        "formal-receipt.json",
+        "td-primary-receipt.json",
+        "matrix-receipt.json",
+        "verification-matrix-final.json",
+    ]
+    for name in patterns:
+        candidate = parent / name
+        if candidate.is_file():
+            status = extract_status_from_receipt(candidate)
+            if status is not None:
+                return status
+    for candidate in sorted(parent.glob("*-receipt.json")):
+        status = extract_status_from_receipt(candidate)
+        if status is not None:
+            return status
+    return None
+
+
+def stage_evidence_root(
+    evidence_root: Path,
+    *,
+    staging_root: Path,
+    include_process_evidence: bool = False,
+    allowlist: EvidenceAllowlist | None = None,
+    make_item: PackageItemFactory | None = None,
+) -> EvidenceCanonResult:
+    """Stage an external delivery/run evidence tree into canonical evidence/ paths."""
+    del make_item  # packager wraps StagedEvidenceFile itself
+    allowlist = allowlist or load_allowlist()
+    evidence_root = evidence_root.resolve(strict=True)
+    staging_root.mkdir(parents=True, exist_ok=True)
+
+    # key -> list of (abs, original_rel, sha, size)
+    matched: dict[str, list[tuple[Path, str, str, int]]] = {}
+    process_files: list[tuple[Path, str]] = []
+    log_actions: list[dict[str, Any]] = []
+    excluded: list[dict[str, str]] = []
+
+    for dirpath, dirnames, filenames in os.walk(evidence_root):
+        dirnames.sort(key=lambda name: name.casefold())
+        filenames.sort(key=lambda name: name.casefold())
+        base = Path(dirpath)
+        for filename in filenames:
+            absolute = base / filename
+            if not absolute.is_file() or absolute.is_symlink():
+                continue
+            original = absolute.relative_to(evidence_root).as_posix()
+            if is_process_evidence(original, allowlist):
+                if include_process_evidence:
+                    process_files.append((absolute, original))
+                else:
+                    excluded.append({"path": f"evidence/process/{original}", "rule": PROCESS_EXCLUDE_RULE})
+                continue
+            entry = match_canonical_entry(original, allowlist, workspace_original=original)
+            if entry is None:
+                # Non-allowlisted evidence stays process-only for compact.
+                if include_process_evidence:
+                    process_files.append((absolute, original))
+                else:
+                    excluded.append(
+                        {
+                            "path": f"evidence/process/{original}",
+                            "rule": NON_ALLOWLIST_RECEIPT_RULE,
+                        }
+                    )
+                continue
+            sha = _sha256_file(absolute)
+            size = absolute.stat().st_size
+            matched.setdefault(entry.key, []).append((absolute, original, sha, size))
+
+    staged: list[StagedEvidenceFile] = []
+    aliases: list[dict[str, Any]] = []
+    catalog: list[dict[str, Any]] = []
+
+    for key, copies in sorted(matched.items()):
+        entry = allowlist.by_key[key]
+        # Prefer identical content groups; if hashes differ, keep the largest (likely final).
+        by_hash: dict[str, list[tuple[Path, str, str, int]]] = {}
+        for copy in copies:
+            by_hash.setdefault(copy[2], []).append(copy)
+        chosen_hash = max(by_hash.keys(), key=lambda digest: (by_hash[digest][0][3], digest))
+        chosen_group = by_hash[chosen_hash]
+        primary_abs, primary_orig, primary_sha, primary_size = chosen_group[0]
+        dest = staging_root / Path(*entry.canonical_path.split("/"))
+        dest.parent.mkdir(parents=True, exist_ok=True)
+        if primary_abs.resolve() != dest.resolve():
+            dest.write_bytes(primary_abs.read_bytes())
+        staged.append(
+            StagedEvidenceFile(
+                absolute=dest,
+                relative=entry.canonical_path,
+                key=key,
+                original_path=primary_orig,
+            )
+        )
+        # Alias = other discovery paths that would have duplicated bytes.
+        other_logical = sorted(
+            {
+                f"evidence/from/{orig}"
+                for _abs, orig, digest, _size in copies
+                if digest == chosen_hash
+            }
+        )
+        other_logical = [
+            path
+            for path in other_logical
+            if path.casefold() != f"evidence/from/{primary_orig}".casefold()
+        ]
+        if other_logical:
+            aliases.append(
+                {
+                    "key": key,
+                    "sha256": primary_sha,
+                    "size": primary_size,
+                    "physical_path": entry.canonical_path,
+                    "logical_paths": other_logical,
+                    "reason": EVIDENCE_ALIAS_REASON,
+                }
+            )
+        for _abs, orig, digest, _size in copies:
+            if digest == chosen_hash:
+                continue
+            excluded.append(
+                {
+                    "path": f"evidence/from/{orig}",
+                    "rule": "conflicting_evidence_hash_not_selected",
+                }
+            )
+        catalog.append(
+            {
+                "key": key,
+                "canonical_path": entry.canonical_path,
+                "sha256": primary_sha,
+                "size": primary_size,
+                "source_original": primary_orig,
+                "role": "compact_default",
+                "duplicate_sources": [orig for _a, orig, digest, _s in copies if digest == chosen_hash],
+            }
+        )
+
+    if include_process_evidence:
+        for absolute, original in process_files:
+            rel = f"evidence/process/{original}"
+            dest = staging_root / Path(*rel.split("/"))
+            dest.parent.mkdir(parents=True, exist_ok=True)
+            if absolute.suffix.casefold() in {".log", ".logw"}:
+                status = _candidate_status_for_log(absolute) or "unknown"
+                retention = log_retention_for_status(status, allowlist)
+                log_actions.append(
+                    {
+                        "path": original,
+                        "status": normalize_result_status(status),
+                        "retention": retention,
+                    }
+                )
+                if retention == "summary":
+                    summary = build_pass_log_summary(
+                        source_path=original,
+                        status=status,
+                        metadata={
+                            "artifact_hashes": {"source_log_sha256": _sha256_file(absolute)},
+                            "result_summary": f"{normalize_result_status(status)} (full log omitted)",
+                            "warning_summary": [],
+                        },
+                        allowlist=allowlist,
+                    )
+                    dest = dest.with_name(dest.name + LOG_SUMMARY_SUFFIX)
+                    dest.parent.mkdir(parents=True, exist_ok=True)
+                    dest.write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
+                    staged.append(
+                        StagedEvidenceFile(
+                            absolute=dest,
+                            relative=dest.relative_to(staging_root).as_posix(),
+                            key=None,
+                            original_path=original,
+                            retention="summary",
+                        )
+                    )
+                    continue
+            dest.write_bytes(absolute.read_bytes())
+            staged.append(
+                StagedEvidenceFile(
+                    absolute=dest,
+                    relative=rel,
+                    key=None,
+                    original_path=original,
+                    retention="full" if absolute.suffix.casefold() in {".log", ".logw"} else None,
+                )
+            )
+
+    aliases.sort(key=lambda row: str(row["physical_path"]).casefold())
+    excluded.sort(key=lambda row: row["path"].casefold())
+    catalog.sort(key=lambda row: str(row["key"]))
+    return EvidenceCanonResult(
+        staged=staged,
+        aliases=aliases,
+        excluded=excluded,
+        log_policy_actions=log_actions,
+        catalog=catalog,
+    )
+
+
+def filter_package_items_for_compact(
+    items: Iterable[Any],
+    *,
+    profile: str,
+    include_process_evidence: bool,
+    allowlist: EvidenceAllowlist | None = None,
+    relative_attr: str = "candidate",
+) -> tuple[list[Any], list[dict[str, str]], list[dict[str, Any]]]:
+    """Drop process / non-allowlisted evidence from review-compact collections.
+
+    Items whose package path is under evidence/ (or workspace receipts that look
+    like evidence) are filtered. Source/meta board-viewer derived assets are kept.
+    """
+    allowlist = allowlist or load_allowlist()
+    include_process = include_process_evidence or profile == "review-debug"
+    if profile not in {"review-compact", "review-debug"}:
+        return list(items), [], []
+
+    kept: list[Any] = []
+    excluded: list[dict[str, str]] = []
+    remaps: list[dict[str, Any]] = []
+
+    for item in items:
+        candidate = getattr(item, relative_attr)
+        relative = candidate.relative if hasattr(candidate, "relative") else str(candidate)
+        lower = relative.casefold()
+        original = getattr(item, "original_path", _strip_layout_prefix(relative))
+
+        # Board-viewer derived assets and meta are not receipt allowlist subjects.
+        if lower.startswith("evidence/board-viewer/") or lower.startswith("meta/"):
+            kept.append(item)
+            continue
+        if not (
+            lower.startswith("evidence/")
+            or lower.startswith("source/receipts/")
+            or str(original).casefold().startswith("receipts/")
+        ):
+            kept.append(item)
+            continue
+
+        if is_process_evidence(relative, allowlist) or is_process_evidence(str(original), allowlist):
+            if include_process:
+                kept.append(item)
+            else:
+                excluded.append({"path": relative, "rule": PROCESS_EXCLUDE_RULE})
+            continue
+
+        if is_compact_allowlisted(relative, allowlist) or is_compact_allowlisted(str(original), allowlist):
+            kept.append(item)
+            continue
+
+        # Historical receipts/ under evidence that are not on the allowlist.
+        if include_process:
+            kept.append(item)
+        else:
+            excluded.append({"path": relative, "rule": NON_ALLOWLIST_RECEIPT_RULE})
+
+    return kept, excluded, remaps
+
+
+def build_evidence_canon_index_fields(
+    *,
+    catalog: list[dict[str, Any]],
+    aliases: list[dict[str, Any]],
+    log_policy_actions: list[dict[str, Any]],
+    include_process_evidence: bool,
+    profile: str,
+) -> dict[str, Any]:
+    return {
+        "schema": EVIDENCE_CANON_SCHEMA,
+        "profile": profile,
+        "include_process_evidence": include_process_evidence or profile == "review-debug",
+        "compact_default_keys": sorted(
+            {str(row["key"]) for row in catalog if row.get("role") == "compact_default"}
+        ),
+        "catalog": catalog,
+        "aliases": aliases,
+        "log_policy": {
+            "schema": "cpld-result-sensitive-log-policy-v1",
+            "pass_retention": "summary",
+            "fail_retention": "full",
+            "actions": log_policy_actions,
+        },
+    }
+
+
+def compact_default_key_list(allowlist: EvidenceAllowlist | None = None) -> list[str]:
+    allowlist = allowlist or load_allowlist()
+    return [entry.key for entry in allowlist.canonical_entries]