Explorar el Código

merge: P1 packager-core tip into evidence lane

root hace 3 meses
padre
commit
479bf9108d

+ 46 - 94
PACKAGE_FOR_AGENT_ANALYSIS.README.zh-CN.md

@@ -1,125 +1,77 @@
-# CPLD 完整分析打包工具
+# CPLD 分析打包工具
 
 根目录入口:
 
-```powershell
-python .\package_for_agent_analysis.py
+```bash
+python3 package_for_agent_analysis.py --profile review-compact --output-dir /tmp/prod2u-handoff
+# 或薄封装:
+tools/package-review-compact.sh
 ```
 
-这个工具用于把指定来源根目录和配置中的外部关联目录交给其他 agent 分析。核心规则是:**来源根内的分析资料默认收入,只执行明确、版本化的递归负向排除规则。** 它不使用 Git 跟踪状态或正向 include 白名单;缓存、虚拟环境、运行态、交付目录和可重建编译产物会在任意子目录递归排除。
+默认上传 profile 是 **`review-compact`**:统一 `source/` + `evidence/` + `meta/` 布局,单一 ZIP + `.tar.zst`,不含完整 Git bundle / PDF / BRD / DSN 原件。
 
 要求 Python 3.11 或更高版本。默认配置是 `config/agent_analysis_handoff_sources.json`,结构约束是 `schemas/agent_analysis_handoff_sources.schema.json`。
 
-## 默认来源
+## Profiles
 
-默认以脚本所在仓库为 primary source root(即当前 CPLD 仓库)。当前 `config/agent_analysis_handoff_sources.json` 的外部来源列表为空:历史工作树、设计权威文档等旧硬编码路径已移除。若需要补充稳定参考资料,请通过 `--config` 传入自定义配置,并确保路径可移植(使用 `{repo_root}`、`{user_profile}` 或相对路径),且不指向一次性旧工作树。
+| Profile | 用途 | 布局 | 完整 Git bundle |
+|---|---|---|---|
+| `review-compact` | **默认远程上传** | `source/` + `evidence/` + `meta/` | 否(commit/status/log-20/tree/逐文件 SHA-256 + TD binding hooks) |
+| `review-debug` | 复杂失败时的调试包 | 同上 | 否 |
+| `archive-local` | 本地归档(默认不上传) | 同上 | 默认是(可用 `--no-git-bundle` 关闭;`--include-full-history` 强制) |
+| `full` | 兼容旧 inclusion-first | `workspace-current` + core/reference 分包 | **必须** |
+| `code-only` | 兼容代码+测试包 | `workspace-current` | 可选 |
 
-`.codegraph` junction 及其 `.omo` 目标是生成的代码图缓存,不收入。
+固件包仍由 `tools/build_firmware_package.py` 独立产出,本工具不改动固件路径。
 
-外部来源不存在时,结果是 `pass_with_warnings`,并在 `HANDOFF-INDEX.json` 记录缺失来源。来源已经找到,但扫描、Git bundle、路径安全、凭据检查或完整性校验失败时,工具直接失败,不会把完整性错误降级成警告。
+## review-compact 调用
 
-## 常用命令
+```bash
+python3 package_for_agent_analysis.py \
+  --profile review-compact \
+  --output-dir "${TMPDIR:-/tmp}/prod2u-handoff" \
+  --package-name "prod2u-review-compact-$(date -u +%Y%m%dT%H%M%SZ)"
 
-完整审计但不创建 ZIP:
-
-```powershell
-python .\package_for_agent_analysis.py --audit-only
-```
-
-解释一个路径为什么收入或排除(路径可以是相对或绝对路径):
-
-```powershell
-python .\package_for_agent_analysis.py --explain .\td\build\current\design.bit
-python .\package_for_agent_analysis.py --explain C:\Anlogic\TD_Release_2026.1_SP1.198.412\doc\TD_User_Guide.pdf
-```
-
-`--explain` 只解释路径规则,不读取文件正文,所以输出中的 `content_scan` 是 `not_run`。完整凭据和归档成员检查由 `--audit-only` 或正式打包执行。
-
-指定 primary source root(配置中的 `{repo_root}` 会随它变化):
-
-```powershell
-python .\package_for_agent_analysis.py --source-root C:\work\CPLD
-```
-
-`--no-git-bundle` 用于省略 Git 历史 bundle,显著减小包体积。
-
-指定配置、输出目录和包名:
-
-```powershell
-python .\package_for_agent_analysis.py `
-  --config .\config\agent_analysis_handoff_sources.json `
-  --output-dir C:\handoff `
-  --package-name cpld-analysis-20260721
-```
-
-同名目录默认拒绝覆盖。确认要原子替换旧目录时使用:
-
-```powershell
-python .\package_for_agent_analysis.py --package-name cpld-analysis-20260721 --force-overwrite
+# 等价:
+tools/package-review-compact.sh
 ```
 
-## 收入和排除规则
-
-默认保留源码、测试、文档、原理图、Allegro `.brd`、`board.xml`、`board.cad`、PDF、公开资料、原始源码、未跟踪 receipts、formal/离线证据和必要的原始资料包。当前仓库和独立 Git 工作树还会保存文件系统快照以及经过 `git bundle verify` 的 `git bundle --all`(可用 `--no-git-bundle` 关闭),但不复制 raw `.git`。
-
-硬排除包括许可证、私钥、真实 `.env`、凭据配置、raw `.git`、路径逃逸、未声明 junction/symlink/reparse point 和输出目录回灌。递归排除包括 `__pycache__`、`.venv`、`.pytest_cache`、`.hypothesis`、`.ruff_cache`、`.mypy_cache`、`.tox`、`.nox`、`node_modules`、`.playwright-browsers`、`*.egg-info`、`build`、`dist`、`runs`、`td/build` 及可重建的 `.bit`、`.bid`、`.data`、`.db`、`.timing`、`.rpt`、`.area`、`.qor`、`.vvp` 文件。
+可选:
 
-所有 ZIP、RAR、7z 和可识别的归档都会由 7-Zip 或 Python `zipfile`/`tarfile` 检查成员路径。没有被过滤成员的原始资料包保留原包;包含编译物、缓存或敏感成员时,只保留安全展开成员,并在排除索引中记录原包。找不到 7-Zip 时使用 Python `zipfile` 回退打包,不失败。
+- `--include-sanitized-git-snapshot`:预留 P2 合成单 commit 快照钩子(当前写入 `meta/git/sanitized-snapshot-status.json`,不冒充原始 tip)
+- `--audit-only`:只扫描不写 ZIP
+- `--explain PATH`:解释某路径是否收入
 
-## 输出结构:core 与 reference
+## 收入与排除(review-*)
 
-打包完成后会生成两个独立包目录:
+**保留**:活动源码/测试/协议/项目合同、board-viewer 六件派生资产(`board-data.json` / `build-info.json` / `import-report.json` / 三张 SVG)、`tests/board_viewer/fixtures` 小 fixture、最终收据类 evidence。
 
-- `<package-name>`:core 包,含源码、工作区快照、Git bundle(除非 `--no-git-bundle`)和 `reference/historical/` 以外的核心文件;
-- `<package-name>-reference`:reference 包,含 `td-docs` 和来源中的 `reference/` 目录文件(`reference/historical/` 除外)。
+**排除**:`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 包使用 SHA-256 指纹缓存:只要 reference 内容指纹不变且未指定 `--force-overwrite`,工具会跳过重复构建,返回 `mode: reference_cached`。
-
-两个包目录都位于默认输出目录:
-
-```text
-%USERPROFILE%\Downloads\CPLD-agent-analysis\<package-name>\
-%USERPROFILE%\Downloads\CPLD-agent-analysis\<package-name>-reference\
-```
+## 包目录内容
 
