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

Merge commit '2f8be43f0373cde49c798d8e3da4240c30368e87' into integrate/linux-continue-20260804T155114Z

root 3 месяцев назад
Родитель
Сommit
fade3d0d87

+ 317 - 18
package_for_agent_analysis.py

@@ -32,7 +32,23 @@ import package_agent_handoff as handoff  # noqa: E402
 PackagingError = handoff.PackagingError
 CONFIG_SCHEMA = "cpld-agent-analysis-sources-v1"
 DEFAULT_CONFIG = ROOT / "config" / "agent_analysis_handoff_sources.json"
-DEFAULT_OUTPUT_DIR = Path.home() / "Downloads" / "CPLD-agent-analysis"
+DEFAULT_OUTPUT_DIR = Path(
+    os.environ.get(
+        "PRODU2_HANDOFF_DIR",
+        str(Path(os.environ.get("TMPDIR", "/tmp")) / "prod2u-handoff"),
+    )
+)
+CONTENT_DEDUP_MIN_BYTES = 4096
+DERIVED_BOARD_VIEWER_ASSETS = frozenset(
+    {
+        "board-copper.svg",
+        "board-silkscreen.svg",
+        "board-mask-edge.svg",
+        "board-data.json",
+        "build-info.json",
+        "import-report.json",
+    }
+)
 CATEGORY_ORDER = {
     "core": 0,
     "hardware": 1,
@@ -272,10 +288,12 @@ def _source_snapshot(
     *,
     source_id: str,
     extra_exclusions: tuple[dict[str, str], ...],
+    profile: str = "full",
 ) -> SourceSnapshot:
     candidates, excluded, _ = scan_analysis_root(
         root,
         extra_exclusions=extra_exclusions,
+        profile=profile,
     )
     return SourceSnapshot(
         source_id=source_id,
@@ -418,6 +436,7 @@ def analysis_exclusion_reason(
     is_dir: bool,
     context: handoff.ScanContext,
     extra_exclusions: tuple[dict[str, str], ...] = (),
+    profile: str = "full",
 ) -> str | None:
     del context
     lower = relative.casefold()
@@ -427,6 +446,13 @@ def analysis_exclusion_reason(
     secret_reason = handoff.secret_path_reason(relative, is_dir=is_dir)
     if secret_reason:
         return secret_reason
+    if profile == "code-only":
+        for prefix, reason in handoff.CODE_ONLY_ROOT_EXCLUSIONS.items():
+            if handoff.is_under(lower, prefix):
+                return 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"
     for item in extra_exclusions:
         prefix = str(item.get("path", "")).casefold().strip("/")
         if prefix and handoff.is_under(lower, prefix):
@@ -445,8 +471,10 @@ def analysis_exclusion_reason(
         "reference/historical": "reference_historical_material",
         "reference/original/legacy_rtl": "reference_legacy_rtl",
         "receipts/local": "local_runtime_receipt",
-        "tools/board-viewer/generated": "generated_board_viewer_output",
+        # Packaged once via external source board-viewer-generated (derived evidence).
+        "tools/board-viewer/generated": "board_viewer_generated_packaged_via_external_source",
         "anlogic_cd": "vendor_installer_payload",
+        "node_modules": "node_modules_runtime",
     }
     for prefix, reason in explicit_roots.items():
         if handoff.is_under(lower, prefix):
@@ -499,12 +527,16 @@ def analysis_exclusion_reason(
         "htmlcov": "coverage_report",
         "build": "build_output",
         "runs": "run_state_directory",
+        "node_modules": "node_modules_runtime",
+        ".playwright-browsers": "browser_runtime_cache",
     }
     for component in parts:
         if component in cache_components:
             return cache_components[component]
         if component == "dist":
             return "generated_delivery_output"
+        if component.endswith(".egg-info"):
+            return "python_package_metadata"
 
     if not is_dir:
         suffix = Path(name).suffix.casefold()
@@ -539,6 +571,7 @@ def scan_analysis_root(
     root: Path,
     *,
     extra_exclusions: tuple[dict[str, str], ...] = (),
+    profile: str = "full",
 ) -> tuple[list[handoff.Candidate], list[dict[str, str]], handoff.ScanContext]:
     def resolve(relative: str, *, is_dir: bool, context: handoff.ScanContext) -> str | None:
         return analysis_exclusion_reason(
@@ -546,9 +579,10 @@ def scan_analysis_root(
             is_dir=is_dir,
             context=context,
             extra_exclusions=extra_exclusions,
+            profile=profile,
         )
 
-    return handoff.scan_tree(root, exclusion_resolver=resolve)
+    return handoff.scan_tree(root, exclusion_resolver=resolve, profile=profile)
 
 
 def resolve_external_sources(
@@ -650,8 +684,13 @@ def _collect_directory_items(
     category: str,
     prefix: str,
     extra_exclusions: tuple[dict[str, str], ...],
+    profile: str = "full",
 ) -> tuple[list[PackageItem], list[dict[str, str]]]:
-    candidates, excluded, _ = scan_analysis_root(root, extra_exclusions=extra_exclusions)
+    candidates, excluded, _ = scan_analysis_root(
+        root,
+        extra_exclusions=extra_exclusions,
+        profile=profile,
+    )
     items = [
         PackageItem(
             candidate=_rebase_candidate(candidate, prefix),
@@ -748,6 +787,7 @@ def collect_analysis_inputs(
     config: HandoffConfig,
     temp_root: Path,
     include_git_bundle: bool = True,
+    profile: str = "full",
 ) -> AnalysisCollection:
     root = repo_root.resolve(strict=True)
     temp_root.mkdir(parents=True, exist_ok=True)
@@ -764,6 +804,7 @@ def collect_analysis_inputs(
         category="core",
         prefix="workspace-current",
         extra_exclusions=config.extra_exclusions,
+        profile=profile,
     )
     items.extend(root_items)
     excluded.extend(root_excluded)
@@ -772,6 +813,7 @@ def collect_analysis_inputs(
             root,
             source_id="workspace-current",
             extra_exclusions=config.extra_exclusions,
+            profile=profile,
         )
     )
     sources.append(
@@ -793,6 +835,10 @@ def collect_analysis_inputs(
         git_metadata.append(bundle_metadata)
 
     resolved_sources, source_warnings = resolve_external_sources(config.external_sources)
+    if profile == "code-only":
+        resolved_sources = [
+            source for source in resolved_sources if source.id != "board-viewer-generated"
+        ]
     warnings.extend(source_warnings)
     for source in resolved_sources:
         prefix = f"external/{source.id}"
@@ -814,6 +860,7 @@ def collect_analysis_inputs(
                 category=source.category,
                 prefix=prefix,
                 extra_exclusions=config.extra_exclusions,
+                profile=profile,
             )
             items.extend(source_items)
             excluded.extend(source_excluded)
@@ -822,6 +869,7 @@ def collect_analysis_inputs(
                     source.path,
                     source_id=source.id,
                     extra_exclusions=config.extra_exclusions,
+                    profile=profile,
                 )
             )
         sources.append(
@@ -1228,6 +1276,177 @@ def _item_sort_key(item: PackageItem) -> tuple[int, str, str]:
     )
 
 
+def _path_basename(relative: str) -> str:
+    return relative.casefold().rsplit("/", 1)[-1]
+
+
+def _is_board_viewer_generated_path(relative: str) -> bool:
+    lower = relative.casefold()
+    return (
+        "board-viewer-generated" in lower
+        or "/tools/board-viewer/generated/" in f"/{lower}/"
+        or lower.startswith("tools/board-viewer/generated/")
+    )
+
+
+def _is_reference_original_path(relative: str) -> bool:
+    lower = f"/{relative.casefold()}/"
+    return "/reference/original/" in lower or lower.startswith("/reference/original/")
+
+
+def _dedup_canonical_path(paths: list[str]) -> str:
+    def rank(path: str) -> tuple[int, int, str]:
+        name = _path_basename(path)
+        in_reference = _is_reference_original_path(path)
+        in_generated = _is_board_viewer_generated_path(path)
+        if name in BOARD_VIEWER_GENERATED_ASSETS or name in DERIVED_BOARD_VIEWER_ASSETS:
+            return (0 if in_generated else 1, 0 if in_reference else 1, path.casefold())
+        if name.endswith((".brd", ".pdf", ".dsn", ".sch")):
+            return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
+        return (0 if in_reference else 1, 0 if in_generated else 1, path.casefold())
+
+    return sorted(paths, key=rank)[0]
+
+
+def _should_content_dedup(size: int, relative: str) -> bool:
+    name = _path_basename(relative)
+    if name in DERIVED_BOARD_VIEWER_ASSETS or name.endswith((".brd", ".pdf")):
+        return True
+    return size >= CONTENT_DEDUP_MIN_BYTES
+
+
+def apply_content_dedup(
+    items: tuple[PackageItem, ...],
+    inventory: list[dict[str, object]],
+) -> tuple[tuple[PackageItem, ...], list[dict[str, object]], list[dict[str, str]]]:
+    """Keep one physical copy per identical content hash; record logical aliases."""
+    by_path = {str(row["path"]): row for row in inventory}
+    groups: dict[str, list[PackageItem]] = {}
+    for item in items:
+        row = by_path[item.candidate.relative]
+        sha = str(row["sha256"])
+        size = int(row["size"])
+        if not _should_content_dedup(size, item.candidate.relative):
+            continue
+        groups.setdefault(sha, []).append(item)
+
+    drop_paths: set[str] = set()
+    dedup_records: list[dict[str, object]] = []
+    excluded: list[dict[str, str]] = []
+    for sha, group in sorted(groups.items(), key=lambda pair: pair[0]):
+        if len(group) < 2:
+            continue
+        paths = [item.candidate.relative for item in group]
+        canonical = _dedup_canonical_path(paths)
+        aliases = sorted(path for path in paths if path != canonical)
+        if not aliases:
+            continue
+        size = int(by_path[canonical]["size"])
+        dedup_records.append(
+            {
+                "sha256": sha,
+                "size": size,
+                "physical_path": canonical,
+                "logical_paths": aliases,
+                "reason": "identical_content_single_physical_copy",
+            }
+        )
+        for alias in aliases:
+            drop_paths.add(alias)
+            excluded.append(
+                {
+                    "path": alias,
+                    "rule": "duplicate_content_logical_alias",
+                }
+            )
+
+    physical_items = tuple(
+        item for item in items if item.candidate.relative not in drop_paths
+    )
+    dedup_records.sort(key=lambda row: str(row["physical_path"]).casefold())
+    excluded.sort(key=lambda row: handoff.windows_collision_key(row["path"]))
+    return physical_items, dedup_records, excluded
+
+
+def classify_derived_evidence(items: tuple[PackageItem, ...]) -> list[dict[str, object]]:
+    derived: list[dict[str, object]] = []
+    for item in items:
+        name = _path_basename(item.candidate.relative)
+        if name not in DERIVED_BOARD_VIEWER_ASSETS:
+            continue
+        if not _is_board_viewer_generated_path(item.candidate.relative):
+            continue
+        role = "derived_from_brd_visual" if name in BOARD_VIEWER_GENERATED_ASSETS else "derived_from_brd_parsed"
+        derived.append(
+            {
+                "path": item.candidate.relative,
+                "asset": name,
+                "role": role,
+                "authority": "analysis_evidence_not_source_closure",
+                "note": "Derived from the original Allegro BRD for remote analysis; not RTL/TD source closure.",
+            }
+        )
+    derived.sort(key=lambda row: str(row["path"]).casefold())
+    return derived
+
+
+def replay_analysis_package(package_dir: Path, *, extract_root: Path) -> dict[str, object]:
+    """Extract a published package and verify SHA256SUMS plus inventory hashes."""
+    package_dir = package_dir.expanduser().resolve(strict=True)
+    extract_root = extract_root.expanduser().resolve(strict=False)
+    if extract_root.exists():
+        raise PackagingError(f"replay extract root already exists: {extract_root}")
+    index_path = package_dir / "HANDOFF-INDEX.json"
+    sums_path = package_dir / "SHA256SUMS.txt"
+    if not index_path.is_file() or not sums_path.is_file():
+        raise PackagingError("package directory is missing HANDOFF-INDEX.json or SHA256SUMS.txt")
+    index = json.loads(index_path.read_text(encoding="utf-8"))
+    extract_root.mkdir(parents=True, exist_ok=False)
+    verified_volumes: list[dict[str, object]] = []
+    for line in sums_path.read_text(encoding="ascii").splitlines():
+        line = line.strip()
+        if not line:
+            continue
+        digest, _, name = line.partition("  ")
+        if not digest or not name:
+            raise PackagingError(f"invalid SHA256SUMS line: {line}")
+        volume_path = package_dir / name
+        actual = handoff.sha256_file(volume_path)
+        if actual != digest:
+            raise PackagingError(f"SHA256SUMS mismatch for {name}")
+        with zipfile.ZipFile(volume_path, "r", allowZip64=True) as archive:
+            archive.extractall(extract_root)
+        verified_volumes.append({"file": name, "sha256": actual})
+    checked_files = 0
+    for item in index.get("files", []):
+        relative = str(item["path"])
+        target = extract_root / "CPLD" / Path(*relative.split("/"))
+        if not target.is_file():
+            raise PackagingError(f"replay missing extracted file: {relative}")
+        digest = handoff.sha256_file(target)
+        if digest != item["sha256"] or target.stat().st_size != int(item["size"]):
+            raise PackagingError(f"replay hash mismatch for {relative}")
+        checked_files += 1
+    for record in index.get("content_dedup", []):
+        physical = extract_root / "CPLD" / Path(*str(record["physical_path"]).split("/"))
+        if not physical.is_file():
+            raise PackagingError(f"replay missing dedup physical file: {record['physical_path']}")
+        for alias in record.get("logical_paths", []):
+            alias_path = extract_root / "CPLD" / Path(*str(alias).split("/"))
+            if alias_path.exists():
+                raise PackagingError(f"replay found duplicated physical alias path: {alias}")
+    return {
+        "status": "pass",
+        "mode": "package_replay",
+        "package_dir": str(package_dir),
+        "extract_root": str(extract_root),
+        "volumes": verified_volumes,
+        "checked_files": checked_files,
+        "content_dedup_groups": len(index.get("content_dedup", [])),
+        "derived_evidence_count": len(index.get("derived_evidence", [])),
+    }
+
+
 def _audit_one_item(item: PackageItem) -> dict[str, object]:
     if item.scan_archive:
         file_inventory = handoff.stream_candidate(item.candidate)
@@ -1377,7 +1596,11 @@ def _write_volume(
     written_inventory: list[dict[str, object]] = []
     try:
         with zipfile.ZipFile(
-            path, "w", compression=zipfile.ZIP_DEFLATED, allowZip64=True
+            path,
+            "w",
+            compression=zipfile.ZIP_DEFLATED,
+            compresslevel=9,
+            allowZip64=True,
         ) as archive:
             for item in sorted(items, key=_item_sort_key):
                 expected = inventory_by_path[item.candidate.relative]
@@ -1611,12 +1834,13 @@ def _assert_items_unchanged(
             raise PackagingError(f"source changed during analysis packaging: {item.candidate.relative}")
 
 
-def _assert_source_trees_unchanged(collection: AnalysisCollection) -> None:
+def _assert_source_trees_unchanged(collection: AnalysisCollection, *, profile: str = "full") -> None:
     for snapshot in collection.source_snapshots:
         current = _source_snapshot(
             snapshot.root,
             source_id=snapshot.source_id,
             extra_exclusions=snapshot.extra_exclusions,
+            profile=profile,
         )
         if (
             current.candidates != snapshot.candidates
@@ -1630,7 +1854,9 @@ def _start_here_text(package_name: str, volume_count: int) -> str:
         f"# {package_name} 分析交付包\n\n"
         f"本目录包含 {volume_count} 个互相独立的普通 ZIP。请先核对 `SHA256SUMS.txt`,"
         "再把所有 ZIP 解压到同一个目录。\n\n"
-        "`HANDOFF-INDEX.json` 记录每个原始文件的来源、目标卷、大小和 SHA-256。\n"
+        "`HANDOFF-INDEX.json` 记录每个原始文件的来源、目标卷、大小和 SHA-256,"
+        "以及 `excluded`(排除原因)、`derived_evidence`(由原始 BRD 派生的 board-viewer JSON/SVG,"
+        "不是 RTL/TD source closure)和 `content_dedup`(相同大文件只保留一份物理副本时的逻辑归属)。\n"
     )
 
 
@@ -1679,6 +1905,7 @@ def create_analysis_package(
     max_zip_bytes: int,
     target_zip_bytes: int,
     force: bool,
+    profile: str = "full",
 ) -> dict[str, object]:
     _validate_package_name(package_name)
     if max_zip_bytes <= 0 or not 0 < target_zip_bytes < max_zip_bytes:
@@ -1694,9 +1921,21 @@ def create_analysis_package(
     run_id = uuid.uuid4().hex
     staging = Path(tempfile.mkdtemp(prefix=f".{package_name}.{run_id}.", dir=output_root))
     try:
-        inventory = _audit_package_items(collection.items)
+        full_inventory = _audit_package_items(collection.items)
+        physical_items, content_dedup, dedup_excluded = apply_content_dedup(
+            collection.items,
+            full_inventory,
+        )
+        inventory = [
+            row
+            for row in full_inventory
+            if str(row["path"]) in {item.candidate.relative for item in physical_items}
+        ]
         inventory_by_path = {str(item["path"]): item for item in inventory}
-        package_items = collection.items
+        package_excluded = list(collection.excluded) + dedup_excluded
+        package_excluded.sort(key=lambda item: handoff.windows_collision_key(item["path"]))
+        derived_evidence = classify_derived_evidence(physical_items)
+        package_items = physical_items
         package_inventory = inventory
         package_inventory_by_path = inventory_by_path
         large_files: list[dict[str, object]] = []
@@ -1708,19 +1947,19 @@ def create_analysis_package(
             package_name=package_name,
             number=1,
             count=1,
-            items=list(sorted(collection.items, key=_item_sort_key)),
+            items=list(sorted(physical_items, key=_item_sort_key)),
             inventory_by_path=inventory_by_path,
         )
         if single_path.stat().st_size < max_zip_bytes:
             volume_infos = [single_info]
-            groups = [list(sorted(collection.items, key=_item_sort_key))]
+            groups = [list(sorted(physical_items, key=_item_sort_key))]
         else:
             single_path.unlink()
             package_items, large_files, chunk_root = _prepare_large_file_chunks(
                 staging,
                 run_id=run_id,
                 package_name=package_name,
-                items=collection.items,
+                items=physical_items,
                 inventory_by_path=inventory_by_path,
                 target_zip_bytes=target_zip_bytes,
                 max_zip_bytes=max_zip_bytes,
@@ -1780,12 +2019,16 @@ def create_analysis_package(
             "created_at_utc": _utc_now(),
             "package_name": package_name,
             "status": collection.status,
+            "profile": profile,
+            "delivery_policy": "code-only" if profile == "code-only" else "inclusion-first",
             "max_zip_bytes": max_zip_bytes,
             "target_zip_bytes": target_zip_bytes,
             "sources": list(collection.sources),
             "git": list(collection.git),
             "warnings": list(collection.warnings),
-            "excluded": list(collection.excluded),
+            "excluded": package_excluded,
+            "content_dedup": content_dedup,
+            "derived_evidence": derived_evidence,
             "volumes": volume_infos,
             "files": indexed_files,
             "large_files": large_files,
@@ -1815,8 +2058,9 @@ def create_analysis_package(
                 raise PackagingError(f"ZIP volume exceeds strict size limit: {volume_path.name}")
             if handoff.sha256_file(volume_path) != info["sha256"]:
                 raise PackagingError(f"ZIP volume hash changed after verification: {volume_path.name}")
-        _assert_items_unchanged(collection.items, inventory_by_path)
-        _assert_source_trees_unchanged(collection)
+        full_inventory_by_path = {str(item["path"]): item for item in full_inventory}
+        _assert_items_unchanged(collection.items, full_inventory_by_path)
+        _assert_source_trees_unchanged(collection, profile=profile)
         if chunk_root is not None:
             shutil.rmtree(chunk_root)
         _publish_directory_atomically(staging, final_dir, force=force)
@@ -1827,12 +2071,16 @@ def create_analysis_package(
     return {
         "status": collection.status,
         "mode": "package",
+        "profile": profile,
+        "delivery_policy": "code-only" if profile == "code-only" else "inclusion-first",
         "run_id": run_id,
         "output_dir": str(final_dir),
         "volumes": volume_infos,
         "included_file_count": len(inventory),
         "included_bytes": sum(int(item["size"]) for item in inventory),
-        "excluded_entry_count": len(collection.excluded),
+        "excluded_entry_count": len(package_excluded),
+        "content_dedup_groups": len(content_dedup),
+        "derived_evidence_count": len(derived_evidence),
         "warning_count": len(collection.warnings),
     }
 
@@ -1922,6 +2170,7 @@ def explain_analysis_path(
     *,
     repo_root: Path,
     config: HandoffConfig,
+    profile: str = "full",
 ) -> dict[str, object]:
     root = repo_root.resolve(strict=True)
     requested = path if path.is_absolute() else root / path
@@ -1957,6 +2206,7 @@ def explain_analysis_path(
         is_dir=is_dir,
         context=context,
         extra_exclusions=config.extra_exclusions,
+        profile=profile,
     )
     archive_relative = (
         f"workspace-current/{relative}"
@@ -2025,6 +2275,26 @@ 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(
+        "--profile",
+        choices=sorted(handoff.HANDOFF_PROFILES),
+        default="full",
+        help=(
+            "inclusion-first full profile packages source+reference+derived board-viewer evidence "
+            "(core/reference split); code-only excludes reference/ and heavy SVG assets"
+        ),
+    )
+    parser.add_argument(
+        "--replay-package",
+        type=Path,
+        metavar="DIR",
+        help="verify SHA256SUMS and replay-extract an existing package directory (selftest)",
+    )
+    parser.add_argument(
+        "--replay-extract-dir",
+        type=Path,
+        help="extract target for --replay-package (must not already exist)",
+    )
     return parser
 
 
@@ -2033,11 +2303,25 @@ def main(argv: list[str] | None = None) -> int:
     package_name = args.package_name or datetime.now(timezone.utc).strftime(
         "cpld-agent-analysis-%Y%m%dT%H%M%SZ"
     )
-    source_root = args.source_root.expanduser().resolve(strict=True)
     try:
+        if args.replay_package is not None:
+            extract_root = args.replay_extract_dir or Path(
+                tempfile.mkdtemp(prefix="prod2u-package-replay-", dir=os.environ.get("TMPDIR", "/tmp"))
+            )
+            payload = replay_analysis_package(args.replay_package, extract_root=extract_root)
+            print(json.dumps(payload, ensure_ascii=False, indent=2))
+            return 0
+        source_root = args.source_root.expanduser().resolve(strict=True)
+        if args.profile not in handoff.HANDOFF_PROFILES:
+            raise PackagingError(f"unsupported handoff profile: {args.profile}")
         config = load_config(args.config, repo_root=source_root)
         if args.explain is not None:
-            payload = explain_analysis_path(args.explain, repo_root=source_root, config=config)
+            payload = explain_analysis_path(
+                args.explain,
+                repo_root=source_root,
+                config=config,
+                profile=args.profile,
+            )
         else:
             seven_zip = find_7z()
             _validate_package_name(package_name)
@@ -2049,6 +2333,7 @@ def main(argv: list[str] | None = None) -> int:
                     config=config,
                     temp_root=temp_root / "inputs",
                     include_git_bundle=not args.no_git_bundle,
+                    profile=args.profile,
                 )
                 preparation = prepare_unsupported_archives(
                     collection.items,
@@ -2059,6 +2344,19 @@ def main(argv: list[str] | None = None) -> int:
                 prepared_collection = merge_archive_preparation(collection, preparation)
                 if args.audit_only:
                     payload = audit_analysis_collection(prepared_collection)
+                    payload["profile"] = args.profile
+                elif args.profile == "code-only":
+                    if not prepared_collection.items:
+                        raise PackagingError("analysis package has no included files")
+                    payload = create_analysis_package(
+                        collection=prepared_collection,
+                        output_root=output_root,
+                        package_name=package_name,
+                        max_zip_bytes=config.max_zip_bytes,
+                        target_zip_bytes=config.target_zip_bytes,
+                        force=args.force_overwrite,
+                        profile=args.profile,
+                    )
                 else:
                     core_collection, reference_collection = _split_collection_by_reference(
                         prepared_collection
@@ -2074,6 +2372,7 @@ def main(argv: list[str] | None = None) -> int:
                             max_zip_bytes=config.max_zip_bytes,
                             target_zip_bytes=config.target_zip_bytes,
                             force=args.force_overwrite,
+                            profile=args.profile,
                         )
                     if reference_collection.items:
                         payload["reference"] = _create_reference_package_with_cache(

+ 72 - 0
schemas/agent_analysis_handoff_index.schema.json

@@ -42,6 +42,78 @@
         "pass_with_warnings"
       ]
     },
+    "profile": {
+      "type": "string"
+    },
+    "delivery_policy": {
+      "type": "string"
+    },
+    "content_dedup": {
+      "type": "array",
+      "items": {
+        "type": "object",
+        "additionalProperties": false,
+        "required": [
+          "sha256",
+          "size",
+          "physical_path",
+          "logical_paths",
+          "reason"
+        ],
+        "properties": {
+          "sha256": {
+            "$ref": "#/$defs/sha256"
+          },
+          "size": {
+            "type": "integer",
+            "minimum": 0
+          },
+          "physical_path": {
+            "type": "string"
+          },
+          "logical_paths": {
+            "type": "array",
+            "items": {
+              "type": "string"
+            }
+          },
+          "reason": {
+            "type": "string"
+          }
+        }
+      }
+    },
+    "derived_evidence": {
+      "type": "array",
+      "items": {
+        "type": "object",
+        "additionalProperties": false,
+        "required": [
+          "path",
+          "asset",
+          "role",
+          "authority",
+          "note"
+        ],
+        "properties": {
+          "path": {
+            "type": "string"
+          },
+          "asset": {
+            "type": "string"
+          },
+          "role": {
+            "type": "string"
+          },
+          "authority": {
+            "type": "string"
+          },
+          "note": {
+            "type": "string"
+          }
+        }
+      }
+    },
     "max_zip_bytes": {
       "type": "integer",
       "minimum": 1

+ 147 - 14
tools/bootstrap_oss_cad_suite.py

@@ -11,6 +11,7 @@ from __future__ import annotations
 import argparse
 import hashlib
 import json
+import os
 import shutil
 import sys
 import urllib.request
@@ -20,7 +21,13 @@ from pathlib import Path
 from typing import Any
 
 
-DEFAULT_TOOLCHAIN_BASE = Path.home() / "CodexToolchains" / "CPLD"
+def _default_toolchain_base() -> Path:
+    if sys.platform.startswith("linux"):
+        return Path.home() / ".cache" / "prod2u"
+    return Path.home() / "CodexToolchains" / "CPLD"
+
+
+DEFAULT_TOOLCHAIN_BASE = _default_toolchain_base()
 DEFAULT_ROOT = DEFAULT_TOOLCHAIN_BASE / "oss-cad-suite" / "latest"
 DEFAULT_DOWNLOAD_DIR = DEFAULT_TOOLCHAIN_BASE / "downloads"
 DEFAULT_COCOTB_VENV = (
@@ -39,12 +46,18 @@ LATEST_API_URL = "https://api.github.com/repos/YosysHQ/oss-cad-suite-build/relea
 REQUIRED_TOOLS = ["iverilog", "vvp", "verilator", "yosys", "sby"]
 
 
+def _verilator_candidates(bin_dir: Path) -> tuple[Path, ...]:
+    if sys.platform.startswith("linux"):
+        return (bin_dir / "verilator_bin",)
+    return (bin_dir / "verilator_bin.exe", bin_dir / "verilator.exe")
+
+
 def tool_status(root: Path) -> dict[str, Any]:
     bin_dir = root / "bin"
     tools = {}
     for name in REQUIRED_TOOLS:
         if name == "verilator":
-            candidates = (bin_dir / "verilator_bin.exe", bin_dir / "verilator.exe")
+            candidates = _verilator_candidates(bin_dir)
         else:
             candidates = (bin_dir / f"{name}.exe", bin_dir / name)
         path = next((candidate for candidate in candidates if candidate.is_file()), None)
@@ -154,6 +167,34 @@ def select_windows_x64_asset(release_payload: dict[str, Any]) -> dict[str, Any]:
     raise ValueError("No oss-cad-suite-windows-x64-*.exe asset found in release payload")
 
 
+def select_linux_x64_asset(release_payload: dict[str, Any]) -> dict[str, Any]:
+    for asset in release_payload.get("assets", []):
+        name = asset.get("name", "")
+        if name.startswith("oss-cad-suite-linux-x64-") and name.endswith(".tgz"):
+            if asset.get("browser_download_url"):
+                return asset
+    raise ValueError("No oss-cad-suite-linux-x64-*.tgz asset found in release payload")
+
+
+def _is_tar_archive(path: Path) -> bool:
+    lowered = path.name.lower()
+    return lowered.endswith(".tgz") or lowered.endswith(".tar.gz") or lowered.endswith(".tar")
+
+
+def _curl_env() -> dict[str, str]:
+    env = os.environ.copy()
+    for key in (
+        "http_proxy",
+        "https_proxy",
+        "HTTP_PROXY",
+        "HTTPS_PROXY",
+        "ALL_PROXY",
+        "all_proxy",
+    ):
+        env.pop(key, None)
+    return env
+
+
 def download_file(url: str, output: Path) -> None:
     output.parent.mkdir(parents=True, exist_ok=True)
 
@@ -174,7 +215,14 @@ def download_file(url: str, output: Path) -> None:
             url,
         ]
         try:
-            result = subprocess.run(cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=7200)
+            result = subprocess.run(
+                cmd,
+                text=True,
+                stdout=subprocess.PIPE,
+                stderr=subprocess.PIPE,
+                timeout=7200,
+                env=_curl_env(),
+            )
         except subprocess.TimeoutExpired as exc:
             raise RuntimeError(f"curl download timed out; rerun the command to resume: {exc}") from exc
         if result.returncode != 0:
@@ -243,6 +291,38 @@ def extract_archive(archive: Path, install_root: Path) -> None:
         if not (install_root / "bin").is_dir():
             detail = "" if last_result is None else (last_result.stdout + last_result.stderr)[-2000:]
             raise RuntimeError(f"OSS CAD Suite SFX extraction did not create bin directory: {detail}")
+    elif _is_tar_archive(archive):
+        staging = install_root.with_name(install_root.name + ".staging")
+        if staging.exists():
+            if not _is_owned(staging, "oss_cad_suite_staging"):
+                raise RuntimeError(f"refusing to replace unowned staging directory: {staging}")
+            shutil.rmtree(staging)
+        staging.mkdir(parents=True, exist_ok=True)
+        _write_owner_marker(staging, "oss_cad_suite_staging", {"archive": str(archive)})
+        tar = shutil.which("tar")
+        if not tar:
+            raise RuntimeError("tar executable not found; cannot extract OSS CAD Suite archive")
+        try:
+            subprocess.run(
+                [tar, "-xzf", str(archive), "-C", str(staging)],
+                text=True,
+                stdout=subprocess.PIPE,
+                stderr=subprocess.PIPE,
+                timeout=1200,
+                check=True,
+            )
+        except subprocess.CalledProcessError as exc:
+            detail = (exc.stdout or "") + (exc.stderr or "")
+            raise RuntimeError(f"tar extraction failed: {detail[-2000:]}") from exc
+        _promote_nested_install_root(staging)
+        if not (staging / "bin").is_dir():
+            raise RuntimeError(f"OSS CAD Suite tar extraction did not create bin directory: {staging}")
+        if install_root.exists():
+            if not _is_owned(install_root, "oss_cad_suite"):
+                raise RuntimeError(f"refusing to replace unowned install root: {install_root}")
+            shutil.rmtree(install_root)
+        staging.rename(install_root)
+        _write_owner_marker(install_root, "oss_cad_suite", {"archive": str(archive), "extractor": "tar"})
     else:
         raise ValueError(f"Unsupported archive type: {archive}")
 
@@ -269,21 +349,14 @@ def _promote_nested_install_root(install_root: Path) -> None:
     temp_root.rmdir()
 
 
-def install_latest_windows_x64(
+def _finalize_install(
     *,
     install_root: Path,
-    download_dir: Path,
-    release_payload: dict[str, Any] | None = None,
-    download_func=download_file,
-    extract_func=extract_archive,
+    release: dict[str, Any],
+    asset: dict[str, Any],
+    archive: Path,
 ) -> dict[str, Any]:
-    release = release_payload or fetch_latest_release()
-    install_root = _assert_safe_toolchain_root(install_root)
-    asset = select_windows_x64_asset(release)
-    archive = download_dir / asset["name"]
-    download_func(asset["browser_download_url"], archive)
     archive_hash = sha256(archive)
-    extract_func(archive, install_root)
     payload = tool_status(install_root)
     payload.update({
         "status": "present" if all(item["status"] == "present" for item in payload["tools"].values()) else "fail",
@@ -314,6 +387,50 @@ def install_latest_windows_x64(
     return payload
 
 
+def install_latest_windows_x64(
+    *,
+    install_root: Path,
+    download_dir: Path,
+    release_payload: dict[str, Any] | None = None,
+    download_func=download_file,
+    extract_func=extract_archive,
+) -> dict[str, Any]:
+    release = release_payload or fetch_latest_release()
+    install_root = _assert_safe_toolchain_root(install_root)
+    asset = select_windows_x64_asset(release)
+    archive = download_dir / asset["name"]
+    download_func(asset["browser_download_url"], archive)
+    extract_func(archive, install_root)
+    return _finalize_install(
+        install_root=install_root,
+        release=release,
+        asset=asset,
+        archive=archive,
+    )
+
+
+def install_latest_linux_x64(
+    *,
+    install_root: Path,
+    download_dir: Path,
+    release_payload: dict[str, Any] | None = None,
+    download_func=download_file,
+    extract_func=extract_archive,
+) -> dict[str, Any]:
+    release = release_payload or fetch_latest_release()
+    install_root = _assert_safe_toolchain_root(install_root)
+    asset = select_linux_x64_asset(release)
+    archive = download_dir / asset["name"]
+    download_func(asset["browser_download_url"], archive)
+    extract_func(archive, install_root)
+    return _finalize_install(
+        install_root=install_root,
+        release=release,
+        asset=asset,
+        archive=archive,
+    )
+
+
 def run_checked(cmd: list[str], *, cwd: Path | None = None, timeout: int = 600) -> subprocess.CompletedProcess[str]:
     result = subprocess.run(
         cmd,
@@ -440,10 +557,12 @@ def build_parser() -> argparse.ArgumentParser:
     parser.add_argument("--python-exe", type=Path, default=DEFAULT_BUNDLED_PYTHON)
     parser.add_argument("--cocotb-version", default=DEFAULT_COCOTB_VERSION)
     parser.add_argument("--install-latest-windows-x64", action="store_true")
+    parser.add_argument("--install-latest-linux-x64", action="store_true")
     parser.add_argument("--install-cocotb-venv", action="store_true")
     parser.add_argument("--download-url", help="Explicit OSS CAD Suite zip URL. See releases URL in --json output.")
     parser.add_argument("--download-to", type=Path, help="Destination zip path for --download-url.")
     parser.add_argument("--extract-zip", type=Path, help="Extract a previously downloaded OSS CAD Suite zip.")
+    parser.add_argument("--extract-archive", type=Path, help="Extract a previously downloaded OSS CAD Suite archive.")
     parser.add_argument("--print-env", action="store_true", help="Print PowerShell environment commands.")
     parser.add_argument("--json", action="store_true")
     return parser
@@ -459,6 +578,10 @@ def main(argv: list[str] | None = None) -> int:
         payload = install_latest_windows_x64(install_root=args.install_root, download_dir=args.download_dir)
         print(json.dumps(payload, indent=2) if args.json else f"installed: {payload['install_root']}")
         return 0
+    if args.install_latest_linux_x64:
+        payload = install_latest_linux_x64(install_root=args.install_root, download_dir=args.download_dir)
+        print(json.dumps(payload, indent=2) if args.json else f"installed: {payload['install_root']}")
+        return 0
     if args.install_cocotb_venv:
         payload = install_cocotb_venv(
             venv_dir=args.cocotb_venv,
@@ -469,6 +592,16 @@ def main(argv: list[str] | None = None) -> int:
         return 0
     if args.extract_zip:
         extract_archive(args.extract_zip, args.install_root)
+    if args.extract_archive:
+        extract_archive(args.extract_archive, args.install_root)
+        payload = _finalize_install(
+            install_root=_assert_safe_toolchain_root(args.install_root),
+            release={"tag_name": "local-archive"},
+            asset={"name": args.extract_archive.name, "browser_download_url": None, "size": args.extract_archive.stat().st_size},
+            archive=args.extract_archive,
+        )
+        print(json.dumps(payload, indent=2) if args.json else f"installed: {payload['install_root']}")
+        return 0
 
     payload = tool_status(args.install_root)
     if args.print_env:

+ 129 - 0
tools/download_oss_cad_linux.sh

@@ -0,0 +1,129 @@
+#!/usr/bin/env bash
+# Resumable native-network download + extract for OSS CAD Suite (Linux x64).
+# Uses curl -C - only; clears proxy env vars. Idempotent when archive is complete.
+set -euo pipefail
+
+unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY all_proxy no_proxy NO_PROXY
+export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:${PATH:-}"
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+CACHE="${XDG_CACHE_HOME:-$HOME/.cache}/prod2u"
+DOWNLOAD_DIR="$CACHE/downloads"
+INSTALL_ROOT="$CACHE/oss-cad-suite/latest"
+LOG="$DOWNLOAD_DIR/oss-cad-download.log"
+
+DEFAULT_URL="${OSS_CAD_DOWNLOAD_URL:-https://github.com/YosysHQ/oss-cad-suite-build/releases/download/2026-08-04/oss-cad-suite-linux-x64-20260804.tgz}"
+DEFAULT_NAME="$(basename "$DEFAULT_URL")"
+ARCHIVE="${OSS_CAD_ARCHIVE:-$DOWNLOAD_DIR/$DEFAULT_NAME}"
+PART="${ARCHIVE}.partial"
+EXPECTED_SIZE="${OSS_CAD_EXPECTED_SIZE:-737555999}"
+EXPECTED_SHA256="${OSS_CAD_EXPECTED_SHA256:-f9c8f52d7333341a1dcad3dc19b0ce229f1b30c5a30cdc8befcc6dd5c8ee2cbd}"
+
+RESUMED=0
+if [[ -f "$PART" && ! -f "$ARCHIVE" ]]; then
+  RESUMED=1
+fi
+
+usage() {
+  cat <<EOF
+Usage: $(basename "$0") [--download-only] [--extract-only] [--url URL] [--archive PATH]
+
+Native curl resume download for OSS CAD Suite Linux x64.
+  download dir : $DOWNLOAD_DIR
+  install root : $INSTALL_ROOT
+  default url  : $DEFAULT_URL
+  expected size: $EXPECTED_SIZE bytes
+
+Environment:
+  OSS_CAD_DOWNLOAD_URL      override download URL
+  OSS_CAD_ARCHIVE           final .tgz path (default: \$DOWNLOAD_DIR/<basename>)
+  OSS_CAD_EXPECTED_SIZE     byte size check (default: $EXPECTED_SIZE)
+  OSS_CAD_EXPECTED_SHA256   sha256 check after download
+                            (default: f9c8f52d7333341a1dcad3dc19b0ce229f1b30c5a30cdc8befcc6dd5c8ee2cbd)
+  OSS_CAD_SKIP_EXTRACT=1    download only, do not extract
+EOF
+}
+
+DOWNLOAD_ONLY=0
+EXTRACT_ONLY=0
+while [[ $# -gt 0 ]]; do
+  case "$1" in
+    --download-only) DOWNLOAD_ONLY=1; shift ;;
+    --extract-only) EXTRACT_ONLY=1; shift ;;
+    --url) DEFAULT_URL="$2"; DEFAULT_NAME="$(basename "$DEFAULT_URL")"; ARCHIVE="$DOWNLOAD_DIR/$DEFAULT_NAME"; PART="${ARCHIVE}.partial"; shift 2 ;;
+    --archive) ARCHIVE="$2"; PART="${ARCHIVE}.partial"; shift 2 ;;
+    -h|--help) usage; exit 0 ;;
+    *) echo "unknown arg: $1" >&2; usage; exit 2 ;;
+  esac
+done
+
+mkdir -p "$DOWNLOAD_DIR"
+
+download_archive() {
+  if [[ -f "$ARCHIVE" ]]; then
+    local sz
+    sz="$(stat -c%s "$ARCHIVE")"
+    if [[ "$sz" -eq "$EXPECTED_SIZE" ]]; then
+      echo "archive already complete: $ARCHIVE ($sz bytes)" | tee -a "$LOG"
+      return 0
+    fi
+    echo "existing archive size mismatch ($sz != $EXPECTED_SIZE); re-downloading via partial resume" | tee -a "$LOG"
+    mv -f "$ARCHIVE" "$PART"
+    RESUMED=1
+  fi
+
+  if [[ -f "$PART" ]]; then
+    RESUMED=1
+    echo "resume from $(stat -c%s "$PART") bytes -> $ARCHIVE (expect $EXPECTED_SIZE)" | tee -a "$LOG"
+  else
+    echo "fresh download -> $PART (expect $EXPECTED_SIZE)" | tee -a "$LOG"
+  fi
+
+  curl -L --fail --retry 8 --retry-delay 10 --retry-all-errors \
+    -C - \
+    --connect-timeout 30 \
+    -o "$PART" \
+    "$DEFAULT_URL" 2>&1 | tee -a "$LOG"
+
+  local sz
+  sz="$(stat -c%s "$PART")"
+  if [[ "$sz" -ne "$EXPECTED_SIZE" ]]; then
+    echo "size mismatch after download: got=$sz expected=$EXPECTED_SIZE" | tee -a "$LOG" >&2
+    exit 2
+  fi
+
+  mv -f "$PART" "$ARCHIVE"
+  local digest
+  digest="$(sha256sum "$ARCHIVE" | awk '{print $1}')"
+  echo "DOWNLOAD_OK path=$ARCHIVE size=$sz sha256=$digest resumed=$RESUMED" | tee -a "$LOG"
+
+  if [[ -n "$EXPECTED_SHA256" && "$digest" != "$EXPECTED_SHA256" ]]; then
+    echo "sha256 mismatch: got=$digest expected=$EXPECTED_SHA256" | tee -a "$LOG" >&2
+    exit 3
+  fi
+}
+
+extract_archive() {
+  if [[ ! -f "$ARCHIVE" ]]; then
+    echo "archive missing: $ARCHIVE" >&2
+    exit 1
+  fi
+  python3 "$ROOT/tools/bootstrap_oss_cad_suite.py" \
+    --install-root "$INSTALL_ROOT" \
+    --extract-archive "$ARCHIVE" \
+    --json
+}
+
+if [[ "$EXTRACT_ONLY" -eq 0 ]]; then
+  download_archive
+fi
+
+if [[ "$DOWNLOAD_ONLY" -eq 0 && "${OSS_CAD_SKIP_EXTRACT:-0}" != "1" ]]; then
+  extract_archive
+fi
+
+if [[ -f "$ARCHIVE" ]]; then
+  sha256sum "$ARCHIVE"
+  stat -c 'path=%n size=%s bytes' "$ARCHIVE"
+fi
+echo "install_root=$INSTALL_ROOT resumed=$RESUMED"

+ 5 - 0
tools/package-handoff.sh

@@ -8,9 +8,14 @@ PY="${VENV}/bin/python"
 [[ -x "$PY" ]] || PY=python3
 OUT="${PRODU2_HANDOFF_DIR:-${TMPDIR:-/tmp}/prod2u-handoff}"
 NAME="${PRODU2_PACKAGE_NAME:-cpld-analysis-$(date -u +%Y%m%dT%H%M%SZ)}"
+PROFILE_ARGS=()
+if [[ -n "${PRODU2_HANDOFF_PROFILE:-}" ]]; then
+  PROFILE_ARGS=(--profile "$PRODU2_HANDOFF_PROFILE")
+fi
 mkdir -p "$OUT"
 exec "$PY" -B "$ROOT/tools/package_agent_handoff.py" \
   --source-root "$ROOT" \
   --output-dir "$OUT" \
   --package-name "$NAME" \
+  "${PROFILE_ARGS[@]}" \
   "$@"

+ 151 - 13
tools/package_agent_handoff.py

@@ -86,6 +86,17 @@ 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"})
+CODE_ONLY_ROOT_EXCLUSIONS = {
+    "reference": "reference_material",
+}
+CODE_ONLY_GENERATED_VISUAL_ASSETS = frozenset(
+    {
+        "board-copper.svg",
+        "board-silkscreen.svg",
+        "board-mask-edge.svg",
+    }
+)
 WINDOWS_RESERVED_NAMES = {
     "con",
     "prn",
@@ -127,6 +138,7 @@ class ArchiveScanBudget:
 @dataclass(frozen=True)
 class ScanContext:
     changxin_version: str | None
+    profile: str = "full"
 
 
 def utc_now() -> str:
@@ -235,7 +247,7 @@ def is_under(relative: str, prefix: str) -> bool:
     return relative == prefix or relative.startswith(prefix + "/")
 
 
-def load_scan_context(root: Path) -> ScanContext:
+def load_scan_context(root: Path, *, profile: str = "full") -> ScanContext:
     pyproject = root / "tools" / "changxin-temp-uart" / "pyproject.toml"
     version: str | None = None
     try:
@@ -250,7 +262,7 @@ def load_scan_context(root: Path) -> ScanContext:
             version = value.strip()
     except (PackagingError, UnicodeError, tomllib.TOMLDecodeError):
         version = None
-    return ScanContext(version)
+    return ScanContext(version, profile=profile)
 
 
 def secret_path_reason(relative: str, *, is_dir: bool) -> str | None:
@@ -470,6 +482,32 @@ def exclusion_reason(relative: str, *, is_dir: bool, context: ScanContext) -> st
     return None
 
 
+def code_only_exclusion_reason(relative: str, *, is_dir: bool) -> str | None:
+    lower = relative.casefold()
+    name = lower.rsplit("/", 1)[-1]
+    for prefix, reason in CODE_ONLY_ROOT_EXCLUSIONS.items():
+        if is_under(lower, prefix):
+            return reason
+    if not is_dir and is_under(lower, "tools/board-viewer/generated"):
+        if name in CODE_ONLY_GENERATED_VISUAL_ASSETS:
+            return "generated_board_viewer_visual_asset"
+    return None
+
+
+def make_exclusion_resolver(profile: str) -> Callable[..., str | None]:
+    if profile not in HANDOFF_PROFILES:
+        raise PackagingError(f"unsupported handoff profile: {profile}")
+
+    def resolve(relative: str, *, is_dir: bool, context: ScanContext) -> str | None:
+        if profile == "code-only":
+            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)
+
+    return resolve
+
+
 def stat_is_reparse_point(file_stat: os.stat_result) -> bool:
     attributes = int(getattr(file_stat, "st_file_attributes", 0))
     reparse_flag = int(getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0))
@@ -498,8 +536,9 @@ def scan_tree(
     root: Path,
     *,
     exclusion_resolver: Callable[..., str | None] | None = None,
+    profile: str = "full",
 ) -> tuple[list[Candidate], list[dict[str, str]], ScanContext]:
-    context = load_scan_context(root)
+    context = load_scan_context(root, profile=profile)
     resolve_exclusion = exclusion_resolver or exclusion_reason
     included: list[Candidate] = []
     excluded: list[dict[str, str]] = []
@@ -1178,23 +1217,66 @@ def collect_git_provenance(root: Path) -> tuple[dict[str, object], dict[str, byt
 def build_metadata(
     *,
     package_name: str,
+    profile: str,
     inventory: list[dict[str, object]],
     excluded: list[dict[str, str]],
     context: ScanContext,
     provenance: dict[str, object],
 ) -> dict[str, bytes]:
     rule_counts = Counter(item["rule"] for item in excluded)
+    derived_evidence = []
+    for item in inventory:
+        path = str(item["path"])
+        name = path.casefold().rsplit("/", 1)[-1]
+        if name not in CODE_ONLY_GENERATED_VISUAL_ASSETS and name not in {
+            "board-data.json",
+            "build-info.json",
+            "import-report.json",
+        }:
+            continue
+        if "tools/board-viewer/generated/" not in path.casefold():
+            continue
+        role = (
+            "derived_from_brd_visual"
+            if name in CODE_ONLY_GENERATED_VISUAL_ASSETS
+            else "derived_from_brd_parsed"
+        )
+        derived_evidence.append(
+            {
+                "path": path,
+                "asset": name,
+                "role": role,
+                "authority": "analysis_evidence_not_source_closure",
+                "note": "Derived from the original Allegro BRD for remote analysis; not RTL/TD source closure.",
+            }
+        )
+    authority_boundary = (
+        "Inclusion-first analysis handoff of source, requirements, tests, original references, "
+        "board-viewer derived evidence (JSON/SVG labeled not source closure), and retained evidence. "
+        "It excludes credentials, license archives, vendor installers, caches, node_modules, venvs, "
+        "raw Git objects, and declared reconstructable runtime outputs."
+    )
+    if profile == "code-only":
+        authority_boundary = (
+            "This archive is a code-and-tests-only analysis handoff. It excludes reference materials, "
+            "generated board-viewer visual assets, credentials, private archives, raw Git objects, "
+            "and declared reconstructable runtime outputs."
+        )
+        derived_evidence = []
     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",
         "archive_root": ARCHIVE_ROOT,
         "source_name": ARCHIVE_ROOT,
         "included_file_count": len(inventory),
         "included_bytes": sum(int(item["size"]) for item in inventory),
         "excluded_entry_count": len(excluded),
         "exclusion_rule_counts": dict(sorted(rule_counts.items())),
+        "derived_evidence": derived_evidence,
         "changxin_temp_uart_version": context.changxin_version,
         "git_provenance": provenance,
         "archive_scan_limits": {
@@ -1207,10 +1289,7 @@ def build_metadata(
             "manifest_contains_absolute_source_path": False,
             "note": "Repository files are preserved byte-for-byte; review document and receipt contents before crossing a trust boundary.",
         },
-        "authority_boundary": (
-            "This archive is an analysis handoff of source, requirements, tests, original references, and retained evidence. "
-            "It excludes credentials, private archives, raw Git objects, and declared reconstructable runtime outputs."
-        ),
+        "authority_boundary": authority_boundary,
     }
     exclusions_payload = {
         "schema": "cpld-agent-handoff-exclusions-v1",
@@ -1531,8 +1610,14 @@ def assert_source_tree_unchanged(
     excluded: list[dict[str, str]],
     context: ScanContext,
     inventory: list[dict[str, object]],
+    *,
+    exclusion_resolver: Callable[..., str | None] | None = None,
 ) -> None:
-    current_candidates, current_excluded, current_context = scan_tree(root)
+    current_candidates, current_excluded, current_context = scan_tree(
+        root,
+        exclusion_resolver=exclusion_resolver,
+        profile=context.profile,
+    )
     if scan_snapshot(candidates, excluded, context) != scan_snapshot(
         current_candidates,
         current_excluded,
@@ -1558,6 +1643,7 @@ def _build_package_with_zipfile(
     *,
     root: Path,
     package_name: str,
+    profile: str,
     candidates: list[Candidate],
     excluded: list[dict[str, str]],
     context: ScanContext,
@@ -1566,11 +1652,18 @@ def _build_package_with_zipfile(
 ) -> tuple[list[dict[str, object]], dict[str, bytes], dict[str, bytes]]:
     """Fallback ZIP writer when 7-Zip is not available."""
     inventory: list[dict[str, object]] = []
-    with zipfile.ZipFile(temp_zip, "w", zipfile.ZIP_DEFLATED, allowZip64=True) as archive:
+    with zipfile.ZipFile(
+        temp_zip,
+        "w",
+        compression=zipfile.ZIP_DEFLATED,
+        compresslevel=9,
+        allowZip64=True,
+    ) as archive:
         for candidate in candidates:
             inventory.append(write_candidate(archive, candidate))
         metadata_artifacts = build_metadata(
             package_name=package_name,
+            profile=profile,
             inventory=inventory,
             excluded=excluded,
             context=context,
@@ -1587,6 +1680,7 @@ def _build_package_with_7z(
     *,
     root: Path,
     package_name: str,
+    profile: str,
     token: str,
     output_dir: Path,
     candidates: list[Candidate],
@@ -1610,6 +1704,7 @@ def _build_package_with_7z(
             )
         metadata_artifacts = build_metadata(
             package_name=package_name,
+            profile=profile,
             inventory=inventory,
             excluded=excluded,
             context=context,
@@ -1641,6 +1736,8 @@ def create_package(
     candidates: list[Candidate],
     excluded: list[dict[str, str]],
     context: ScanContext,
+    profile: str = "full",
+    exclusion_resolver: Callable[..., str | None] | None = None,
 ) -> dict[str, object]:
     # Prefer Python zipfile so UTF-8 arcnames stay consistent on Linux/Windows.
     # 7-Zip remains available as an optional verifier, not the primary writer.
@@ -1663,6 +1760,7 @@ def create_package(
                 temp_zip,
                 root=root,
                 package_name=package_name,
+                profile=profile,
                 candidates=candidates,
                 excluded=excluded,
                 context=context,
@@ -1675,6 +1773,7 @@ def create_package(
                 temp_zip,
                 root=root,
                 package_name=package_name,
+                profile=profile,
                 token=token,
                 output_dir=output_dir,
                 candidates=candidates,
@@ -1703,7 +1802,14 @@ def create_package(
                 zip_sha256 = zip_digest.hexdigest()
         except OSError as exc:
             raise PackagingError("temporary ZIP changed during stable verification") from exc
-        assert_source_tree_unchanged(root, candidates, excluded, context, inventory)
+        assert_source_tree_unchanged(
+            root,
+            candidates,
+            excluded,
+            context,
+            inventory,
+            exclusion_resolver=exclusion_resolver,
+        )
         sidecar_payload = f"{zip_sha256}  {final_zip.name}\n".encode("ascii")
         temp_sidecar.write_bytes(sidecar_payload)
 
@@ -1717,7 +1823,14 @@ def create_package(
                 inventory=inventory,
                 expected_payloads=expected_payloads,
             )
-            assert_source_tree_unchanged(root, candidates, excluded, context, inventory)
+            assert_source_tree_unchanged(
+                root,
+                candidates,
+                excluded,
+                context,
+                inventory,
+                exclusion_resolver=exclusion_resolver,
+            )
 
         cleanup_warnings = publish_artifacts_atomically(
             [(temp_zip, final_zip), (temp_sidecar, final_sidecar)],
@@ -1736,6 +1849,7 @@ def create_package(
     return {
         "status": "pass",
         "mode": "package",
+        "profile": profile,
         "package_name": package_name,
         "package_zip": str(final_zip),
         "package_zip_sha256": zip_sha256,
@@ -1775,6 +1889,15 @@ def build_parser() -> argparse.ArgumentParser:
     parser.add_argument("--package-name")
     parser.add_argument("--force-overwrite", action="store_true")
     parser.add_argument("--audit-only", action="store_true")
+    parser.add_argument(
+        "--profile",
+        choices=sorted(HANDOFF_PROFILES),
+        default="full",
+        help=(
+            "inclusion-first full profile includes reference + derived board-viewer JSON/SVG; "
+            "code-only excludes reference/ and heavy board-viewer SVG assets"
+        ),
+    )
     parser.add_argument(
         "--reference-archive",
         action="append",
@@ -1811,14 +1934,27 @@ def main(argv: list[str] | None = None) -> int:
         return 1
     try:
         source, output = validate_paths(args.source_root, args.output_dir)
-        candidates, excluded, context = scan_tree(source)
+        exclusion_resolver = make_exclusion_resolver(args.profile)
+        candidates, excluded, context = scan_tree(
+            source,
+            exclusion_resolver=exclusion_resolver,
+            profile=args.profile,
+        )
         if args.audit_only:
             audit_inventory = audit_candidates(candidates)
-            assert_source_tree_unchanged(source, candidates, excluded, context, audit_inventory)
+            assert_source_tree_unchanged(
+                source,
+                candidates,
+                excluded,
+                context,
+                audit_inventory,
+                exclusion_resolver=exclusion_resolver,
+            )
             rule_counts = Counter(item["rule"] for item in excluded)
             payload = {
                 "status": "pass",
                 "mode": "audit_only",
+                "profile": args.profile,
                 "package_name": package_name,
                 "included_file_count": len(candidates),
                 "included_bytes": sum(item.size for item in candidates),
@@ -1831,10 +1967,12 @@ def main(argv: list[str] | None = None) -> int:
                 root=source,
                 output_dir=output,
                 package_name=package_name,
+                profile=args.profile,
                 force=args.force_overwrite,
                 candidates=candidates,
                 excluded=excluded,
                 context=context,
+                exclusion_resolver=exclusion_resolver,
             )
     except (PackagingError, OSError) as exc:
         print(f"error: {exc}", file=sys.stderr)