-每个目录内包含:
+- 一个(或少数)普通 `.zip` + 同源 `.tar.zst`
+- `PACKAGE-PURPOSE.txt`:上传意图
+- `HANDOFF-INDEX.json`:来源、卷、SHA-256、`member_count`(ZIP 业务成员 vs 自引用控制文件)、`size_budget`、`content_dedup` aliases、`derived_evidence`
+- `size-budget.json`:≥256KiB 或 >1% 体积成员表
+- `EXCLUSIONS.txt` / `START-HERE.zh-CN.md` / `SHA256SUMS.txt`
 
-- 一个或多个普通 `.zip`;
-- `HANDOFF-INDEX.json`:总索引、来源、卷、逐文件 SHA-256、Git、警告和排除原因;
-- `START-HERE.zh-CN.md`:交接起点;
-- `SHA256SUMS.txt`:所有 ZIP 的 SHA-256;
-- `reassemble_large_files.py`:只有发生大文件分块时才生成;
-- `REFERENCE-FINGERPRINT`:reference 包特有,用于缓存判断。
+ZIP 内(`CPLD/` 根下):
 
-每个 ZIP 内都有自己的 `CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json`。总索引结构由 `schemas/agent_analysis_handoff_index.schema.json` 约束。
+- `source/` 活动源与测试
+- `evidence/` 收据与 board-viewer 派生资产(物理 dedup + index aliases)
+- `meta/` PACKAGE-PURPOSE、git 溯源、TD source-closure binding hooks
 
-## ZIP 大小和多卷
-
-工具优先使用 7-Zip 压缩一个完整的普通 ZIP,参数为标准 Deflate `-mx=9`,不使用 LZMA;未安装 7-Zip 时回退到 Python `zipfile`:
-
-- 压缩后严格小于 `380,000,000` 字节:发布一个普通 ZIP;
-- 达到或超过该值:改为多个互相独立的普通 ZIP,目标大小不超过 `350,000,000` 字节;
-- 无论哪种模式,每个最终 ZIP 都必须严格小于 `380,000,000` 字节,否则整个运行失败;
-- 单个文件无法放入目标卷时,会拆成多个 ZIP 内部块,并记录原文件 SHA-256。
-
-## 解压和重组
-
-多个 ZIP 是独立 ZIP,不是 7-Zip/RAR 连续分卷。可以全部解压到同一个目录;源文件路径不会互相冲突。各卷中的同名 `VOLUME-MANIFEST.json` 只描述当前卷,统一解压时最后一个可能覆盖前一个,因此跨卷分析应以外层 `HANDOFF-INDEX.json` 为准。
-
-```powershell
-New-Item -ItemType Directory -Force .\extracted | Out-Null
-Get-ChildItem -Filter *.zip | ForEach-Object {
-  Expand-Archive -LiteralPath $_.FullName -DestinationPath .\extracted -Force
-}
-```
+成员计数语义:`member_count.indexed_files` = `files[]`;`self_reference_control_files` 是包目录控制文件(列入 SHA256SUMS),不要与 ZIP payload 重复加总。
 
-如果存在大文件分块,直接从交付目录运行:
+## 兼容命令(legacy)
 
-```powershell
-python .\reassemble_large_files.py --package-dir . --output-dir .\reassembled
+```bash
+python3 package_for_agent_analysis.py --profile full --output-dir /tmp/out
+python3 package_for_agent_analysis.py --profile code-only --no-git-bundle
 ```
 
-脚本会逐块核对 SHA-256,重组完成后再次核对原始文件大小和 SHA-256;任一不一致都会失败且不会覆盖最终目标文件,失败时可删除同目录的 `.partial` 文件后重试。
+`--no-git-bundle` 在 `full` 下会失败(full 强制 bundle)。`review-compact` 始终无 bundle。
 
 ## 安全边界
 

+ 421 - 54
package_for_agent_analysis.py

@@ -49,11 +49,21 @@ DERIVED_BOARD_VIEWER_ASSETS = frozenset(
         "import-report.json",
     }
 )
+SELF_REFERENCE_CONTROL_FILES = (
+    "HANDOFF-INDEX.json",
+    "SHA256SUMS.txt",
+    "EXCLUSIONS.txt",
+    "PACKAGE-PURPOSE.txt",
+    "START-HERE.zh-CN.md",
+    "size-budget.json",
+)
 CATEGORY_ORDER = {
     "core": 0,
+    "source": 0,
     "hardware": 1,
     "td-docs": 2,
     "evidence": 3,
+    "meta": 4,
 }
 GENERATED_BINARY_SUFFIXES = {
     ".bit",
@@ -453,6 +463,12 @@ def analysis_exclusion_reason(
         if not is_dir and handoff.is_under(lower, "tools/board-viewer/generated"):
             if name in handoff.CODE_ONLY_GENERATED_VISUAL_ASSETS:
                 return "generated_board_viewer_visual_asset"
+    if handoff.is_review_profile(profile):
+        review_reason = handoff.review_exclusion_reason(
+            relative, is_dir=is_dir, profile=profile
+        )
+        if review_reason:
+            return review_reason
     for item in extra_exclusions:
         prefix = str(item.get("path", "")).casefold().strip("/")
         if prefix and handoff.is_under(lower, prefix):
@@ -547,13 +563,21 @@ def analysis_exclusion_reason(
         if suffix in RUNTIME_EVIDENCE_SUFFIXES:
             return "runtime_evidence_or_waveform"
         if suffix in BOARD_DESIGN_SUFFIXES:
+            if handoff.is_board_viewer_fixture_path(relative):
+                return None
+            if handoff.is_review_profile(profile):
+                return "heavy_design_original_not_packaged"
             if "reference" in parts:
                 return None
             return "board_design_file"
         if suffix in IMAGE_SUFFIXES:
-            if "reference" in parts:
+            if name in BOARD_VIEWER_GENERATED_ASSETS or name in DERIVED_BOARD_VIEWER_ASSETS:
                 return None
-            if name in BOARD_VIEWER_GENERATED_ASSETS:
+            if handoff.is_board_viewer_fixture_path(relative):
+                return None
+            if handoff.is_review_profile(profile) and suffix == ".pdf":
+                return "heavy_design_original_not_packaged"
+            if "reference" in parts:
                 return None
             return "image_file"
         if name in STRAY_FILENAMES:
@@ -726,6 +750,63 @@ def _run_git(command: list[str], *, cwd: Path, timeout: int = 300) -> str:
     return completed.stdout
 
 
+def _is_evidence_source_path(relative: str) -> bool:
+    lower = relative.casefold()
+    if handoff.is_under(lower, "receipts"):
+        return True
+    if handoff.is_under(lower, "tools/board-viewer/generated"):
+        return True
+    name = lower.rsplit("/", 1)[-1]
+    if name in DERIVED_BOARD_VIEWER_ASSETS and "board-viewer" in lower:
+        return True
+    return False
+
+
+def _unified_layout_prefix(
+    *,
+    source_id: str,
+    original_relative: str,
+    profile: str,
+) -> tuple[str, str]:
+    """Return (archive_prefix, category) for unified review layouts."""
+    del profile
+    if source_id == "board-viewer-generated" or source_id.startswith("board-viewer"):
+        return "evidence/board-viewer", "evidence"
+    if source_id != "workspace-current" and source_id != "source":
+        if _is_evidence_source_path(original_relative):
+            return f"evidence/external/{source_id}", "evidence"
+        return f"source/external/{source_id}", "source"
+    if _is_evidence_source_path(original_relative):
+        return "evidence", "evidence"
+    return "source", "source"
+
+
+def _materialize_bytes_items(
+    payloads: dict[str, bytes],
+    *,
+    temp_root: Path,
+    source_id: str,
+    category: str,
+) -> list[PackageItem]:
+    items: list[PackageItem] = []
+    root = temp_root / "generated-meta"
+    root.mkdir(parents=True, exist_ok=True)
+    for relative, payload in sorted(payloads.items()):
+        path = root / Path(*relative.split("/"))
+        path.parent.mkdir(parents=True, exist_ok=True)
+        path.write_bytes(payload)
+        items.append(
+            make_package_item(
+                path,
+                relative=relative,
+                category=category,
+                source_id=source_id,
+                scan_archive=False,
+            )
+        )
+    return items
+
+
 def _create_git_bundle(
     *,
     root: Path,
@@ -788,14 +869,22 @@ def collect_analysis_inputs(
     temp_root: Path,
     include_git_bundle: bool = True,
     profile: str = "full",
+    include_sanitized_git_snapshot: bool = False,
+    package_name: str = "pending",
 ) -> AnalysisCollection:
     root = repo_root.resolve(strict=True)
     temp_root.mkdir(parents=True, exist_ok=True)
+    if profile not in handoff.HANDOFF_PROFILES:
+        raise PackagingError(f"unsupported handoff profile: {profile}")
     if profile == "full" and not include_git_bundle:
         raise PackagingError(
             "full inclusion-first packages require a git bundle so replay can restore "
             "commit-to-commit source closure comparison"
         )
+    unified = handoff.uses_unified_layout(profile)
+    # review-compact / review-debug never ship a full bundle unless explicitly forced later.
+    if profile in {"review-compact", "review-debug"}:
+        include_git_bundle = False
     items: list[PackageItem] = []
     excluded: list[dict[str, str]] = []
     warnings: list[dict[str, str]] = []
@@ -803,28 +892,90 @@ def collect_analysis_inputs(
     git_metadata: list[dict[str, object]] = []
     source_snapshots: list[SourceSnapshot] = []
 
-    root_items, root_excluded = _collect_directory_items(
-        root=root,
-        source_id="workspace-current",
-        category="core",
-        prefix="workspace-current",
-        extra_exclusions=config.extra_exclusions,
-        profile=profile,
-    )
-    items.extend(root_items)
-    excluded.extend(root_excluded)
+    primary_source_id = "workspace-current"
+    if unified:
+        # Collect with a temporary prefix, then remap into source/ or evidence/.
+        root_items, root_excluded = _collect_directory_items(
+            root=root,
+            source_id=primary_source_id,
+            category="source",
+            prefix="__workspace__",
+            extra_exclusions=config.extra_exclusions,
+            profile=profile,
+        )
+        remapped: list[PackageItem] = []
+        for item in root_items:
+            original = item.original_path
+            prefix, category = _unified_layout_prefix(
+                source_id=primary_source_id,
+                original_relative=original,
+                profile=profile,
+            )
+            remapped.append(
+                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,
+                    ),
+                    category=category,
+                    source_id=primary_source_id,
+                    original_path=original,
+                    scan_archive=item.scan_archive,
+                )
+            )
+        items.extend(remapped)
+        for entry in root_excluded:
+            original_excluded = entry["path"]
+            if original_excluded.startswith("__workspace__/"):
+                original_excluded = original_excluded[len("__workspace__/") :]
+            elif original_excluded == "__workspace__":
+                original_excluded = "."
+            prefix, _category = _unified_layout_prefix(
+                source_id=primary_source_id,
+                original_relative=original_excluded,
+                profile=profile,
+            )
+            excluded.append(
+                {
+                    "path": (
+                        original_excluded
+                        if original_excluded == "."
+                        else f"{prefix}/{original_excluded}"
+                    ),
+                    "rule": entry["rule"],
+                }
+            )
+    else:
+        root_items, root_excluded = _collect_directory_items(
+            root=root,
+            source_id=primary_source_id,
+            category="core",
+            prefix="workspace-current",
+            extra_exclusions=config.extra_exclusions,
+            profile=profile,
+        )
+        items.extend(root_items)
+        excluded.extend(root_excluded)
     source_snapshots.append(
         _source_snapshot(
             root,
-            source_id="workspace-current",
+            source_id=primary_source_id,
             extra_exclusions=config.extra_exclusions,
             profile=profile,
         )
     )
     sources.append(
         {
-            "id": "workspace-current",
-            "category": "core",
+            "id": primary_source_id,
+            "category": "source" if unified else "core",
             "kind": "git_worktree",
             "path": str(root),
             "status": "pass",
@@ -833,11 +984,59 @@ def collect_analysis_inputs(
     if include_git_bundle:
         bundle_item, bundle_metadata = _create_git_bundle(
             root=root,
-            source_id="workspace-current",
+            source_id=primary_source_id,
             temp_root=temp_root,
         )
+        if unified:
+            # Keep bundle under meta/git-history for archive-local.
+            bundle_rel = f"meta/git-history/{primary_source_id}.bundle"
+            bundle_item = PackageItem(
+                candidate=handoff.Candidate(
+                    absolute=bundle_item.candidate.absolute,
+                    relative=bundle_rel,
+                    size=bundle_item.candidate.size,
+                    mtime_ns=bundle_item.candidate.mtime_ns,
+                    device=bundle_item.candidate.device,
+                    inode=bundle_item.candidate.inode,
+                    mode=bundle_item.candidate.mode,
+                ),
+                category="meta",
+                source_id=primary_source_id,
+                original_path=".git",
+                scan_archive=False,
+            )
+            bundle_metadata = {**bundle_metadata, "bundle_path": bundle_rel}
         items.append(bundle_item)
         git_metadata.append(bundle_metadata)
+    elif unified:
+        provenance, provenance_artifacts = handoff.collect_review_git_provenance(
+            root,
+            include_sanitized_git_snapshot=include_sanitized_git_snapshot,
+            meta_prefix="meta/git",
+        )
+        binding = handoff.build_td_source_closure_binding_hook(root)
+        provenance_artifacts["meta/td-source-closure-binding.json"] = handoff.json_bytes(binding)
+        purpose = handoff.package_purpose_text(profile, package_name=package_name)
+        provenance_artifacts["meta/PACKAGE-PURPOSE.txt"] = purpose.encode("utf-8")
+        items.extend(
+            _materialize_bytes_items(
+                provenance_artifacts,
+                temp_root=temp_root,
+                source_id="meta-generated",
+                category="meta",
+            )
+        )
+        git_metadata.append(
+            {
+                "source_id": primary_source_id,
+                "status": provenance.get("status"),
+                "branch": provenance.get("branch"),
+                "head": provenance.get("head"),
+                "full_bundle": False,
+                "provenance": provenance,
+                "td_source_closure_binding": binding,
+            }
+        )
 
     resolved_sources, source_warnings = resolve_external_sources(config.external_sources)
     if profile == "code-only":
@@ -846,47 +1045,127 @@ def collect_analysis_inputs(
         ]
     warnings.extend(source_warnings)
     for source in resolved_sources:
-        prefix = f"external/{source.id}"
-        if source.kind == "file":
-            candidate = _candidate_from_path(source.path, f"{prefix}/{source.path.name}")
-            items.append(
-                PackageItem(
-                    candidate=candidate,
-                    category=source.category,
+        if unified:
+            # Prefer derived board-viewer assets under evidence/.
+            if source.kind == "file":
+                prefix, category = _unified_layout_prefix(
                     source_id=source.id,
-                    original_path=source.path.name,
-                    scan_archive=source.archive_policy == "inspect",
+                    original_relative=source.path.name,
+                    profile=profile,
+                )
+                candidate = _candidate_from_path(
+                    source.path, f"{prefix}/{source.path.name}"
+                )
+                items.append(
+                    PackageItem(
+                        candidate=candidate,
+                        category=category,
+                        source_id=source.id,
+                        original_path=source.path.name,
+                        scan_archive=source.archive_policy == "inspect",
+                    )
+                )
+            else:
+                source_items, source_excluded = _collect_directory_items(
+                    root=source.path,
+                    source_id=source.id,
+                    category="evidence",
+                    prefix="__external__",
+                    extra_exclusions=config.extra_exclusions,
+                    profile=profile,
+                )
+                for item in source_items:
+                    original = item.original_path
+                    prefix, category = _unified_layout_prefix(
+                        source_id=source.id,
+                        original_relative=original,
+                        profile=profile,
+                    )
+                    items.append(
+                        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,
+                            ),
+                            category=category,
+                            source_id=source.id,
+                            original_path=original,
+                            scan_archive=item.scan_archive,
+                        )
+                    )
+                for entry in source_excluded:
+                    original_excluded = entry["path"]
+                    if original_excluded.startswith("__external__/"):
+                        original_excluded = original_excluded[len("__external__/") :]
+                    prefix, _category = _unified_layout_prefix(
+                        source_id=source.id,
+                        original_relative=original_excluded,
+                        profile=profile,
+                    )
+                    excluded.append(
+                        {
+                            "path": f"{prefix}/{original_excluded}",
+                            "rule": entry["rule"],
+                        }
+                    )
+                source_snapshots.append(
+                    _source_snapshot(
+                        source.path,
+                        source_id=source.id,
+                        extra_exclusions=config.extra_exclusions,
+                        profile=profile,
+                    )
                 )
-            )
         else:
-            source_items, source_excluded = _collect_directory_items(
-                root=source.path,
-                source_id=source.id,
-                category=source.category,
-                prefix=prefix,
-                extra_exclusions=config.extra_exclusions,
-                profile=profile,
-            )
-            items.extend(source_items)
-            excluded.extend(source_excluded)
-            source_snapshots.append(
-                _source_snapshot(
-                    source.path,
+            prefix = f"external/{source.id}"
+            if source.kind == "file":
+                candidate = _candidate_from_path(source.path, f"{prefix}/{source.path.name}")
+                items.append(
+                    PackageItem(
+                        candidate=candidate,
+                        category=source.category,
+                        source_id=source.id,
+                        original_path=source.path.name,
+                        scan_archive=source.archive_policy == "inspect",
+                    )
+                )
+            else:
+                source_items, source_excluded = _collect_directory_items(
+                    root=source.path,
                     source_id=source.id,
+                    category=source.category,
+                    prefix=prefix,
                     extra_exclusions=config.extra_exclusions,
                     profile=profile,
                 )
-            )
+                items.extend(source_items)
+                excluded.extend(source_excluded)
+                source_snapshots.append(
+                    _source_snapshot(
+                        source.path,
+                        source_id=source.id,
+                        extra_exclusions=config.extra_exclusions,
+                        profile=profile,
+                    )
+                )
         sources.append(
             {
                 "id": source.id,
-                "category": source.category,
+                "category": "evidence" if unified else source.category,
                 "kind": source.kind,
                 "path": str(source.path),
                 "status": "pass",
             }
         )
-        if source.kind == "git_worktree":
+        if source.kind == "git_worktree" and include_git_bundle:
             external_bundle, external_git = _create_git_bundle(
                 root=source.path,
                 source_id=source.id,
@@ -1289,6 +1568,7 @@ def _is_board_viewer_generated_path(relative: str) -> bool:
     lower = relative.casefold()
     return (
         "board-viewer-generated" in lower
+        or handoff.is_under(lower, "evidence/board-viewer")
         or "/tools/board-viewer/generated/" in f"/{lower}/"
         or lower.startswith("tools/board-viewer/generated/")
     )
@@ -1889,8 +2169,8 @@ def _assert_source_trees_unchanged(collection: AnalysisCollection, *, profile: s
             raise PackagingError("source tree changed during analysis packaging: retry from a stable workspace snapshot")
 
 
-def _start_here_text(package_name: str, volume_count: int) -> str:
-    return (
+def _start_here_text(package_name: str, volume_count: int, *, profile: str = "full") -> str:
+    base = (
         f"# {package_name} 分析交付包\n\n"
         f"本目录包含 {volume_count} 个互相独立的普通 ZIP,以及可选的 `.tar.zst` 同源归档。"
         "请先核对 `SHA256SUMS.txt`,再把所有 ZIP 解压到同一个目录;"
@@ -1899,11 +2179,42 @@ def _start_here_text(package_name: str, volume_count: int) -> str:
         "`EXCLUSIONS.txt` 列出排除路径与规则,"
         "以及 `excluded`(排除原因)、`derived_evidence`(由原始 BRD 派生的 board-viewer JSON/SVG,"
         "不是 RTL/TD source closure)和 `content_dedup`(相同大文件只保留一份物理副本时的逻辑归属)。\n"
+    )
+    if handoff.uses_unified_layout(profile):
+        return base + (
+            "本包为统一布局:`source/` + `evidence/` + `meta/`。\n"
+            "`PACKAGE-PURPOSE.txt` 说明上传意图;`size-budget.json` 列出 ≥256KiB 或 >1% 体积的成员。\n"
+            "默认 **不含** 完整 Git bundle;`meta/git/` 提供 commit/status/log-20/tree/逐文件 SHA-256 "
+            "与 TD source-closure 绑定钩子。\n"
+            "成员计数:`member_count.indexed_files` 对应 ZIP 内业务文件;"
+            "`self_reference_control_files` 是包目录控制文件(亦列入 SHA256SUMS),"
+            "不要把控制文件与 ZIP payload 成员重复加总。\n"
+        )
+    return base + (
         "完整 full 包必须包含 `git-history/*.bundle`,以便在干净提取后用 commit-to-commit "
         "恢复 source closure 比对。\n"
     )
 
 
+def build_member_count_semantics(
+    *,
+    indexed_files: int,
+    zip_file_entries: int,
+    control_files: tuple[str, ...] = SELF_REFERENCE_CONTROL_FILES,
+) -> dict[str, object]:
+    return {
+        "indexed_files": indexed_files,
+        "zip_file_entries": zip_file_entries,
+        "self_reference_control_files": list(control_files),
+        "note": (
+            "indexed_files counts HANDOFF-INDEX files[] (ZIP payload business members). "
+            "zip_file_entries counts non-directory ZIP entries including VOLUME-MANIFEST. "
+            "self_reference_control_files live in the package directory and appear in "
+            "SHA256SUMS; do not add them again to indexed_files."
+        ),
+    }
+
+
 def write_exclusions_text(excluded: list[dict[str, object]]) -> str:
     """Render a portable EXCLUSIONS.txt for the package sidecar layout."""
     lines = [
@@ -1978,6 +2289,8 @@ def write_package_layout_sidecars(
     excluded: list[dict[str, object]],
     package_name: str,
     include_tar_zst: bool = True,
+    profile: str = "full",
+    size_budget: dict[str, object] | None = None,
 ) -> list[dict[str, object]]:
     """Write index/checksums/exclusions and optional tar.zst; return checksum rows."""
     staging.mkdir(parents=True, exist_ok=True)
@@ -1987,11 +2300,18 @@ def write_package_layout_sidecars(
         encoding="utf-8",
         newline="\n",
     )
+    (staging / "PACKAGE-PURPOSE.txt").write_text(
+        handoff.package_purpose_text(profile, package_name=package_name),
+        encoding="utf-8",
+        newline="\n",
+    )
     (staging / "START-HERE.zh-CN.md").write_text(
-        _start_here_text(package_name, len(index.get("volumes", []))),
+        _start_here_text(package_name, len(index.get("volumes", [])), profile=profile),
         encoding="utf-8",
         newline="\n",
     )
+    if size_budget is not None:
+        (staging / "size-budget.json").write_bytes(handoff.json_bytes(size_budget))
 
     checksum_rows: list[dict[str, object]] = []
     for info in index.get("volumes", []):
@@ -2020,7 +2340,15 @@ def write_package_layout_sidecars(
         }
         (staging / "HANDOFF-INDEX.json").write_bytes(handoff.json_bytes(index))
 
-    for sidecar in ("HANDOFF-INDEX.json", "EXCLUSIONS.txt", "START-HERE.zh-CN.md"):
+    sidecar_names = [
+        "HANDOFF-INDEX.json",
+        "EXCLUSIONS.txt",
+        "PACKAGE-PURPOSE.txt",
+        "START-HERE.zh-CN.md",
+    ]
+    if size_budget is not None:
+        sidecar_names.append("size-budget.json")
+    for sidecar in sidecar_names:
         checksum_rows.append(
             {"file": sidecar, "sha256": handoff.sha256_file(staging / sidecar)}
         )
@@ -2187,6 +2515,19 @@ def create_analysis_package(
         for large_file in large_files:
             for chunk in large_file["chunks"]:
                 chunk["volume"] = volume_by_path[str(chunk["path"])]
+        zip_entry_count = 0
+        for info in volume_infos:
+            volume_path = staging / str(info["file"])
+            with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
+                zip_entry_count += sum(1 for name in archive.namelist() if not name.endswith("/"))
+        size_budget = handoff.build_size_budget(
+            inventory,
+            zip_total_bytes=sum(int(info["compressed_bytes"]) for info in volume_infos),
+        )
+        member_count = build_member_count_semantics(
+            indexed_files=len(indexed_files),
+            zip_file_entries=zip_entry_count,
+        )
         index = {
             "schema": "cpld-agent-analysis-index-v1",
             "run_id": run_id,
@@ -2194,7 +2535,7 @@ def create_analysis_package(
             "package_name": package_name,
             "status": collection.status,
             "profile": profile,
-            "delivery_policy": "code-only" if profile == "code-only" else "inclusion-first",
+            "delivery_policy": handoff.delivery_policy_for_profile(profile),
             "max_zip_bytes": max_zip_bytes,
             "target_zip_bytes": target_zip_bytes,
             "sources": list(collection.sources),
@@ -2203,6 +2544,8 @@ def create_analysis_package(
             "excluded": package_excluded,
             "content_dedup": content_dedup,
             "derived_evidence": derived_evidence,
+            "member_count": member_count,
+            "size_budget": size_budget,
             "volumes": volume_infos,
             "files": indexed_files,
             "large_files": large_files,
@@ -2225,6 +2568,8 @@ def create_analysis_package(
             excluded=package_excluded,
             package_name=package_name,
             include_tar_zst=True,
+            profile=profile,
+            size_budget=size_budget if handoff.uses_unified_layout(profile) else None,
         )
         full_inventory_by_path = {str(item["path"]): item for item in full_inventory}
         _assert_items_unchanged(collection.items, full_inventory_by_path)
@@ -2244,7 +2589,7 @@ def create_analysis_package(
         "status": collection.status,
         "mode": "package",
         "profile": profile,
-        "delivery_policy": "code-only" if profile == "code-only" else "inclusion-first",
+        "delivery_policy": handoff.delivery_policy_for_profile(profile),
         "run_id": run_id,
         "output_dir": str(final_dir),
         "volumes": volume_infos,
@@ -2255,6 +2600,7 @@ def create_analysis_package(
         "excluded_entry_count": len(package_excluded),
         "content_dedup_groups": len(content_dedup),
         "derived_evidence_count": len(derived_evidence),
+        "member_count": member_count,
         "warning_count": len(collection.warnings),
     }
 
@@ -2449,13 +2795,23 @@ def build_parser() -> argparse.ArgumentParser:
     parser.add_argument("--package-name", help="portable package directory and ZIP base name")
     parser.add_argument("--force-overwrite", action="store_true", help="atomically replace an existing package directory")
     parser.add_argument("--no-git-bundle", action="store_true", help="omit the git history bundle from the package")
+    parser.add_argument(
+        "--include-full-history",
+        action="store_true",
+        help="include a full git bundle (archive-local / explicit override; ignored as default for review-compact)",
+    )
+    parser.add_argument(
+        "--include-sanitized-git-snapshot",
+        action="store_true",
+        help="request sanitized synthetic git snapshot hook (P2 extension; records reserved status)",
+    )
     parser.add_argument(
         "--profile",
         choices=sorted(handoff.HANDOFF_PROFILES),
-        default="full",
+        default=handoff.DEFAULT_HANDOFF_PROFILE,
         help=(
-            "inclusion-first full profile packages source+reference+derived board-viewer evidence "
-            "(core/reference split); code-only excludes reference/ and heavy SVG assets"
+            "review-compact (default upload: unified source/evidence/meta, no full git bundle); "
+            "review-debug; archive-local; legacy full (core/reference split) / code-only"
         ),
     )
     parser.add_argument(
@@ -2500,14 +2856,24 @@ def main(argv: list[str] | None = None) -> int:
             seven_zip = find_7z()
             _validate_package_name(package_name)
             output_root = _validate_output_root(args.output_dir, repo_root=source_root, config=config)
+            if args.profile == "archive-local":
+                include_git_bundle = not args.no_git_bundle or args.include_full_history
+                if args.include_full_history:
+                    include_git_bundle = True
+            elif args.profile in {"review-compact", "review-debug"}:
+                include_git_bundle = False
+            else:
+                include_git_bundle = not args.no_git_bundle
             with tempfile.TemporaryDirectory(prefix="ca-") as temporary:
                 temp_root = Path(temporary)
                 collection = collect_analysis_inputs(
                     repo_root=source_root,
                     config=config,
                     temp_root=temp_root / "inputs",
-                    include_git_bundle=not args.no_git_bundle,
+                    include_git_bundle=include_git_bundle,
                     profile=args.profile,
+                    include_sanitized_git_snapshot=args.include_sanitized_git_snapshot,
+                    package_name=package_name,
                 )
                 preparation = prepare_unsupported_archives(
                     collection.items,
@@ -2519,7 +2885,8 @@ def main(argv: list[str] | None = None) -> int:
                 if args.audit_only:
                     payload = audit_analysis_collection(prepared_collection)
                     payload["profile"] = args.profile
-                elif args.profile == "code-only":
+                    payload["delivery_policy"] = handoff.delivery_policy_for_profile(args.profile)
+                elif handoff.uses_unified_layout(args.profile) or args.profile == "code-only":
                     if not prepared_collection.items:
                         raise PackagingError("analysis package has no included files")
                     payload = create_analysis_package(
@@ -2537,7 +2904,7 @@ def main(argv: list[str] | None = None) -> int:
                     )
                     if not core_collection.items and not reference_collection.items:
                         raise PackagingError("analysis package has no included files")
-                    payload: dict[str, object] = {}
+                    payload = {}
                     if core_collection.items:
                         payload["core"] = create_analysis_package(
                             collection=core_collection,

+ 59 - 0
schemas/agent_analysis_handoff_index.schema.json

@@ -139,6 +139,65 @@
         }
       }
     },
+    "member_count": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": [
+        "indexed_files",
+        "zip_file_entries",
+        "self_reference_control_files",
+        "note"
+      ],
+      "properties": {
+        "indexed_files": {
+          "type": "integer",
+          "minimum": 0
+        },
+        "zip_file_entries": {
+          "type": "integer",
+          "minimum": 0
+        },
+        "self_reference_control_files": {
+          "type": "array",
+          "items": {
+            "type": "string"
+          }
+        },
+        "note": {
+          "type": "string"
+        }
+      }
+    },
+    "size_budget": {
+      "type": "object",
+      "additionalProperties": true,
+      "required": [
+        "schema",
+        "members"
+      ],
+      "properties": {
+        "schema": {
+          "type": "string"
+        },
+        "total_bytes_basis": {
+          "type": "integer",
+          "minimum": 0
+        },
+        "threshold_bytes": {
+          "type": "integer",
+          "minimum": 0
+        },
+        "threshold_share": {
+          "type": "number"
+        },
+        "members": {
+          "type": "array",
+          "items": {
+            "type": "object"
+          }
+        }
+      }
+    },
     "max_zip_bytes": {
       "type": "integer",
       "minimum": 1

+ 133 - 0
tests/unit/test_package_for_agent_analysis.py

@@ -1141,5 +1141,138 @@ class PackageForAgentAnalysisTests(unittest.TestCase):
                 )
 
 
+class ReviewCompactProfileSmokeTests(unittest.TestCase):
+    maxDiff = None
+
+    def _init_repo(self, repo: Path) -> str:
+        git = shutil.which("git")
+        if not git:
+            self.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, "receipts/final.json", b'{"status":"pass"}\n')
+        write_file(repo, "reference/original/board/main.brd", b"BOARD")
+        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, ".run_id_stale", b"stale\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), "commit", "-q", "-m", "fixture"], check=True)
+        return git
+
+    def test_review_compact_excludes_heavy_originals_keeps_fixtures(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            write_file(root, "src/core.v", b"module core; endmodule\n")
+            write_file(root, "reference/original/board/main.brd", b"BOARD")
+            write_file(root, "reference/original/schematics/main.pdf", b"%PDF")
+            write_file(root, "tests/board_viewer/fixtures/tiny.dsn", b"fixture-dsn\n")
+            write_file(root, ".run_id_stale", b"stale\n")
+            candidates, excluded, _ = analyzer.scan_analysis_root(root, profile="review-compact")
+            included = {item.relative for item in candidates}
+            self.assertIn("src/core.v", included)
+            self.assertIn("tests/board_viewer/fixtures/tiny.dsn", included)
+            self.assertNotIn("reference/original/board/main.brd", included)
+            self.assertNotIn("reference/original/schematics/main.pdf", included)
+            self.assertNotIn(".run_id_stale", included)
+            rules = {item["path"]: item["rule"] for item in excluded}
+            self.assertEqual(rules.get("reference/original/board"), "reference_original_board")
+
+    def test_review_compact_unified_layout_and_no_git_bundle(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            repo = temp / "repo"
+            self._init_repo(repo)
+            generated = temp / "generated"
+            write_file(generated, "board-data.json", b'{"ok":true}\n')
+            write_file(generated, "build-info.json", b'{"ok":true}\n')
+            write_file(generated, "import-report.json", b'{"ok":true}\n')
+            write_file(generated, "board-copper.svg", b"<svg/>\n")
+            write_file(generated, "board-silkscreen.svg", b"<svg/>\n")
+            write_file(generated, "board-mask-edge.svg", b"<svg/>\n")
+            config = analyzer.HandoffConfig(
+                max_zip_bytes=5_000_000,
+                target_zip_bytes=4_000_000,
+                external_sources=(
+                    analyzer.ExternalSource(
+                        id="board-viewer-generated",
+                        category="hardware",
+                        kind="directory",
+                        path_candidates=(generated,),
+                        archive_policy="copy",
+                    ),
+                ),
+                extra_exclusions=(),
+            )
+            collection = analyzer.collect_analysis_inputs(
+                repo_root=repo,
+                config=config,
+                temp_root=temp / "run",
+                include_git_bundle=True,  # must be forced off for review-compact
+                profile="review-compact",
+                package_name="smoke-review-compact",
+            )
+            paths = {item.candidate.relative for item in collection.items}
+            self.assertTrue(any(path.startswith("source/") for path in paths))
+            self.assertIn("source/src/core.v", paths)
+            self.assertIn("evidence/receipts/final.json", paths)
+            self.assertIn("evidence/board-viewer/board-data.json", 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("reference/original/board" in path for path in paths))
+
+            result = analyzer.create_analysis_package(
+                collection=collection,
+                output_root=temp / "output",
+                package_name="smoke-review-compact",
+                max_zip_bytes=5_000_000,
+                target_zip_bytes=4_000_000,
+                force=False,
+                profile="review-compact",
+            )
+            package_dir = Path(result["output_dir"])
+            self.assertEqual(result["delivery_policy"], "review-compact")
+            self.assertTrue((package_dir / "PACKAGE-PURPOSE.txt").is_file())
+            self.assertTrue((package_dir / "size-budget.json").is_file())
+            index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
+            self.assertEqual(index["profile"], "review-compact")
+            self.assertIn("member_count", index)
+            self.assertIn("self_reference_control_files", index["member_count"])
+            self.assertIn("size_budget", index)
+            volume = package_dir / result["volumes"][0]["file"]
+            with zipfile.ZipFile(volume) as archive:
+                names = set(archive.namelist())
+            self.assertIn("CPLD/source/src/core.v", names)
+            self.assertIn("CPLD/evidence/receipts/final.json", names)
+            self.assertIn("CPLD/meta/git/log-20.txt", names)
+            self.assertIn("CPLD/meta/td-source-closure-binding.json", names)
+            self.assertFalse(any(name.endswith(".bundle") for name in names))
+            index_schema = json.loads(
+                (ROOT / "schemas" / "agent_analysis_handoff_index.schema.json").read_text(
+                    encoding="utf-8"
+                )
+            )
+            jsonschema.validate(index, index_schema)
+
+    def test_review_debug_and_archive_local_profiles_are_registered(self) -> None:
+        analyzer = load_analyzer(self)
+        self.assertIn("review-debug", analyzer.handoff.HANDOFF_PROFILES)
+        self.assertIn("archive-local", analyzer.handoff.HANDOFF_PROFILES)
+        self.assertEqual(analyzer.handoff.DEFAULT_HANDOFF_PROFILE, "review-compact")
+        self.assertTrue(analyzer.handoff.uses_unified_layout("review-debug"))
+        self.assertEqual(
+            analyzer.handoff.delivery_policy_for_profile("archive-local"),
+            "archive-local",
+        )
+
+
 if __name__ == "__main__":
     unittest.main()

+ 17 - 0
tools/package-review-compact.sh

@@ -0,0 +1,17 @@
+#!/usr/bin/env bash
+# Thin entrypoint for the default remote-agent review-compact package.
+set -euo pipefail
+unset LD_LIBRARY_PATH LD_PRELOAD QT_PLUGIN_PATH || true
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+VENV="${PRODU2_VERIFY_VENV:-${XDG_CACHE_HOME:-$HOME/.cache}/prod2u/venvs/verify}"
+PY="${VENV}/bin/python"
+[[ -x "$PY" ]] || PY=python3
+OUT="${PRODU2_HANDOFF_DIR:-${TMPDIR:-/tmp}/prod2u-handoff}"
+NAME="${PRODU2_PACKAGE_NAME:-prod2u-review-compact-$(date -u +%Y%m%dT%H%M%SZ)}"
+mkdir -p "$OUT"
+exec "$PY" -B "$ROOT/package_for_agent_analysis.py" \
+  --profile review-compact \
+  --source-root "$ROOT" \
+  --output-dir "$OUT" \
+  --package-name "$NAME" \
+  "$@"

+ 322 - 6
tools/package_agent_handoff.py

@@ -86,7 +86,11 @@ SECRET_PATTERNS = (
 )
 SAFE_PACKAGE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,119}$")
 TD_BUILD_EVIDENCE_SUFFIXES = {".qor", ".area", ".timing", ".rpt", ".log", ".logw"}
-HANDOFF_PROFILES = frozenset({"full", "code-only"})
+LEGACY_HANDOFF_PROFILES = frozenset({"full", "code-only"})
+REVIEW_PROFILES = frozenset({"review-compact", "review-debug", "archive-local"})
+HANDOFF_PROFILES = LEGACY_HANDOFF_PROFILES | REVIEW_PROFILES
+UNIFIED_LAYOUT_PROFILES = REVIEW_PROFILES
+DEFAULT_HANDOFF_PROFILE = "review-compact"
 CODE_ONLY_ROOT_EXCLUSIONS = {
     "reference": "reference_material",
 }
@@ -97,6 +101,20 @@ CODE_ONLY_GENERATED_VISUAL_ASSETS = frozenset(
         "board-mask-edge.svg",
     }
 )
+BOARD_VIEWER_DERIVED_ASSETS = CODE_ONLY_GENERATED_VISUAL_ASSETS | {
+    "board-data.json",
+    "build-info.json",
+    "import-report.json",
+}
+REVIEW_HEAVY_ORIGINAL_SUFFIXES = {".pdf", ".brd", ".dsn"}
+REVIEW_ORIGINAL_ROOT_EXCLUSIONS = {
+    "reference/original/board": "reference_original_board",
+    "reference/original/schematics": "reference_original_schematics",
+    "reference/original/diagrams": "reference_original_diagrams",
+    "reference/original/local_archives": "reference_original_archives",
+}
+SIZE_BUDGET_MIN_BYTES = 256 * 1024
+SIZE_BUDGET_MIN_SHARE = 0.01
 WINDOWS_RESERVED_NAMES = {
     "con",
     "prn",
@@ -494,6 +512,51 @@ def code_only_exclusion_reason(relative: str, *, is_dir: bool) -> str | None:
     return None
 
 
+def is_board_viewer_fixture_path(relative: str) -> bool:
+    return is_under(relative.casefold(), "tests/board_viewer/fixtures")
+
+
+def is_review_profile(profile: str) -> bool:
+    return profile in REVIEW_PROFILES
+
+
+def uses_unified_layout(profile: str) -> bool:
+    return profile in UNIFIED_LAYOUT_PROFILES
+
+
+def delivery_policy_for_profile(profile: str) -> str:
+    if profile == "code-only":
+        return "code-only"
+    if profile in REVIEW_PROFILES:
+        return profile
+    return "inclusion-first"
+
+
+def review_exclusion_reason(relative: str, *, is_dir: bool, profile: str) -> str | None:
+    """Extra exclusions for review-* / archive-local unified packages."""
+    del profile
+    lower = relative.casefold()
+    name = lower.rsplit("/", 1)[-1]
+    if name.startswith(".run_id"):
+        return "run_id_marker"
+    if name in {"evidence-batch-summary.txt"}:
+        return "stale_run_summary"
+    for prefix, reason in REVIEW_ORIGINAL_ROOT_EXCLUSIONS.items():
+        if is_under(lower, prefix):
+            return reason
+    if is_board_viewer_fixture_path(relative):
+        return None
+    if not is_dir:
+        suffix = Path(name).suffix.casefold()
+        if suffix in REVIEW_HEAVY_ORIGINAL_SUFFIXES:
+            return "heavy_design_original_not_packaged"
+        if name.endswith((".lic",)) or name in {"anlogic.lic"}:
+            return "credential_or_license_file"
+        if "license" in name and suffix in {".zip", ".tgz", ".7z", ".rar", ".txt", ".pdf"}:
+            return "license_material"
+    return None
+
+
 def make_exclusion_resolver(profile: str) -> Callable[..., str | None]:
     if profile not in HANDOFF_PROFILES:
         raise PackagingError(f"unsupported handoff profile: {profile}")
@@ -503,7 +566,12 @@ def make_exclusion_resolver(profile: str) -> Callable[..., str | None]:
             code_only_reason = code_only_exclusion_reason(relative, is_dir=is_dir)
             if code_only_reason:
                 return code_only_reason
-        return exclusion_reason(relative, is_dir=is_dir, context=context)
+        base = exclusion_reason(relative, is_dir=is_dir, context=context)
+        if base:
+            return base
+        if is_review_profile(profile):
+            return review_exclusion_reason(relative, is_dir=is_dir, profile=profile)
+        return None
 
     return resolve
 
@@ -1214,6 +1282,248 @@ def collect_git_provenance(root: Path) -> tuple[dict[str, object], dict[str, byt
     }, artifacts
 
 
+def _git_bytes(git: str, args: list[str], *, cwd: Path) -> bytes | None:
+    code, payload = run_capture([git, *args], cwd=cwd)
+    if code != 0:
+        return None
+    return payload
+
+
+def build_td_source_closure_binding_hook(root: Path) -> dict[str, object]:
+    """Record TD source-closure binding hooks without requiring a live bitstream."""
+    manifest = root / "src" / "generated" / "td-source-manifest.json"
+    project = root / "projects" / "prod2u-door-temp" / "project.json"
+    binding: dict[str, object] = {
+        "schema": "cpld-td-source-closure-binding-hook-v1",
+        "status": "hook_ready",
+        "note": (
+            "Bindings are recorded for remote review; recompute against an existing "
+            "bitstream receipt when production inputs are unchanged. Full TD rebuild "
+            "is out of scope for review-compact packaging."
+        ),
+        "td_source_manifest_path": "src/generated/td-source-manifest.json",
+        "td_source_manifest_sha256": None,
+        "project_config_path": "projects/prod2u-door-temp/project.json",
+        "project_config_sha256": None,
+        "bitstream_binding": "deferred_to_evidence_receipt",
+    }
+    if manifest.is_file():
+        binding["td_source_manifest_sha256"] = sha256_file(manifest)
+    else:
+        binding["status"] = "hook_partial"
+        binding["td_source_manifest_sha256"] = None
+    if project.is_file():
+        binding["project_config_sha256"] = sha256_file(project)
+    return binding
+
+
+def collect_review_git_provenance(
+    root: Path,
+    *,
+    include_sanitized_git_snapshot: bool = False,
+    meta_prefix: str = "meta/git",
+) -> 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)
+    artifacts: dict[str, bytes] = {}
+    if git_dir is None:
+        metadata: dict[str, object] = {
+            "status": "not_a_git_worktree",
+            "branch": None,
+            "head": None,
+            "tool": None,
+            "full_bundle": False,
+            "sanitized_git_snapshot": {
+                "requested": include_sanitized_git_snapshot,
+                "status": "not_applicable",
+            },
+        }
+        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,
+            "tool": None,
+            "full_bundle": False,
+            "sanitized_git_snapshot": {
+                "requested": include_sanitized_git_snapshot,
+                "status": "blocked_missing_git_tool",
+            },
+        }, artifacts
+
+    status_payload = _git_bytes(
+        git,
+        [
+            "--no-optional-locks",
+            "-c",
+            "core.fsmonitor=false",
+            "-c",
+            "core.untrackedCache=false",
+            "status",
+            "--short",
+            "--branch",
+            "--untracked-files=all",
+        ],
+        cwd=root,
+    )
+    log_payload = _git_bytes(
+        git,
+        ["log", "-20", "--format=%H %ad %s", "--date=iso-strict"],
+        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] = {}
+    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")
+            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"]))
+
+    artifacts[f"{meta_prefix}/HEAD.txt"] = f"{head or ''}\n".encode("utf-8")
+    if branch:
+        artifacts[f"{meta_prefix}/branch.txt"] = f"{branch}\n".encode("utf-8")
+    if status_payload is not None:
+        artifacts[f"{meta_prefix}/status.txt"] = status_payload
+    if log_payload is not None:
+        artifacts[f"{meta_prefix}/log-20.txt"] = log_payload
+    artifacts[f"{meta_prefix}/tree-manifest.json"] = json_bytes(
+        {
+            "schema": "cpld-review-git-tree-manifest-v1",
+            "head": head,
+            "file_count": len(tree_rows),
+            "files": tree_rows,
+        }
+    )
+    artifacts[f"{meta_prefix}/file-sha256.json"] = json_bytes(
+        {
+            "schema": "cpld-review-git-file-sha256-v1",
+            "head": head,
+            "files": file_hashes,
+        }
+    )
+
+    snapshot_status = {
+        "requested": include_sanitized_git_snapshot,
+        "status": (
+            "reserved_for_p2"
+            if include_sanitized_git_snapshot
+            else "not_requested"
+        ),
+        "note": (
+            "Optional sanitized synthetic single-commit snapshot is a P2 extension. "
+            "When implemented it must record synthetic→original commit mapping and "
+            "must not impersonate the original tip."
+        ),
+    }
+    artifacts[f"{meta_prefix}/sanitized-snapshot-status.json"] = json_bytes(snapshot_status)
+
+    capture_status = "pass"
+    if status_payload is None or log_payload is None or ls_files is None:
+        capture_status = "partial"
+    return {
+        "status": capture_status,
+        "branch": branch,
+        "head": head,
+        "tool": "git",
+        "full_bundle": False,
+        "status_captured": status_payload is not None,
+        "log20_captured": log_payload is not None,
+        "tree_manifest_files": len(tree_rows),
+        "sanitized_git_snapshot": snapshot_status,
+    }, artifacts
+
+
+def build_size_budget(
+    inventory: list[dict[str, object]],
+    *,
+    zip_total_bytes: int | None = None,
+) -> dict[str, object]:
+    """Members ≥256KiB or >1% of ZIP (when known) enter the size-budget table."""
+    total = int(zip_total_bytes) if zip_total_bytes is not None else sum(
+        int(item.get("size", 0)) for item in inventory
+    )
+    rows: list[dict[str, object]] = []
+    for item in inventory:
+        size = int(item.get("size", 0))
+        share = (size / total) if total > 0 else 0.0
+        if size >= SIZE_BUDGET_MIN_BYTES or share > SIZE_BUDGET_MIN_SHARE:
+            rows.append(
+                {
+                    "path": str(item.get("path", "")),
+                    "size": size,
+                    "share_of_total": round(share, 6),
+                    "reason": (
+                        "gte_256kiB"
+                        if size >= SIZE_BUDGET_MIN_BYTES
+                        else "gt_1pct_of_package"
+                    ),
+                }
+            )
+    rows.sort(key=lambda row: (-int(row["size"]), str(row["path"]).casefold()))
+    return {
+        "schema": "cpld-review-size-budget-v1",
+        "total_bytes_basis": total,
+        "threshold_bytes": SIZE_BUDGET_MIN_BYTES,
+        "threshold_share": SIZE_BUDGET_MIN_SHARE,
+        "members": rows,
+    }
+
+
+def package_purpose_text(profile: str, *, package_name: str) -> str:
+    lines = [
+        f"PACKAGE-PURPOSE: {package_name}",
+        f"profile: {profile}",
+        f"delivery_policy: {delivery_policy_for_profile(profile)}",
+        "",
+    ]
+    if profile == "review-compact":
+        lines.extend(
+            [
+                "Default remote-agent upload package.",
+                "Layout: source/ (active code+tests) + evidence/ (receipts, derived board-viewer) + meta/.",
+                "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.",
+                "Hardware validation remains not_run unless a future task authorizes it.",
+            ]
+        )
+    elif profile == "review-debug":
+        lines.extend(
+            [
+                "Debug-oriented review package (unified layout).",
+                "Same heavy-original exclusions as review-compact; may carry additional debug evidence.",
+                "Still omits full Git history bundles by default.",
+            ]
+        )
+    elif profile == "archive-local":
+        lines.extend(
+            [
+                "Local archival package (not the default upload).",
+                "May include a full Git bundle / --include-full-history for offline restore.",
+                "Still uses unified source/evidence/meta layout.",
+            ]
+        )
+    else:
+        lines.append("Legacy inclusion-first or code-only analysis handoff.")
+    lines.append("")
+    return "\n".join(lines)
+
+
 def build_metadata(
     *,
     package_name: str,
@@ -1263,13 +1573,19 @@ def build_metadata(
             "and declared reconstructable runtime outputs."
         )
         derived_evidence = []
+    elif is_review_profile(profile):
+        authority_boundary = (
+            "Unified review package (source/evidence/meta). Keeps board-viewer derived assets and "
+            "small test fixtures; excludes PDF/BRD/DSN originals, vendor installers, license material, "
+            "caches, venvs, node_modules, and full Git bundles unless archive-local/--include-full-history."
+        )
     manifest = {
         "schema": "cpld-agent-handoff-v1",
         "status": "pass",
         "created_at": utc_now(),
         "package_name": package_name,
         "profile": profile,
-        "delivery_policy": "code-only" if profile == "code-only" else "inclusion-first",
+        "delivery_policy": delivery_policy_for_profile(profile),
         "archive_root": ARCHIVE_ROOT,
         "source_name": ARCHIVE_ROOT,
         "included_file_count": len(inventory),
@@ -1892,10 +2208,10 @@ def build_parser() -> argparse.ArgumentParser:
     parser.add_argument(
         "--profile",
         choices=sorted(HANDOFF_PROFILES),
-        default="full",
+        default=DEFAULT_HANDOFF_PROFILE,
         help=(
-            "inclusion-first full profile includes reference + derived board-viewer JSON/SVG; "
-            "code-only excludes reference/ and heavy board-viewer SVG assets"
+            "review-compact (default upload, unified source/evidence/meta, no full git bundle); "
+            "review-debug; archive-local; legacy full/code-only"
         ),
     )
     parser.add_argument(