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

chore: migrate CPLD reference assets and audit tooling

Codex Resource Selftest 4 месяцев назад
Родитель
Сommit
4aeb07a8c2
69 измененных файлов с 23946 добавлено и 1 удалено
  1. 4 0
      .gitignore
  2. 20 1
      AGENTS.md
  3. 110 0
      PACKAGE_FOR_AGENT_ANALYSIS.README.zh-CN.md
  4. 49 0
      config/agent_analysis_handoff_sources.json
  5. 2602 0
      config/board_viewer_annotations.fcb_fpga_mcu0611.json
  6. 29 0
      config/cpld_c_drive_audit.json
  7. 120 0
      config/pin_inventory.fcb_fpga_mcu0611.json
  8. 131 0
      config/pin_inventory.mini.json
  9. 12 0
      config/pin_inventory.product.placeholder.json
  10. 32 0
      docs/agent-handoff-packaging.zh-CN.md
  11. 1584 0
      package_for_agent_analysis.py
  12. 1023 0
      reference/historical/serial/prod2u-p4-binary921-v3-serial-port-summary-v1.zh-CN.md
  13. 1034 0
      reference/historical/serial/prod2u-p4-serial-port-hex-summary-v1.zh-CN.md
  14. 25 0
      reference/original/MANIFEST.zh-CN.md
  15. 299 0
      schemas/agent_analysis_handoff_index.schema.json
  16. 101 0
      schemas/agent_analysis_handoff_sources.schema.json
  17. 237 0
      schemas/board_viewer_annotations.schema.json
  18. 90 0
      schemas/board_viewer_build_info.schema.json
  19. 238 0
      schemas/board_viewer_data.schema.json
  20. 80 0
      schemas/cpld_c_drive_audit.schema.json
  21. 28 0
      schemas/cpld_c_drive_audit_config.schema.json
  22. 423 0
      tests/board_viewer/board-logic.test.mjs
  23. 118 0
      tests/board_viewer/fixtures/connector_layouts.kicad_pcb
  24. 7 0
      tests/board_viewer/fixtures/parser_edge_cases.d356
  25. 62 0
      tests/board_viewer/fixtures/parser_edge_cases.kicad_pcb
  26. 105 0
      tests/board_viewer/fixtures/parser_edge_cases.kicad_prl
  27. 394 0
      tests/board_viewer/playwright_e2e.cjs
  28. 185 0
      tests/board_viewer/test_annotations_and_eligibility.py
  29. 131 0
      tests/board_viewer/test_asset_validation.py
  30. 69 0
      tests/board_viewer/test_cli_launcher.py
  31. 901 0
      tests/board_viewer/test_data_contract.py
  32. 247 0
      tests/board_viewer/test_generator.py
  33. 68 0
      tests/board_viewer/test_ipcd356_alignment.py
  34. 76 0
      tests/board_viewer/test_pcb_parser.py
  35. 102 0
      tests/board_viewer/test_photo_overlay.py
  36. 176 0
      tests/board_viewer/test_product_functional_annotations.py
  37. 656 0
      tests/board_viewer/test_product_regression.py
  38. 126 0
      tests/board_viewer/test_server.py
  39. 87 0
      tests/board_viewer/test_web_shell.py
  40. 1570 0
      tests/unit/test_agent_handoff_package.py
  41. 112 0
      tests/unit/test_cpld_c_drive_audit.py
  42. 787 0
      tests/unit/test_package_for_agent_analysis.py
  43. 325 0
      tests/unit/test_pin_inventory.py
  44. 18 0
      tools/board-viewer/OPEN_BOARD_VIEWER.cmd
  45. 131 0
      tools/board-viewer/README.zh-CN.md
  46. 8 0
      tools/board-viewer/board_viewer.py
  47. 1 0
      tools/board-viewer/board_viewer/__init__.py
  48. 180 0
      tools/board-viewer/board_viewer/annotations.py
  49. 124 0
      tools/board-viewer/board_viewer/assets.py
  50. 162 0
      tools/board-viewer/board_viewer/cli.py
  51. 797 0
      tools/board-viewer/board_viewer/data.py
  52. 73 0
      tools/board-viewer/board_viewer/eligibility.py
  53. 423 0
      tools/board-viewer/board_viewer/generator.py
  54. 143 0
      tools/board-viewer/board_viewer/ipcd356.py
  55. 391 0
      tools/board-viewer/board_viewer/pcb.py
  56. 135 0
      tools/board-viewer/board_viewer/photo.py
  57. 573 0
      tools/board-viewer/board_viewer/regression.py
  58. 179 0
      tools/board-viewer/board_viewer/server.py
  59. 190 0
      tools/board-viewer/board_viewer/sexpr.py
  60. 63 0
      tools/board-viewer/package-lock.json
  61. 15 0
      tools/board-viewer/package.json
  62. 1281 0
      tools/board-viewer/web/app.css
  63. 1038 0
      tools/board-viewer/web/app.js
  64. 288 0
      tools/board-viewer/web/board-logic.mjs
  65. 126 0
      tools/board-viewer/web/index.html
  66. 569 0
      tools/cpld_c_drive_audit.py
  67. 203 0
      tools/package_agent_handoff.ps1
  68. 1639 0
      tools/package_agent_handoff.py
  69. 621 0
      tools/pin_inventory.py

+ 4 - 0
.gitignore

@@ -46,3 +46,7 @@ tmp_last_pkg*.txt
 __pycache__/
 *.py[cod]
 .pytest_cache/
+node_modules/
+.playwright-browsers/
+tools/board-viewer/generated/**
+reference/original/board/FCB_FPGA_MCU_V1.1_20260625/*.brd

+ 20 - 1
AGENTS.md

@@ -7,11 +7,18 @@
 - 唯一生产顶层是 `src/top/prod2u_p4_normal_v3_top.v`。
 - 活 RTL 只放在 `src/rtl/`,活验证只放在 `tests/`、`tools/`、`td/`、`config/`、`constraints/`、`schemas/`。
 - `td/prod2u_p4_normal_v3.prj` 及同名 syn/phy/bitgen 脚本是唯一 TD 工程入口。
-- `reference/original/**`、`receipts/**` 和用户 `.planning/` 不得修改或纳入当前构建证据。
+- `reference/original/**`、`receipts/**` 和用户 `.planning/` 不得纳入当前构建证据。仅允许在明确的非生产资产治理提交中更新原始资料清单或本地忽略资产,且必须证明生产构建输入未变化。
 - `td/build/`、`tmp/`、bit/bid/data/log/timing/area 和工具运行目录均为生成物,不得提交。
 - 当前是临时快速开发:优先最小、可用、易验证的逻辑,不为低概率边界增加缓存、锁或复杂恢复。
 - 未回答的需求或边界问题必须再次询问,不得自行采用默认值;Git 暂存和提交只由单一协调者执行。
 
+## 资产治理
+
+- 板卡查看器、分析/交接打包器和只读磁盘审计工具属于非生产辅助能力,不得成为新的 RTL、TD 或固件入口。
+- 历史协议资料只放在 `reference/historical/`,必须明确绑定旧提交或旧包,不得作为当前 `1920ab3e` 协议合同。
+- 原始 `.brd`、厂商资料、license 和私有压缩包只在 `reference/original/` 本地保留并由 `.gitignore` 排除;Git 只提交路径、用途和 SHA-256 清单。
+- C 盘审计工具只允许读取并输出 JSON 清单,不得提供删除、移动、改名、Git 引用修改或硬件操作入口。
+
 ## 功能合同
 
 - 保留 24 路 PTC、4 路 FAN、solenoid、UART 和 X/Y 电机;LS1/LS2 仅保留物理引脚,Z 只保留协议位置。
@@ -48,3 +55,15 @@
 - 本仓库默认只生成和验证刷机包,不打开 COM5/JTAG,不执行编程。
 - 明确授权的板测最多一次 `PROGRAM_SRAM @ 200 kHz`,异常不得自动重试;编程后立即发送 DISABLE。
 - JOG 完全无机械保护且单条可执行 65535 步;DISABLE、watchdog 和限位均不能停电机。任何异常必须立即断电或复位/重新配置。
+
+## 安全边界
+
+- 禁止 flash、驱动安装/重装、真实 PTC/fan/BMC 未受控动作。
+- 任何出现 `PROGRAM_FLASH`、`ERASE_FLASH`、`PROGRAM_SPIBIN`、`DIRECT_FLASH_WRITE` 或真实热闭环动作的路径必须 fail closed。
+- `uart-preflight` 只能枚举串口,禁止打开未知 COM 口或切换 DTR/RTS;本轮资产工具和审计工具不得连接串口、JTAG 或硬件。
+- `uart-board-sram-test` 类 receipt 只允许 `PROGRAM_SRAM`,必须记录 bitstream hash、串口 transcript hash、debug UART 事件流、register dump 和 counterparty。
+
+## 资产更新要求
+
+- 新增真实板级 PID、flash、驱动、外部仪器或生产硬件动作时,必须同时新增独立 gate、receipt schema、rollback/安全边界和中文 runbook。
+- 板卡查看器、handoff/analysis 打包器和 C 盘审计 CLI 只能读文件并输出验证结果,不得成为生产构建入口或提供自动删除入口。

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

@@ -0,0 +1,110 @@
+# CPLD 完整分析打包工具
+
+根目录入口:
+
+```powershell
+python .\package_for_agent_analysis.py
+```
+
+这个工具用于把当前 CPLD 仓库和配置中的外部关联目录交给其他 agent 分析。核心规则是:**来源根内的普通文件默认全部收入,只执行明确、版本化的负向排除规则。** 它不会按扩展名、文件大小、Git 跟踪状态或“看起来可能有用”来建立正向白名单。
+
+要求 Python 3.11 或更高版本。默认配置是 `config/agent_analysis_handoff_sources.json`,结构约束是 `schemas/agent_analysis_handoff_sources.schema.json`。
+
+## 默认来源
+
+除了当前 CPLD 仓库,默认还检查:
+
+- TD 2026.1 SP1 的 `doc/` 文档目录;
+- `C:\Users\Administrator\CodexTemp\cpld-board-viewer-discovery-20260721` 板卡查看器目录;
+- `C:\Users\Administrator\CodexTemp\p4-normal-v1-no-gates-73df4ee` 独立 P4 审查工作树;
+- 仓库 `.codegraph` junction 指向的真实代码图数据目录。
+
+外部来源不存在时,结果是 `pass_with_warnings`,并在 `HANDOFF-INDEX.json` 记录缺失来源。来源已经找到,但扫描、Git bundle、路径安全、凭据检查或完整性校验失败时,工具直接失败,不会把完整性错误降级成警告。
+
+## 常用命令
+
+完整审计但不创建 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` 或正式打包执行。
+
+指定配置、输出目录和包名:
+
+```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
+```
+
+## 收入和排除规则
+
+默认保留源码、测试、文档、原理图、Allegro `.brd`、`board.xml`、`board.cad`、位流、TD 数据库、`.codegraph`、未跟踪 receipts、未知二进制、失败证据和其他可能帮助分析的内容。当前仓库和独立 Git 工作树还会保存文件系统快照以及经过 `git bundle verify` 的 `git bundle --all`,但不复制 raw `.git`。
+
+硬排除包括许可证、私钥、真实 `.env`、凭据配置、raw `.git`、路径逃逸、junction/symlink/reparse point 和输出目录回灌。分析排除包括虚拟环境、Python 字节码、测试/类型检查缓存、编辑器临时文件和已明确标记的工具缓存。
+
+RAR/7z 必须由本机 7-Zip 列目录、验证成员路径、完整展开并扫描。安全归档同时保留原包和展开版;含许可证或凭据路径时,只保留清理后的展开版和排除记录。找不到 7-Zip 时,未经安全检查的 RAR/7z 不收入,并产生警告。
+
+## ZIP 大小和多卷
+
+工具首先实际压缩一个完整 ZIP:
+
+- 压缩后严格小于 `380,000,000` 字节:发布一个普通 ZIP;
+- 达到或超过该值:改为多个互相独立的普通 ZIP,目标大小不超过 `350,000,000` 字节;
+- 无论哪种模式,每个最终 ZIP 都必须严格小于 `380,000,000` 字节,否则整个运行失败;
+- 单个文件无法放入目标卷时,会拆成多个 ZIP 内部块,并记录原文件 SHA-256。
+
+输出目录默认为:
+
+```text
+%USERPROFILE%\Downloads\CPLD-agent-analysis\<package-name>\
+```
+
+目录内包含:
+
+- 一个或多个普通 `.zip`;
+- `HANDOFF-INDEX.json`:总索引、来源、卷、逐文件 SHA-256、Git、警告和排除原因;
+- `START-HERE.zh-CN.md`:交接起点;
+- `SHA256SUMS.txt`:所有 ZIP 的 SHA-256;
+- `reassemble_large_files.py`:只有发生大文件分块时才生成。
+
+每个 ZIP 内都有自己的 `CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json`。总索引结构由 `schemas/agent_analysis_handoff_index.schema.json` 约束。
+
+## 解压和重组
+
+多个 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
+}
+```
+
+如果存在大文件分块,直接从交付目录运行:
+
+```powershell
+python .\reassemble_large_files.py --package-dir . --output-dir .\reassembled
+```
+
+脚本会逐块核对 SHA-256,重组完成后再次核对原始文件大小和 SHA-256;任一不一致都会失败且不会覆盖最终目标文件,失败时可删除同目录的 `.partial` 文件后重试。
+
+## 安全边界
+
+该工具只读取文件、运行 Git/7-Zip 的离线检查并写入指定输出目录。它不会枚举或打开串口,不会切换 DTR/RTS,不会启动 TD GUI,不会运行 JTAG,不会执行 `PROGRAM_SRAM`、Flash 或任何真实执行器动作,也不会上传、推送或自动提交 Git。

+ 49 - 0
config/agent_analysis_handoff_sources.json

@@ -0,0 +1,49 @@
+{
+  "schema": "cpld-agent-analysis-sources-v1",
+  "max_zip_bytes": 380000000,
+  "target_zip_bytes": 350000000,
+  "external_sources": [
+    {
+      "id": "td-docs",
+      "category": "td-docs",
+      "kind": "directory",
+      "path_candidates": [
+        "C:/Anlogic/TD_Release_2026.1_SP1.198.412/doc"
+      ],
+      "archive_policy": "inspect"
+    },
+    {
+      "id": "board-viewer",
+      "category": "hardware",
+      "kind": "directory",
+      "path_candidates": [
+        "{codex_temp}/cpld-board-viewer-discovery-20260721"
+      ],
+      "archive_policy": "inspect"
+    },
+    {
+      "id": "p4-review-worktree",
+      "category": "core",
+      "kind": "git_worktree",
+      "path_candidates": [
+        "{codex_temp}/p4-normal-v1-no-gates-73df4ee"
+      ],
+      "archive_policy": "inspect"
+    },
+    {
+      "id": "codegraph",
+      "category": "evidence",
+      "kind": "directory",
+      "path_candidates": [
+        "{repo_root}/.codegraph"
+      ],
+      "archive_policy": "inspect"
+    }
+  ],
+  "extra_exclusions": [
+    {
+      "path": ".codegraph",
+      "reason": "declared_external_reparse_alias"
+    }
+  ]
+}

Разница между файлами не показана из-за своего большого размера
+ 2602 - 0
config/board_viewer_annotations.fcb_fpga_mcu0611.json


+ 29 - 0
config/cpld_c_drive_audit.json

@@ -0,0 +1,29 @@
+{
+  "$schema": "https://local.invalid/schemas/cpld_c_drive_audit_config.schema.json",
+  "schema": "cpld-c-drive-audit-config-v1",
+  "scan_roots": [
+    {"path": "C:/Users/Administrator/Agentworkspace/CPLD", "scope": "cpld_workspace"},
+    {"path": "C:/Users/Administrator/CodexTemp", "scope": "cpld_temp_candidates"},
+    {"path": "C:/Users/Administrator/Downloads", "scope": "cpld_delivery_candidates"},
+    {"path": "C:/ct", "scope": "named_cpld_path"},
+    {"path": "C:/P2U", "scope": "named_cpld_path"},
+    {"path": "C:/P4INDEX", "scope": "named_cpld_path"},
+    {"path": "C:/P4R03", "scope": "named_cpld_path"},
+    {"path": "C:/P4STATIC", "scope": "named_cpld_path"},
+    {"path": "C:/P4T", "scope": "named_cpld_path"},
+    {"path": "C:/P4ZIPTEST", "scope": "named_cpld_path"}
+  ],
+  "candidate_patterns": [
+    "cpld", "p4", "prod2u", "temperature", "normal", "handoff", "analysis",
+    "board", "ct7428", "fpga", "firmware", "bitstream", "td-build"
+  ],
+  "excluded_patterns": [
+    "\\.codex", "mediatek", "lixun", "langchao", "boardripper",
+    "\\bnode_modules\\b", "\\.playwright-browsers", "__pycache__", "\\.git"
+  ],
+  "protected_patterns": [
+    "release", "source", "firmware", "final-gate", "rc1", "sha256sums", "dist", "normal-source", "normal\\.bit",
+    "license", "\\.lic$", "private", "original", "hardware[-_ ]evidence"
+  ],
+  "max_files": 100000
+}

Разница между файлами не показана из-за своего большого размера
+ 120 - 0
config/pin_inventory.fcb_fpga_mcu0611.json


+ 131 - 0
config/pin_inventory.mini.json

@@ -0,0 +1,131 @@
+{
+  "schema": "cpld-pin-inventory-v1",
+  "board_id": "ef2l45bg256b_mini_v2",
+  "board_role": "development_validation_carrier",
+  "clock_hz": 25000000,
+  "manual_verification_required": true,
+  "product_thermal_gate_allowed": false,
+  "electrical_boundary": "FPGA IO is 3.3V UART only. External MAX3232 RS232 level shifter required between GPIO UART and RJ45 RS232 wiring.",
+  "source_documents": [
+    {
+      "kind": "hardware_user_guide",
+      "path": "reference/original/board/EF2L45BG256B_MINI_V2.0/EF2L45BG256B_MINI_V2.0板文档/TN427_安路科技EF2L45BG256B_MINI板硬件使用指南.pdf",
+      "confidence": "primary_manual_cross_check_required"
+    },
+    {
+      "kind": "schematic_pdf",
+      "path": "reference/original/board/EF2L45BG256B_MINI_V2.0/EF2L45BG256B_MINI_V2.0原理图/EF2L45BG256B_MINI_V2.0dsn.pdf",
+      "confidence": "schematic_cross_check_required"
+    }
+  ],
+  "pins": [
+    {
+      "signal": null,
+      "connector": "J5",
+      "connector_pin": 5,
+      "fpga_ball": "D2",
+      "io_standard": "LVCMOS33",
+      "role": "user_io",
+      "capability": ["gpio", "uart_rx", "uart_tx"],
+      "reserved": false,
+      "manually_verified": false,
+      "source_confidence": "tn427_cross_check_required"
+    },
+    {
+      "signal": null,
+      "connector": "J5",
+      "connector_pin": 6,
+      "fpga_ball": "D3",
+      "io_standard": "LVCMOS33",
+      "role": "user_io",
+      "capability": ["gpio", "uart_rx", "uart_tx"],
+      "reserved": false,
+      "manually_verified": false,
+      "source_confidence": "tn427_cross_check_required"
+    },
+    {
+      "signal": null,
+      "connector": "J6",
+      "connector_pin": 5,
+      "fpga_ball": "T4",
+      "io_standard": "LVCMOS33",
+      "role": "user_io",
+      "capability": ["gpio", "uart_rx", "uart_tx"],
+      "reserved": false,
+      "manually_verified": false,
+      "source_confidence": "tn427_cross_check_required"
+    },
+    {
+      "signal": null,
+      "connector": "J6",
+      "connector_pin": 6,
+      "fpga_ball": "R5",
+      "io_standard": "LVCMOS33",
+      "role": "user_io",
+      "capability": ["gpio", "uart_rx", "uart_tx"],
+      "reserved": false,
+      "manually_verified": false,
+      "source_confidence": "tn427_cross_check_required"
+    },
+    {
+      "signal": "+3V3",
+      "connector": "J5",
+      "connector_pin": 1,
+      "fpga_ball": "PWR_3V3_J5_1",
+      "io_standard": null,
+      "role": "power",
+      "capability": ["power"],
+      "reserved": true,
+      "manually_verified": false,
+      "source_confidence": "tn427_cross_check_required"
+    },
+    {
+      "signal": "GND",
+      "connector": "J5",
+      "connector_pin": 37,
+      "fpga_ball": "GND_J5_37",
+      "io_standard": null,
+      "role": "gnd",
+      "capability": ["gnd"],
+      "reserved": true,
+      "manually_verified": false,
+      "source_confidence": "tn427_cross_check_required"
+    },
+    {
+      "signal": "GND",
+      "connector": "J5",
+      "connector_pin": 38,
+      "fpga_ball": "GND_J5_38",
+      "io_standard": null,
+      "role": "gnd",
+      "capability": ["gnd"],
+      "reserved": true,
+      "manually_verified": false,
+      "source_confidence": "tn427_cross_check_required"
+    },
+    {
+      "signal": "GND",
+      "connector": "J6",
+      "connector_pin": 39,
+      "fpga_ball": "GND_J6_39",
+      "io_standard": null,
+      "role": "gnd",
+      "capability": ["gnd"],
+      "reserved": true,
+      "manually_verified": false,
+      "source_confidence": "tn427_cross_check_required"
+    },
+    {
+      "signal": "GND",
+      "connector": "J6",
+      "connector_pin": 40,
+      "fpga_ball": "GND_J6_40",
+      "io_standard": null,
+      "role": "gnd",
+      "capability": ["gnd"],
+      "reserved": true,
+      "manually_verified": false,
+      "source_confidence": "tn427_cross_check_required"
+    }
+  ]
+}

+ 12 - 0
config/pin_inventory.product.placeholder.json

@@ -0,0 +1,12 @@
+{
+  "schema": "cpld-pin-inventory-v1",
+  "board_id": "product_board_placeholder",
+  "board_role": "final_product_board",
+  "status": "product_pin_map_missing",
+  "clock_hz": 25000000,
+  "manual_verification_required": true,
+  "product_thermal_gate_allowed": false,
+  "electrical_boundary": "Product board schematic, pin map, driver circuits, interlock wiring, and rollback evidence are not imported yet.",
+  "source_documents": [],
+  "pins": []
+}

+ 32 - 0
docs/agent-handoff-packaging.zh-CN.md

@@ -0,0 +1,32 @@
+# CPLD 分析与交接打包
+
+本工具用于把当前 CPLD 工作区和明确配置的外部资料交给分析代理。它是只读打包能力,不是生产 RTL、TD 或固件入口;不会打开串口、启动 TD GUI、烧录 FPGA,也不会驱动真实 PTC、fan 或 BMC。
+
+运行环境要求 Python 3.11 或更高版本。PowerShell 入口只选择位于脚本仓库和有效 `SourceRoot` 之外的 Python;解释器版本探测和打包核心都使用 `-I -S -B`,不加载用户 site、`PYTHON*` 启动环境或待分析工作区的 `.pyc`。
+
+先执行只读审计,不创建 ZIP 或持久化输出:
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File tools\package_agent_handoff.ps1 -AuditOnly
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File tools\package_agent_handoff.ps1 -AuditOnly -SourceRoot C:\work\CPLD
+```
+
+创建 ZIP 时可以指定仓库外输出目录、包名和覆盖策略:
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File tools\package_agent_handoff.ps1
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File tools\package_agent_handoff.ps1 -OutputDir C:\handoff -PackageName cpld-analysis -ForceOverwrite
+```
+
+同名 ZIP 或 sidecar 默认拒绝覆盖;只有明确传入 `-ForceOverwrite` 时才允许覆盖可写普通文件。目录、symlink/junction、reparse point 和 Windows 只读文件仍会被拒绝。可用 PowerShell 独立核对产物:
+
+```powershell
+Get-FileHash -Algorithm SHA256 C:\handoff\cpld-analysis.zip
+Get-Content C:\handoff\cpld-analysis.zip.sha256.txt
+```
+
+工具打包当前文件系统快照,而不只打包 Git tracked 文件,也不把 `.gitignore` 当成排除清单。原始资料、测试 fixture、非本地 receipts、TD 文本报告、`tmp/photos`、`tmp/pdfs`、formal/mutation/资源分析记录、未知 `tmp` 内容和 `tools/changxin-temp-uart/dist` 中的历史发布物会按配置保留。嵌套归档扫描最多展开 3 层、100,000 个成员和累计 8 GiB 解压字节;超过预算会 fail closed。
+
+明确排除 raw `.git`、license/私有归档、真实 `.env` 和凭据配置、虚拟环境、缓存、TD 数据库/bitstream、复制源码,以及已证明可重建的运行目录。`.env.example`、`.sample`、`.template`、`.dist` 模板和公开证书 PEM 保留;私钥 PEM 由内容扫描 fail closed。未知 `tmp` 路径默认保留,新增排除规则前必须证明没有独立分析价值。
+
+如果 `tmp` 中仍有未迁入 `reference/original/`、`docs/` 或 `receipts/` 的唯一证据,应先完成交接包或证据迁移,再运行 `clean-runtime`。ZIP 内的 `CPLD/HANDOFF-METADATA/` 记录 SHA-256、实际排除路径及可获取的 Git HEAD、branch 和 status;发布前后都会校验 ZIP 路径、CRC、逐文件 SHA-256、metadata 原始字节和 sidecar 哈希。

Разница между файлами не показана из-за своего большого размера
+ 1584 - 0
package_for_agent_analysis.py


Разница между файлами не показана из-за своего большого размера
+ 1023 - 0
reference/historical/serial/prod2u-p4-binary921-v3-serial-port-summary-v1.zh-CN.md


Разница между файлами не показана из-за своего большого размера
+ 1034 - 0
reference/historical/serial/prod2u-p4-serial-port-hex-summary-v1.zh-CN.md


+ 25 - 0
reference/original/MANIFEST.zh-CN.md

@@ -11,5 +11,30 @@
 
 - `local_archives/`:安装包、压缩包、license、私有归档或体积较大的本地资料。
 - `vendor/`:厂商安装介质或可重新获取的大型 vendor payload。
+- `local_archives/ct7428/`:用户提供的 CT7428 原始压缩包,保留原始字节并使用可读文件名归档。
+- `vendor/ct7428/`:从上述压缩包解出的数据手册、转换说明、参考代码,以及用户提供的线缆、地址表和 2N3904 截图。
+- `board/FCB_FPGA_MCU_V1.1_20260625/FCB_FPGA+MCU_V1.1_20260625.brd`:用户提供的 Allegro 原始板数据库,仅本地保留,用于板卡查看器和物理连接核对。
 
 这些路径已由 `.gitignore` 排除。若后续确实需要把某个大型或私有资料纳入可复现证据,应先新增只含 `sha256`、来源、用途、许可边界的 manifest 条目,不直接提交 license、安装包或私有压缩包。
+
+## CT7428 本地资料索引
+
+以下资料于 2026-07-22 从仓库根目录整理而来。压缩包采用 CP936 文件名解码;解压内容保持原始字节,仅规范化了落盘文件名。资料只用于本地器件协议、板级连接和参考实现核对,不作为已验证的生产 RTL 合同,也不随 Git 分发。
+
+| 路径 | 原始名称或来源 | SHA-256 |
+| --- | --- | --- |
+| `local_archives/ct7428/CT7428-温度传感器资料-original.zip` | `温度传感器(1).zip` | `55406405C5AA0327D6621180D0715255E200E6B783DFE3791112741D867F2FC6` |
+| `local_archives/ct7428/CT7428-参考代码-original.zip` | `参考(1).zip` | `18DB67852A27F33509B1214830988AB7C70C7239AF4DB09ECB93C4F59EBBCFE1` |
+| `vendor/ct7428/datasheets/CT7428-datasheet.pdf` | `CT7428.pdf` | `3051BEED5928FE790324D4E6BE9C6EFF0430A5A805CC0091B7ACB96A7099E875` |
+| `vendor/ct7428/datasheets/CT7428-conversion-notes.docx` | `CT7428 conv.docx` | `61AD020495050D163B69DCB2A8FFAFD7BD756A1725C7B2B010C8A63D6C442010` |
+| `vendor/ct7428/datasheets/CT7428-中文翻译.docx` | `CT7428 中文翻译.docx` | `703C08F5E124EF586ACD6C232028B144FD3ABE94BAF767B71AA094E51A21BEB5` |
+| `vendor/ct7428/reference_code/Dri_IIC0.c` | `参考/Dri_IIC0.c` | `872C53250EB5BF9D6664DD9059017C2377F02EB76540ABB464B95B29A334C5A9` |
+| `vendor/ct7428/reference_code/Dri_IIC0.h` | `参考/Dri_IIC0.h` | `87FFB42956C844F186FF6079CE0A5FCFB0F474C91E6922F248B39AB59DF3BF1F` |
+| `vendor/ct7428/reference_code/Int_CT7428.c` | `参考/Int_CT7428.c` | `C72CBA87A1F4293DCEE2DA39AEE17F9DFF4D14F22941D728E38B0E60BB269211` |
+| `vendor/ct7428/reference_code/Int_CT7428.h` | `参考/Int_CT7428.h` | `D52EE9DD9A2145E9AAB8FA71BBB7B0402B78E81EC97371F59DD1518BCC3B98D2` |
+| `vendor/ct7428/reference_code/ct7428_refcode001-51-normal-v1.0-20260714.c` | `ct7428_refcode001-51-normal-v1.0-20260714(2).c` | `C74215CF5F779B121BB986832B77086A89B4738E753FDBB4DDFA886F9C3338FE` |
+| `vendor/ct7428/screenshots/front-sensor-cable-8025A0000401-LSQWH010-SD-R-A03.jpg` | 用户提供的前端温度传感器线缆图截图 | `F8A5F3D32DB553147C4CA17F5AC4026BBB7438CE49B6986F2068FB68F1B877F3` |
+| `vendor/ct7428/screenshots/CT7428-slave-address-table.jpg` | 用户提供的 CT7428 地址表截图 | `CC463C5F298DA555C9BC9F5148B54B5C1BBCB3AF69A00954E1F00760A027CA5A` |
+| `vendor/ct7428/screenshots/2N3904-TO92-datasheet-screenshot.jpg` | 用户提供的 2N3904 数据手册截图 | `0388529B0527C9D02D7DEE64ABDDC6CE77A5071B5CEDD4E8097DA4A05C4C776E` |
+
+`FCB_FPGA+MCU_V1.1_20260625.brd` SHA-256 为 `DB02938F7943B2AE532AA18208F61588364D32A70A0CC72F74B4A94AAAB7E258`;原始 `.brd` 仍由 `.gitignore` 排除。

+ 299 - 0
schemas/agent_analysis_handoff_index.schema.json

@@ -0,0 +1,299 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "https://local.invalid/schemas/agent_analysis_handoff_index.schema.json",
+  "title": "CPLD agent analysis handoff index",
+  "type": "object",
+  "additionalProperties": false,
+  "required": [
+    "schema",
+    "run_id",
+    "created_at_utc",
+    "package_name",
+    "status",
+    "max_zip_bytes",
+    "target_zip_bytes",
+    "sources",
+    "git",
+    "warnings",
+    "excluded",
+    "volumes",
+    "files",
+    "large_files"
+  ],
+  "properties": {
+    "schema": {
+      "const": "cpld-agent-analysis-index-v1"
+    },
+    "run_id": {
+      "type": "string",
+      "pattern": "^[0-9a-f]{32}$"
+    },
+    "created_at_utc": {
+      "type": "string",
+      "format": "date-time"
+    },
+    "package_name": {
+      "type": "string",
+      "minLength": 1
+    },
+    "status": {
+      "enum": [
+        "pass",
+        "pass_with_warnings"
+      ]
+    },
+    "max_zip_bytes": {
+      "type": "integer",
+      "minimum": 1
+    },
+    "target_zip_bytes": {
+      "type": "integer",
+      "minimum": 1
+    },
+    "sources": {
+      "type": "array",
+      "items": {
+        "type": "object",
+        "required": [
+          "id",
+          "status"
+        ],
+        "properties": {
+          "id": {
+            "type": "string"
+          },
+          "status": {
+            "enum": [
+              "pass",
+              "warning"
+            ]
+          }
+        },
+        "additionalProperties": true
+      }
+    },
+    "git": {
+      "type": "array",
+      "items": {
+        "type": "object"
+      }
+    },
+    "warnings": {
+      "type": "array",
+      "items": {
+        "type": "object"
+      }
+    },
+    "excluded": {
+      "type": "array",
+      "items": {
+        "$ref": "#/$defs/excluded"
+      }
+    },
+    "volumes": {
+      "type": "array",
+      "minItems": 1,
+      "items": {
+        "$ref": "#/$defs/volume"
+      }
+    },
+    "files": {
+      "type": "array",
+      "items": {
+        "$ref": "#/$defs/file"
+      }
+    },
+    "large_files": {
+      "type": "array",
+      "items": {
+        "$ref": "#/$defs/large_file"
+      }
+    }
+  },
+  "$defs": {
+    "sha256": {
+      "type": "string",
+      "pattern": "^[0-9a-f]{64}$"
+    },
+    "excluded": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": [
+        "path",
+        "rule"
+      ],
+      "properties": {
+        "path": {
+          "type": "string"
+        },
+        "rule": {
+          "type": "string"
+        }
+      }
+    },
+    "volume": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": [
+        "file",
+        "volume_number",
+        "volume_count",
+        "categories",
+        "file_count",
+        "uncompressed_bytes",
+        "compressed_bytes",
+        "sha256"
+      ],
+      "properties": {
+        "file": {
+          "type": "string"
+        },
+        "volume_number": {
+          "type": "integer",
+          "minimum": 1
+        },
+        "volume_count": {
+          "type": "integer",
+          "minimum": 1
+        },
+        "categories": {
+          "type": "array",
+          "items": {
+            "type": "string"
+          }
+        },
+        "file_count": {
+          "type": "integer",
+          "minimum": 0
+        },
+        "uncompressed_bytes": {
+          "type": "integer",
+          "minimum": 0
+        },
+        "compressed_bytes": {
+          "type": "integer",
+          "minimum": 1
+        },
+        "sha256": {
+          "$ref": "#/$defs/sha256"
+        }
+      }
+    },
+    "file": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": [
+        "path",
+        "archive_path",
+        "category",
+        "source_id",
+        "original_path",
+        "size",
+        "sha256",
+        "volume"
+      ],
+      "properties": {
+        "path": {
+          "type": "string"
+        },
+        "archive_path": {
+          "type": "string"
+        },
+        "category": {
+          "type": "string"
+        },
+        "source_id": {
+          "type": "string"
+        },
+        "original_path": {
+          "type": "string"
+        },
+        "size": {
+          "type": "integer",
+          "minimum": 0
+        },
+        "sha256": {
+          "$ref": "#/$defs/sha256"
+        },
+        "volume": {
+          "type": "string"
+        }
+      }
+    },
+    "chunk": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": [
+        "number",
+        "path",
+        "archive_path",
+        "size",
+        "sha256",
+        "volume"
+      ],
+      "properties": {
+        "number": {
+          "type": "integer",
+          "minimum": 1
+        },
+        "path": {
+          "type": "string"
+        },
+        "archive_path": {
+          "type": "string"
+        },
+        "size": {
+          "type": "integer",
+          "minimum": 1
+        },
+        "sha256": {
+          "$ref": "#/$defs/sha256"
+        },
+        "volume": {
+          "type": "string"
+        }
+      }
+    },
+    "large_file": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": [
+        "path",
+        "category",
+        "source_id",
+        "original_path",
+        "size",
+        "sha256",
+        "chunks"
+      ],
+      "properties": {
+        "path": {
+          "type": "string"
+        },
+        "category": {
+          "type": "string"
+        },
+        "source_id": {
+          "type": "string"
+        },
+        "original_path": {
+          "type": "string"
+        },
+        "size": {
+          "type": "integer",
+          "minimum": 1
+        },
+        "sha256": {
+          "$ref": "#/$defs/sha256"
+        },
+        "chunks": {
+          "type": "array",
+          "minItems": 2,
+          "items": {
+            "$ref": "#/$defs/chunk"
+          }
+        }
+      }
+    }
+  }
+}

+ 101 - 0
schemas/agent_analysis_handoff_sources.schema.json

@@ -0,0 +1,101 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "https://local.invalid/schemas/agent_analysis_handoff_sources.schema.json",
+  "title": "CPLD agent analysis source configuration",
+  "type": "object",
+  "additionalProperties": false,
+  "required": [
+    "schema",
+    "max_zip_bytes",
+    "target_zip_bytes",
+    "external_sources",
+    "extra_exclusions"
+  ],
+  "properties": {
+    "schema": {
+      "const": "cpld-agent-analysis-sources-v1"
+    },
+    "max_zip_bytes": {
+      "type": "integer",
+      "minimum": 1
+    },
+    "target_zip_bytes": {
+      "type": "integer",
+      "minimum": 1
+    },
+    "external_sources": {
+      "type": "array",
+      "items": {
+        "$ref": "#/$defs/source"
+      }
+    },
+    "extra_exclusions": {
+      "type": "array",
+      "items": {
+        "$ref": "#/$defs/exclusion"
+      }
+    }
+  },
+  "$defs": {
+    "source": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": [
+        "id",
+        "category",
+        "kind",
+        "path_candidates",
+        "archive_policy"
+      ],
+      "properties": {
+        "id": {
+          "type": "string",
+          "pattern": "^[a-z0-9][a-z0-9-]{0,63}$"
+        },
+        "category": {
+          "type": "string",
+          "minLength": 1
+        },
+        "kind": {
+          "enum": [
+            "directory",
+            "file",
+            "git_worktree"
+          ]
+        },
+        "path_candidates": {
+          "type": "array",
+          "minItems": 1,
+          "items": {
+            "type": "string",
+            "minLength": 1
+          }
+        },
+        "archive_policy": {
+          "enum": [
+            "inspect",
+            "copy"
+          ]
+        }
+      }
+    },
+    "exclusion": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": [
+        "path",
+        "reason"
+      ],
+      "properties": {
+        "path": {
+          "type": "string",
+          "minLength": 1
+        },
+        "reason": {
+          "type": "string",
+          "minLength": 1
+        }
+      }
+    }
+  }
+}

+ 237 - 0
schemas/board_viewer_annotations.schema.json

@@ -0,0 +1,237 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "https://local.invalid/schemas/board_viewer_annotations.schema.json",
+  "title": "Board viewer curated annotations",
+  "type": "object",
+  "additionalProperties": false,
+  "required": ["schema", "board_id", "connector_profiles", "touchpoints", "interfaces", "photo_overlay"],
+  "properties": {
+    "schema": {"const": "board-viewer-annotations-v1"},
+    "board_id": {"type": "string", "minLength": 1},
+    "connector_profiles": {
+      "type": "object",
+      "additionalProperties": {"$ref": "#/$defs/connectorProfile"}
+    },
+    "annotation_templates": {
+      "type": "object",
+      "additionalProperties": {"$ref": "#/$defs/touchpointAnnotation"}
+    },
+    "template_instances": {
+      "type": "object",
+      "additionalProperties": {"$ref": "#/$defs/templateInstance"}
+    },
+    "touchpoints": {
+      "type": "object",
+      "additionalProperties": {"$ref": "#/$defs/touchpointAnnotation"}
+    },
+    "interfaces": {
+      "type": "array",
+      "items": {"$ref": "#/$defs/interface"}
+    },
+    "photo_overlay": {
+      "oneOf": [
+        {"type": "null"},
+        {"$ref": "#/$defs/photoOverlay"}
+      ]
+    }
+  },
+  "$defs": {
+    "evidenceTier": {
+      "enum": ["board_database", "cross_verified", "name_inferred", "unknown"]
+    },
+    "touchpointAnnotation": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["summary", "pins"],
+      "properties": {
+        "summary": {"type": "string", "minLength": 1},
+        "pins": {
+          "type": "object",
+          "additionalProperties": {"$ref": "#/$defs/pinAnnotation"}
+        }
+      }
+    },
+    "templateInstance": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["template", "variables"],
+      "properties": {
+        "template": {"type": "string", "minLength": 1},
+        "variables": {
+          "type": "object",
+          "additionalProperties": {"type": "string"}
+        }
+      }
+    },
+    "connectorProfile": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["references", "contact_pins", "shield_pads", "evidence_tier", "sources"],
+      "properties": {
+        "component_value": {"type": "string"},
+        "references": {
+          "type": "array",
+          "minItems": 1,
+          "uniqueItems": true,
+          "items": {"type": "string", "pattern": "^(CON|J|PL)[0-9]+$"}
+        },
+        "contact_pins": {
+          "type": "array",
+          "minItems": 1,
+          "uniqueItems": true,
+          "items": {"type": "string", "minLength": 1}
+        },
+        "shield_pads": {
+          "type": "array",
+          "uniqueItems": true,
+          "items": {"type": "string", "minLength": 1}
+        },
+        "evidence_tier": {"$ref": "#/$defs/evidenceTier"},
+        "sources": {
+          "type": "array",
+          "minItems": 1,
+          "items": {"type": "string", "minLength": 1}
+        }
+      }
+    },
+    "pinAnnotation": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["summary", "path", "evidence_tier", "sources"],
+      "properties": {
+        "summary": {"type": "string", "minLength": 1},
+        "path": {"type": "array", "items": {"type": "string", "minLength": 1}},
+        "evidence_tier": {"$ref": "#/$defs/evidenceTier"},
+        "sources": {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1}},
+        "direction": {"enum": ["input", "output", "bidirectional", "passive", "unknown"]},
+        "external_level": {"type": "string", "minLength": 1},
+        "function_category": {"type": "string", "minLength": 1},
+        "reserved": {"type": "boolean"},
+        "fixed_load_conflict": {"type": "boolean"},
+        "board_pull": {"type": ["string", "null"]},
+        "adc_pulltype": {"type": ["string", "null"], "pattern": "^[A-Z][A-Z0-9_]*$"},
+        "active_level": {"type": "string", "minLength": 1},
+        "polarity": {"type": "string", "minLength": 1},
+        "external_components": {
+          "type": "array",
+          "items": {"type": "string", "minLength": 1}
+        },
+        "fpga": {"$ref": "#/$defs/fpgaAnnotation"},
+        "mcu": {"$ref": "#/$defs/mcuAnnotation"},
+        "programming": {"$ref": "#/$defs/programmingAnnotation"}
+      }
+    },
+    "fpgaAnnotation": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["ball", "board_signal", "io_standard", "capabilities", "evidence_tier", "sources"],
+      "properties": {
+        "ball": {"type": "string", "minLength": 1},
+        "board_signal": {"type": "string", "minLength": 1},
+        "io_standard": {"type": "string", "minLength": 1},
+        "capabilities": {
+          "type": "array",
+          "minItems": 1,
+          "items": {"type": "string", "minLength": 1}
+        },
+        "evidence_tier": {"$ref": "#/$defs/evidenceTier"},
+        "sources": {
+          "type": "array",
+          "minItems": 1,
+          "items": {"type": "string", "minLength": 1}
+        }
+      }
+    },
+    "mcuAnnotation": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["device", "family", "pin", "signal", "capabilities", "evidence_tier", "sources"],
+      "properties": {
+        "device": {"type": "string", "minLength": 1},
+        "family": {"type": "string", "minLength": 1},
+        "pin": {"type": "string", "minLength": 1},
+        "signal": {"type": "string", "minLength": 1},
+        "capabilities": {
+          "type": "array",
+          "minItems": 1,
+          "items": {"type": "string", "minLength": 1}
+        },
+        "evidence_tier": {"$ref": "#/$defs/evidenceTier"},
+        "sources": {
+          "type": "array",
+          "minItems": 1,
+          "items": {"type": "string", "minLength": 1}
+        }
+      }
+    },
+    "programmingAnnotation": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["evidence_tier", "sources"],
+      "properties": {
+        "status": {"enum": ["verified_fpga", "verified_mcu", "board_only", "not_programmable", "unknown"]},
+        "conclusion": {"type": "string", "minLength": 1},
+        "network_explanation": {"type": "string", "minLength": 1},
+        "hdl_guidance": {"type": "string", "minLength": 1},
+        "connection_guidance": {
+          "type": "array",
+          "minItems": 1,
+          "items": {"type": "string", "minLength": 1}
+        },
+        "constraints": {"type": "array", "items": {"type": "string", "minLength": 1}},
+        "risks": {"type": "array", "items": {"type": "string", "minLength": 1}},
+        "evidence_tier": {"$ref": "#/$defs/evidenceTier"},
+        "sources": {
+          "type": "array",
+          "minItems": 1,
+          "items": {"type": "string", "minLength": 1}
+        }
+      }
+    },
+    "interface": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["id", "name", "touchpoint", "pins", "external_level", "evidence_tier", "sources"],
+      "properties": {
+        "id": {"type": "string", "pattern": "^[a-z0-9-]+$"},
+        "name": {"type": "string", "minLength": 1},
+        "touchpoint": {"type": "string", "pattern": "^(CON|J|PL|TP)[0-9]+$"},
+        "pins": {"type": "array", "minItems": 1, "items": {"type": "string"}},
+        "external_level": {"type": "string", "minLength": 1},
+        "evidence_tier": {"$ref": "#/$defs/evidenceTier"},
+        "sources": {"type": "array", "minItems": 1, "items": {"type": "string", "minLength": 1}}
+      }
+    },
+    "photoOverlay": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["path", "sha256", "control_points"],
+      "properties": {
+        "path": {"type": "string", "minLength": 1},
+        "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
+        "control_points": {
+          "type": "array",
+          "minItems": 3,
+          "items": {
+            "type": "object",
+            "additionalProperties": false,
+            "required": ["image", "board"],
+            "properties": {
+              "image": {"$ref": "#/$defs/point"},
+              "board": {"$ref": "#/$defs/point"}
+            }
+          }
+        }
+      }
+    },
+    "point": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["x", "y"],
+      "properties": {
+        "x": {"type": "number"},
+        "y": {"type": "number"}
+      }
+    }
+  }
+}

+ 90 - 0
schemas/board_viewer_build_info.schema.json

@@ -0,0 +1,90 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "https://local.invalid/schemas/board_viewer_build_info.schema.json",
+  "title": "Board viewer generated asset manifest",
+  "type": "object",
+  "additionalProperties": false,
+  "required": ["schema", "generated_at", "generator_version", "toolchain", "sources", "assets", "verification", "counts"],
+  "properties": {
+    "schema": {"const": "board-viewer-build-info-v1"},
+    "generated_at": {"type": "string", "format": "date-time"},
+    "generator_version": {"type": "string", "minLength": 1},
+    "toolchain": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["python", "kicad"],
+      "properties": {
+        "python": {"type": "string", "minLength": 1},
+        "kicad": {"type": "string", "minLength": 1}
+      }
+    },
+    "sources": {
+      "type": "object",
+      "minProperties": 3,
+      "additionalProperties": {"$ref": "#/$defs/file"}
+    },
+    "assets": {
+      "type": "object",
+      "minProperties": 1,
+      "propertyNames": {"pattern": "^[^/\\\\]+$"},
+      "additionalProperties": {"$ref": "#/$defs/fileDigest"}
+    },
+    "verification": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["ipcd356"],
+      "properties": {
+        "ipcd356": {
+          "type": "object",
+          "additionalProperties": false,
+          "required": ["numbered_pads", "matched_pads", "record_types", "tolerance_mm"],
+          "properties": {
+            "numbered_pads": {"type": "integer", "minimum": 0},
+            "matched_pads": {"type": "integer", "minimum": 0},
+            "record_types": {
+              "type": "object",
+              "additionalProperties": false,
+              "required": ["317", "327"],
+              "properties": {
+                "317": {"type": "integer", "minimum": 0},
+                "327": {"type": "integer", "minimum": 0}
+              }
+            },
+            "tolerance_mm": {"type": "number", "exclusiveMinimum": 0}
+          }
+        }
+      }
+    },
+    "counts": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["footprints", "touchpoints", "pads"],
+      "properties": {
+        "footprints": {"type": "integer", "minimum": 0},
+        "touchpoints": {"type": "integer", "minimum": 0},
+        "pads": {"type": "integer", "minimum": 0}
+      }
+    }
+  },
+  "$defs": {
+    "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
+    "file": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["path", "sha256"],
+      "properties": {
+        "path": {"type": "string", "minLength": 1},
+        "sha256": {"$ref": "#/$defs/sha256"}
+      }
+    },
+    "fileDigest": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["sha256", "bytes"],
+      "properties": {
+        "sha256": {"$ref": "#/$defs/sha256"},
+        "bytes": {"type": "integer", "minimum": 0}
+      }
+    }
+  }
+}

+ 238 - 0
schemas/board_viewer_data.schema.json

@@ -0,0 +1,238 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "https://local.invalid/schemas/board_viewer_data.schema.json",
+  "title": "Generated board viewer data",
+  "type": "object",
+  "additionalProperties": false,
+  "required": ["schema", "board", "counts", "touchpoints", "interfaces", "photo_overlay"],
+  "properties": {
+    "schema": {"const": "board-viewer-data-v1"},
+    "board": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["id", "name", "source_bounds", "view_box"],
+      "properties": {
+        "id": {"type": "string", "minLength": 1},
+        "name": {"type": "string", "minLength": 1},
+        "source_bounds": {"$ref": "#/$defs/bounds"},
+        "view_box": {"$ref": "#/$defs/bounds"}
+      }
+    },
+    "counts": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["footprints", "touchpoints", "pads", "connector_contacts", "connector_auxiliary_pads", "categories", "sides"],
+      "properties": {
+        "footprints": {"type": "integer", "minimum": 0},
+        "touchpoints": {"type": "integer", "minimum": 0},
+        "pads": {"type": "integer", "minimum": 0},
+        "connector_contacts": {"type": "integer", "minimum": 0},
+        "connector_auxiliary_pads": {"type": "integer", "minimum": 0},
+        "categories": {"$ref": "#/$defs/countMap"},
+        "sides": {
+          "type": "object",
+          "additionalProperties": false,
+          "required": ["front", "back"],
+          "properties": {
+            "front": {"type": "integer", "minimum": 0},
+            "back": {"type": "integer", "minimum": 0}
+          }
+        }
+      }
+    },
+    "touchpoints": {"type": "array", "items": {"$ref": "#/$defs/touchpoint"}},
+    "interfaces": {"type": "array", "items": {"type": "object"}},
+    "photo_overlay": {
+      "oneOf": [
+        {"type": "null"},
+        {
+          "type": "object",
+          "additionalProperties": false,
+          "required": ["asset", "sha256", "matrix", "control_point_count"],
+          "properties": {
+            "asset": {"type": "string", "pattern": "^board-photo\\.(png|jpg|jpeg|webp)$"},
+            "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
+            "matrix": {
+              "type": "array",
+              "minItems": 6,
+              "maxItems": 6,
+              "items": {"type": "number"}
+            },
+            "control_point_count": {"type": "integer", "minimum": 3}
+          }
+        }
+      ]
+    }
+  },
+  "$defs": {
+    "countMap": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["CON", "J", "PL", "TP"],
+      "properties": {
+        "CON": {"type": "integer", "minimum": 0},
+        "J": {"type": "integer", "minimum": 0},
+        "PL": {"type": "integer", "minimum": 0},
+        "TP": {"type": "integer", "minimum": 0}
+      }
+    },
+    "point": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["x", "y"],
+      "properties": {"x": {"type": "number"}, "y": {"type": "number"}}
+    },
+    "bounds": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["x", "y", "width", "height"],
+      "properties": {
+        "x": {"type": "number"},
+        "y": {"type": "number"},
+        "width": {"type": "number", "minimum": 0},
+        "height": {"type": "number", "minimum": 0}
+      }
+    },
+    "evidenceTier": {"enum": ["board_database", "cross_verified", "name_inferred", "unknown"]},
+    "fpga": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["ball", "board_signal", "io_standard", "capabilities", "evidence_tier", "sources"],
+      "properties": {
+        "ball": {"type": "string"},
+        "board_signal": {"type": "string"},
+        "io_standard": {"type": "string"},
+        "capabilities": {"type": "array", "items": {"type": "string"}},
+        "evidence_tier": {"$ref": "#/$defs/evidenceTier"},
+        "sources": {"type": "array", "items": {"type": "string"}}
+      }
+    },
+    "mcu": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["device", "family", "pin", "signal", "capabilities", "evidence_tier", "sources"],
+      "properties": {
+        "device": {"type": "string", "minLength": 1},
+        "family": {"type": "string", "minLength": 1},
+        "pin": {"type": "string", "minLength": 1},
+        "signal": {"type": "string", "minLength": 1},
+        "capabilities": {"type": "array", "items": {"type": "string", "minLength": 1}},
+        "evidence_tier": {"$ref": "#/$defs/evidenceTier"},
+        "sources": {"type": "array", "items": {"type": "string", "minLength": 1}}
+      }
+    },
+    "pin": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["id", "number", "pad_role", "row", "column", "board_order", "mechanical", "electrical", "net", "position", "view_position", "size", "rotation", "shape", "layers", "direction", "external_level", "function_category", "reserved", "fixed_load_conflict", "board_pull", "adc_pulltype", "active_level", "polarity", "external_components", "summary", "path", "evidence_tier", "evidence_sources", "fpga", "mcu", "programming", "recommendation"],
+      "properties": {
+        "id": {"type": "string", "minLength": 1},
+        "number": {"type": "string"},
+        "pad_role": {"enum": ["contact", "shield", "mechanical", "unknown"]},
+        "row": {"type": ["integer", "null"], "minimum": 1},
+        "column": {"type": ["integer", "null"], "minimum": 1},
+        "board_order": {"type": ["integer", "null"], "minimum": 1},
+        "mechanical": {"type": "boolean"},
+        "electrical": {"type": "boolean"},
+        "net": {"type": ["string", "null"]},
+        "position": {"$ref": "#/$defs/point"},
+        "view_position": {"$ref": "#/$defs/point"},
+        "size": {
+          "type": "object",
+          "additionalProperties": false,
+          "required": ["width", "height", "drill_width", "drill_height"],
+          "properties": {
+            "width": {"type": "number", "minimum": 0},
+            "height": {"type": "number", "minimum": 0},
+            "drill_width": {"type": "number", "minimum": 0},
+            "drill_height": {"type": "number", "minimum": 0}
+          }
+        },
+        "rotation": {"type": "number"},
+        "shape": {"type": "string"},
+        "layers": {"type": "array", "items": {"type": "string"}},
+        "direction": {"enum": ["input", "output", "bidirectional", "passive", "unknown"]},
+        "external_level": {"type": "string"},
+        "function_category": {"type": "string"},
+        "reserved": {"type": "boolean"},
+        "fixed_load_conflict": {"type": "boolean"},
+        "board_pull": {"type": ["string", "null"]},
+        "adc_pulltype": {"type": ["string", "null"], "pattern": "^[A-Z][A-Z0-9_]*$"},
+        "active_level": {"type": "string", "minLength": 1},
+        "polarity": {"type": "string", "minLength": 1},
+        "external_components": {"type": "array", "items": {"type": "string", "minLength": 1}},
+        "summary": {"type": "string"},
+        "path": {"type": "array", "items": {"type": "string"}},
+        "evidence_tier": {"$ref": "#/$defs/evidenceTier"},
+        "evidence_sources": {"type": "array", "items": {"type": "string"}},
+        "fpga": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/fpga"}]},
+        "mcu": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/mcu"}]},
+        "programming": {"$ref": "#/$defs/programming"},
+        "recommendation": {
+          "type": "object",
+          "additionalProperties": false,
+          "required": ["eligible", "reasons"],
+          "properties": {
+            "eligible": {"type": "boolean"},
+            "reasons": {"type": "array", "items": {"type": "string"}}
+          }
+        }
+      }
+    },
+    "programming": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["status", "conclusion", "network_explanation", "hdl_guidance", "connection_guidance", "constraints", "risks", "evidence_tier", "sources"],
+      "properties": {
+        "status": {"enum": ["verified_fpga", "verified_mcu", "board_only", "not_programmable", "unknown"]},
+        "conclusion": {"type": "string", "minLength": 1},
+        "network_explanation": {"type": "string", "minLength": 1},
+        "hdl_guidance": {"type": "string", "minLength": 1},
+        "connection_guidance": {"type": "array", "items": {"type": "string", "minLength": 1}},
+        "constraints": {"type": "array", "items": {"type": "string", "minLength": 1}},
+        "risks": {"type": "array", "items": {"type": "string", "minLength": 1}},
+        "evidence_tier": {"$ref": "#/$defs/evidenceTier"},
+        "sources": {"type": "array", "items": {"type": "string", "minLength": 1}}
+      }
+    },
+    "connector": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["profile", "review_status", "view", "contact_count", "auxiliary_pad_count", "rows", "columns", "contact_grid", "contact_order", "sources"],
+      "properties": {
+        "profile": {"type": ["string", "null"]},
+        "review_status": {"$ref": "#/$defs/evidenceTier"},
+        "view": {"const": "board_front"},
+        "contact_count": {"type": "integer", "minimum": 0},
+        "auxiliary_pad_count": {"type": "integer", "minimum": 0},
+        "rows": {"type": "integer", "minimum": 0},
+        "columns": {"type": "integer", "minimum": 0},
+        "contact_grid": {
+          "type": "array",
+          "items": {"type": "array", "items": {"type": "string", "minLength": 1}}
+        },
+        "contact_order": {"type": "array", "items": {"type": "string", "minLength": 1}},
+        "sources": {"type": "array", "items": {"type": "string", "minLength": 1}}
+      }
+    },
+    "touchpoint": {
+      "type": "object",
+      "additionalProperties": false,
+      "required": ["reference", "category", "component_value", "position", "view_position", "rotation", "bounds", "view_bounds", "side", "summary", "connector", "pins"],
+      "properties": {
+        "reference": {"type": "string", "pattern": "^(CON|J|PL|TP)[0-9]+$"},
+        "category": {"enum": ["CON", "J", "PL", "TP"]},
+        "component_value": {"type": "string"},
+        "position": {"$ref": "#/$defs/point"},
+        "view_position": {"$ref": "#/$defs/point"},
+        "rotation": {"type": "number"},
+        "bounds": {"$ref": "#/$defs/bounds"},
+        "view_bounds": {"$ref": "#/$defs/bounds"},
+        "side": {"enum": ["front", "back"]},
+        "summary": {"type": "string"},
+        "connector": {"oneOf": [{"type": "null"}, {"$ref": "#/$defs/connector"}]},
+        "pins": {"type": "array", "items": {"$ref": "#/$defs/pin"}}
+      }
+    }
+  }
+}

+ 80 - 0
schemas/cpld_c_drive_audit.schema.json

@@ -0,0 +1,80 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "https://local.invalid/schemas/cpld_c_drive_audit.schema.json",
+  "title": "CPLD C-drive read-only audit output",
+  "oneOf": [
+    {
+      "type": "object",
+      "properties": {
+        "schema": {"const": "cpld-c-drive-audit-v1"},
+        "command": {"const": "scan"},
+        "generated_at": {"type": "string"},
+        "roots": {"type": "array", "items": {"type": "string"}},
+        "records": {"type": "array", "items": {"$ref": "#/$defs/record"}}
+      },
+      "required": ["schema", "command", "generated_at", "roots", "records"],
+      "additionalProperties": true
+    },
+    {
+      "type": "object",
+      "properties": {
+        "schema": {"const": "cpld-c-drive-audit-v1"},
+        "command": {"const": "compare-archives"},
+        "generated_at": {"type": "string"},
+        "archive": {"$ref": "#/$defs/record"},
+        "directory": {"$ref": "#/$defs/record"},
+        "comparison": {
+          "type": "object",
+          "properties": {
+            "status": {"enum": ["full_coverage", "mismatch", "unsafe"]},
+            "recommended_action": {"type": "string"},
+            "members": {"type": "array", "items": {"$ref": "#/$defs/member"}}
+          },
+          "required": ["status", "recommended_action", "members"],
+          "additionalProperties": true
+        }
+      },
+      "required": ["schema", "command", "generated_at", "archive", "directory", "comparison"],
+      "additionalProperties": true
+    }
+  ],
+  "$defs": {
+    "record": {
+      "type": "object",
+      "properties": {
+        "absolute_path": {"type": ["string", "null"]},
+        "resolved_path": {"type": ["string", "null"]},
+        "size": {"type": ["integer", "null"], "minimum": 0},
+        "git_common_dir": {"type": ["string", "null"]},
+        "worktree_dirty": {"type": "boolean"},
+        "reparse_point": {"type": "boolean"},
+        "ownership_evidence": {"type": "array", "items": {"type": "string"}},
+        "sha256": {"type": ["string", "null"]},
+        "comparison_target": {"type": ["string", "null"]},
+        "comparison_result": {"type": "string"},
+        "classification": {"type": "string"},
+        "recommended_action": {"type": "string"},
+        "reason": {"type": "string"}
+      },
+      "required": [
+        "absolute_path", "resolved_path", "size", "git_common_dir", "worktree_dirty",
+        "reparse_point", "ownership_evidence", "sha256", "comparison_target",
+        "comparison_result", "classification", "recommended_action", "reason"
+      ],
+      "additionalProperties": true
+    },
+    "member": {
+      "allOf": [
+        {"$ref": "#/$defs/record"},
+        {
+          "type": "object",
+          "properties": {
+            "member_path": {"type": "string"},
+            "target_size": {"type": ["integer", "null"], "minimum": 0}
+          },
+          "required": ["member_path", "target_size"]
+        }
+      ]
+    }
+  }
+}

+ 28 - 0
schemas/cpld_c_drive_audit_config.schema.json

@@ -0,0 +1,28 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "https://local.invalid/schemas/cpld_c_drive_audit_config.schema.json",
+  "title": "CPLD C-drive audit configuration",
+  "type": "object",
+  "properties": {
+    "$schema": {"type": "string"},
+    "schema": {"const": "cpld-c-drive-audit-config-v1"},
+    "scan_roots": {
+      "type": "array",
+      "items": {
+        "type": "object",
+        "properties": {
+          "path": {"type": "string", "minLength": 1},
+          "scope": {"type": "string", "minLength": 1}
+        },
+        "required": ["path", "scope"],
+        "additionalProperties": false
+      }
+    },
+    "candidate_patterns": {"type": "array", "items": {"type": "string"}},
+    "excluded_patterns": {"type": "array", "items": {"type": "string"}},
+    "protected_patterns": {"type": "array", "items": {"type": "string"}},
+    "max_files": {"type": "integer", "minimum": 1}
+  },
+  "required": ["schema", "scan_roots", "candidate_patterns", "excluded_patterns", "protected_patterns", "max_files"],
+  "additionalProperties": false
+}

+ 423 - 0
tests/board_viewer/board-logic.test.mjs

@@ -0,0 +1,423 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import {readFileSync} from "node:fs";
+
+import {
+  connectorPinGroups,
+  findCandidates,
+  generateAdcSnippet,
+  isValidRtlPortName,
+  sameNetPins,
+  searchBoard,
+} from "../../tools/board-viewer/web/board-logic.mjs";
+
+
+function pin(overrides = {}) {
+  return {
+    id: "fixture-pin",
+    number: "1",
+    pad_role: "contact",
+    net: "UART_A_TX",
+    summary: "UART transmit",
+    path: ["CON10.1", "UART_A_TX", "FPGA A1"],
+    mechanical: false,
+    electrical: true,
+    direction: "output",
+    external_level: "3.3V LVCMOS",
+    function_category: "uart_tx",
+    reserved: false,
+    fixed_load_conflict: false,
+    board_pull: null,
+    adc_pulltype: null,
+    programming: {
+      status: "verified_fpga",
+      conclusion: "FPGA 输出 UART_A_TX",
+      network_explanation: "连接器网络 UART_A_TX 直达 FPGA",
+      hdl_guidance: "RTL 端口方向应为 output",
+      connection_guidance: ["连接到对端设备的接收端(RX)。"],
+      constraints: ["LOCATION = A1", "IOSTANDARD = LVCMOS33"],
+      risks: ["仍需检查当前工程约束冲突。"],
+      evidence_tier: "cross_verified",
+      sources: ["fixture"],
+    },
+    evidence_tier: "cross_verified",
+    fpga: {
+      ball: "A1",
+      board_signal: "UART_A_TX",
+      io_standard: "LVCMOS33",
+      capabilities: ["gpio", "uart_tx"],
+      evidence_tier: "cross_verified",
+      sources: ["fixture"],
+    },
+    recommendation: {eligible: true, reasons: []},
+    ...overrides,
+  };
+}
+
+
+function boardData() {
+  return {
+    touchpoints: [
+      {
+        reference: "CON78",
+        category: "CON",
+        summary: "UART2 RS-232 connector through U23",
+        pins: [
+          pin({
+            number: "1",
+            net: "RS232_TX2",
+            path: ["CON78.1 RS232_TX2", "U23", "UART2_TX", "FPGA M10"],
+            external_level: "RS232",
+            reserved: true,
+            fpga: {
+              ball: "M10",
+              board_signal: "UART2_TX",
+              io_standard: "LVCMOS33",
+              capabilities: ["gpio", "uart_tx", "rs232_via_transceiver"],
+              evidence_tier: "cross_verified",
+              sources: ["fixture"],
+            },
+            recommendation: {eligible: false, reasons: ["reserved"]},
+            programming: {
+              status: "verified_fpga",
+              conclusion: "FPGA 输出 UART2_TX 经 U23 转为 RS-232",
+              network_explanation: "连接器侧网络 RS232_TX2 对应逻辑侧 UART2_TX",
+              hdl_guidance: "RTL 端口方向应为 output",
+              connection_guidance: ["连接到对端设备的接收端(RX)。", "不能直接接 3.3V TTL/CMOS 串口。"],
+              constraints: ["LOCATION = M10", "IOSTANDARD = LVCMOS33"],
+              risks: ["当前功能已保留。"],
+              evidence_tier: "cross_verified",
+              sources: ["fixture"],
+            },
+          }),
+        ],
+      },
+      {
+        reference: "CON10",
+        category: "CON",
+        summary: "Verified UART fixture",
+        pins: [pin()],
+      },
+      {
+        reference: "J2",
+        category: "J",
+        summary: "PWM fixture",
+        pins: [
+          pin({
+            number: "7",
+            net: "FAN_PWM_TEST",
+            summary: "Fan PWM",
+            function_category: "pwm",
+            board_pull: "10k external pull-up to 3.3V",
+            fpga: {
+              ball: "B2",
+              board_signal: "FAN_PWM_TEST",
+              io_standard: "LVCMOS33",
+              capabilities: ["gpio", "gpio_output", "pwm"],
+              evidence_tier: "cross_verified",
+              sources: ["fixture"],
+            },
+          }),
+          pin({
+            number: "8",
+            net: "FAN_PWM_PULLTYPE",
+            function_category: "pwm",
+            adc_pulltype: "PULLUP",
+            fpga: {
+              ball: "B3",
+              board_signal: "FAN_PWM_PULLTYPE",
+              io_standard: "LVCMOS33",
+              capabilities: ["gpio", "gpio_output", "pwm"],
+              evidence_tier: "cross_verified",
+              sources: ["fixture"],
+            },
+          }),
+        ],
+      },
+      {
+        reference: "TP3",
+        category: "TP",
+        summary: "Unverified test point",
+        pins: [
+          pin({
+            net: "MYSTERY",
+            external_level: "unknown",
+            evidence_tier: "unknown",
+            fpga: null,
+            recommendation: {eligible: false, reasons: ["pin_evidence_not_verified"]},
+          }),
+        ],
+      },
+    ],
+  };
+}
+
+
+test("search covers reference, pin, net, function, capability, and FPGA ball", () => {
+  const data = boardData();
+
+  assert.equal(searchBoard(data, "CON78")[0].reference, "CON78");
+  assert.equal(searchBoard(data, "CON78.1")[0].pinNumber, "1");
+  assert.equal(searchBoard(data, "rs232_tx2")[0].reference, "CON78");
+  assert.equal(searchBoard(data, "uart_tx")[0].reference, "CON10");
+  assert.equal(searchBoard(data, "rs232_via_transceiver")[0].reference, "CON78");
+  assert.equal(searchBoard(data, "m10")[0].pinNumber, "1");
+  assert.ok(searchBoard(data, "对端设备的接收端").some((result) => result.reference === "CON78"));
+  assert.equal(searchBoard(data, "不能直接接 3.3v ttl")[0].reference, "CON78");
+  assert.deepEqual(searchBoard(data, "does-not-exist"), []);
+});
+
+
+test("search covers verified MCU device, package pin, signal, and capability", () => {
+  const data = boardData();
+  const mcuPin = data.touchpoints.find((item) => item.reference === "TP3").pins[0];
+  mcuPin.summary = "GD32 firmware test point";
+  mcuPin.path = [];
+  mcuPin.programming = {
+    status: "verified_mcu",
+    conclusion: "Verified MCU test point",
+    network_explanation: "Verified MCU path",
+    hdl_guidance: "Use from firmware",
+    connection_guidance: [],
+    constraints: [],
+    risks: [],
+    evidence_tier: "cross_verified",
+    sources: ["fixture"],
+  };
+  mcuPin.mcu = {
+    device: "U27",
+    family: "GD32F303CGT6",
+    pin: "10",
+    signal: "PA0",
+    capabilities: ["gpio", "adc_input"],
+    evidence_tier: "cross_verified",
+    sources: ["fixture"],
+  };
+
+  assert.equal(searchBoard(data, "u27.10")[0].reference, "TP3");
+  assert.equal(searchBoard(data, "gd32f303")[0].reference, "TP3");
+  assert.equal(searchBoard(data, "pa0")[0].reference, "TP3");
+  assert.equal(searchBoard(data, "adc_input")[0].reference, "TP3");
+  assert.ok(!findCandidates(data, "gpio").some((item) => item.reference === "TP3"));
+});
+
+
+test("same-net lookup returns every matching pad and ignores empty nets", () => {
+  const data = boardData();
+  data.touchpoints[1].pins.push(pin({number: "2", net: "RS232_TX2"}));
+
+  assert.deepEqual(
+    sameNetPins(data, "RS232_TX2").map((item) => `${item.reference}.${item.pinNumber}`),
+    ["CON10.2", "CON78.1"],
+  );
+  assert.deepEqual(sameNetPins(data, ""), []);
+});
+
+
+test("candidate filtering is fail-closed and sorted by natural reference and pin", () => {
+  const candidates = findCandidates(boardData(), "uart_tx");
+
+  assert.deepEqual(candidates.map((item) => `${item.reference}.${item.pin.number}`), ["CON10.1"]);
+  assert.match(candidates[0].reason, /已验证 FPGA 路径/);
+  assert.match(candidates[0].warning, /当前工程约束冲突/);
+});
+
+
+test("candidate filters recognize canonical board capability aliases", () => {
+  const aliases = [
+    ["pwm", "pwm_output"],
+    ["gpio_output", "digital_output"],
+    ["gpio_input", "digital_input"],
+    ["tach", "tach_input"],
+    ["fan_tach", "tach_input"],
+    ["presence", "presence_input"],
+  ];
+
+  for (const [filter, capability] of aliases) {
+    const data = {
+      touchpoints: [{
+        reference: "CON1",
+        category: "CON",
+        summary: "Alias fixture",
+        pins: [pin({
+          fpga: {
+            ball: "A1",
+            board_signal: "ALIAS_SIGNAL",
+            io_standard: "LVCMOS33",
+            capabilities: ["gpio", capability],
+            evidence_tier: "cross_verified",
+            sources: ["fixture"],
+          },
+        })],
+      }],
+    };
+    assert.equal(findCandidates(data, filter).length, 1, `${filter} -> ${capability}`);
+  }
+});
+
+
+test("generic GPIO candidates exclude dedicated tach, PWM, presence, and protocol pins", () => {
+  const data = {
+    touchpoints: [{
+      reference: "CON1",
+      category: "CON",
+      summary: "Mixed GPIO fixture",
+      pins: [
+        pin({number: "1", function_category: "gpio", summary: "Direct bidirectional GPIO"}),
+        pin({number: "2", function_category: "fan_tach", summary: "Fan tach input"}),
+        pin({number: "3", function_category: "pwm", summary: "Open-collector PWM"}),
+        pin({number: "4", function_category: "presence", summary: "Presence input"}),
+      ],
+    }],
+  };
+
+  assert.deepEqual(
+    findCandidates(data, "gpio").map((item) => `${item.reference}.${item.pin.number}`),
+    ["CON1.1"],
+  );
+});
+
+
+test("candidate reason exposes the pin purpose and non-default polarity", () => {
+  const data = {
+    touchpoints: [{
+      reference: "CON31",
+      category: "CON",
+      summary: "Fan connector",
+      pins: [pin({
+        function_category: "pwm",
+        summary: "风扇 PWM 开集电极下拉输出",
+        active_level: "connector low",
+        polarity: "FPGA high -> connector low",
+        fpga: {
+          ball: "E10",
+          board_signal: "FAN_GPIO6",
+          io_standard: "LVCMOS33",
+          capabilities: ["gpio", "pwm_output", "fan_pwm"],
+          evidence_tier: "cross_verified",
+          sources: ["fixture"],
+        },
+      })],
+    }],
+  };
+
+  const [candidate] = findCandidates(data, "pwm");
+  assert.match(candidate.reason, /风扇 PWM 开集电极下拉输出/);
+  assert.match(candidate.reason, /FPGA high -> connector low/);
+});
+
+
+test("product candidate filters keep dedicated functions out of generic GPIO", () => {
+  const data = JSON.parse(readFileSync(
+    new URL("../../tools/board-viewer/generated/board-data.json", import.meta.url),
+    "utf8",
+  ));
+
+  assert.equal(findCandidates(data, "gpio").length, 33);
+  assert.equal(findCandidates(data, "pwm").length, 43);
+  assert.equal(findCandidates(data, "gpio_output").length, 33);
+  assert.equal(findCandidates(data, "gpio_input").length, 51);
+  assert.equal(findCandidates(data, "tach").length, 14);
+  assert.equal(findCandidates(data, "presence").length, 4);
+  assert.equal(findCandidates(data, "uart_tx").length, 0);
+  assert.ok(findCandidates(data, "gpio").every((item) => item.pin.function_category === "gpio"));
+});
+
+
+test("unknown, inferred, power, ground, mechanical, reserved, and fixed-load pins are never candidates", () => {
+  const blockers = [
+    {evidence_tier: "unknown"},
+    {evidence_tier: "name_inferred"},
+    {function_category: "power", net: "+3V3"},
+    {function_category: "ground", net: "GND"},
+    {mechanical: true, electrical: false},
+    {pad_role: "shield"},
+    {pad_role: "unknown"},
+    {reserved: true},
+    {fixed_load_conflict: true},
+  ];
+  for (const [index, override] of blockers.entries()) {
+    const data = {touchpoints: [{reference: `J${index + 1}`, category: "J", summary: "", pins: [pin(override)]}]};
+    assert.deepEqual(findCandidates(data, "uart_tx"), []);
+  }
+});
+
+
+test("connector groups follow reviewed board-front order and separate auxiliary pads", () => {
+  const touchpoint = {
+    reference: "CON78",
+    connector: {
+      review_status: "cross_verified",
+      contact_order: ["1", "2", "3", "4"],
+      contact_grid: [["1"], ["2"], ["3"], ["4"]],
+    },
+    pins: [
+      pin({id: "shield-5", number: "5", pad_role: "shield"}),
+      pin({id: "contact-4", number: "4"}),
+      pin({id: "contact-2", number: "2"}),
+      pin({id: "mechanical-1", number: "", pad_role: "mechanical", mechanical: true, electrical: false}),
+      pin({id: "contact-1", number: "1"}),
+      pin({id: "contact-3", number: "3"}),
+    ],
+  };
+
+  const groups = connectorPinGroups(touchpoint);
+
+  assert.deepEqual(groups.contactRows.map((row) => row.map((item) => item.number)), [["1"], ["2"], ["3"], ["4"]]);
+  assert.deepEqual(groups.contacts.map((item) => item.number), ["1", "2", "3", "4"]);
+  assert.deepEqual(groups.auxiliary.map((item) => item.id), ["shield-5", "mechanical-1"]);
+});
+
+
+test("unknown connector layout never invents contact ordering", () => {
+  const touchpoint = {
+    reference: "CON1",
+    connector: {review_status: "unknown", contact_order: [], contact_grid: []},
+    pins: [pin({id: "unknown-1", pad_role: "unknown"})],
+  };
+
+  assert.deepEqual(connectorPinGroups(touchpoint), {
+    contactRows: [],
+    contacts: [],
+    auxiliary: [touchpoint.pins[0]],
+  });
+});
+
+
+test("RTL port names reject syntax that could escape an ADC assignment", () => {
+  for (const name of ["uart_tx", "fan_pwm_out[3]", "_debug$signal"]) {
+    assert.equal(isValidRtlPortName(name), true, name);
+  }
+  for (const name of ["", "3bad", "a b", "a;set", "name[foo]", "{signal}", "a\nnext"]) {
+    assert.equal(isValidRtlPortName(name), false, name);
+  }
+});
+
+
+test("ADC generation requires current verified eligible data and omits implicit PULLTYPE", () => {
+  const data = boardData();
+  const pwm = data.touchpoints[2].pins[0];
+  const snippet = generateAdcSnippet(pwm, "fan_pwm_out[3]", {adcCopyEnabled: true});
+
+  assert.equal(
+    snippet,
+    "set_pin_assignment { fan_pwm_out[3] } { LOCATION = B2; IOSTANDARD = LVCMOS33; }",
+  );
+  assert.doesNotMatch(snippet, /PULLTYPE/);
+  assert.throws(() => generateAdcSnippet(pwm, "a;bad", {adcCopyEnabled: true}), /合法的 RTL 端口名/);
+  assert.throws(() => generateAdcSnippet(pwm, "fan_pwm_out", {adcCopyEnabled: false}), /源数据已过期/);
+  assert.throws(
+    () => generateAdcSnippet(data.touchpoints[0].pins[0], "uart2_tx", {adcCopyEnabled: true}),
+    /不具备 ADC 生成资格/,
+  );
+});
+
+
+test("ADC generation includes PULLTYPE only when curated annotation explicitly supplies it", () => {
+  const pinWithPulltype = boardData().touchpoints[2].pins[1];
+
+  assert.equal(
+    generateAdcSnippet(pinWithPulltype, "fan_pwm_aux", {adcCopyEnabled: true}),
+    "set_pin_assignment { fan_pwm_aux } { LOCATION = B3; IOSTANDARD = LVCMOS33; PULLTYPE = PULLUP; }",
+  );
+});

+ 118 - 0
tests/board_viewer/fixtures/connector_layouts.kicad_pcb

@@ -0,0 +1,118 @@
+(kicad_pcb
+  (version 20250114)
+  (generator pcbnew)
+  (gr_rect (start 0 0) (end 180 40) (stroke (width 0.05) (type default)) (fill none) (layer "Edge.Cuts"))
+
+  (footprint "Fixture:4P-A"
+    (layer "F.Cu")
+    (at 10 20 -90)
+    (property "Reference" "CON1")
+    (property "Component Value" "CON_11251W00_NPX_SX_4P")
+    (pad "1" smd rect (at 1.875 -1.8 270) (size 0.8 1.6) (layers "F.Cu" "F.Mask") (net 1 "P1"))
+    (pad "2" smd rect (at 0.625 -1.8 270) (size 0.8 1.6) (layers "F.Cu" "F.Mask") (net 2 "P2"))
+    (pad "3" smd rect (at -0.625 -1.8 270) (size 0.8 1.6) (layers "F.Cu" "F.Mask") (net 3 "P3"))
+    (pad "4" smd rect (at -1.875 -1.8 270) (size 0.8 1.6) (layers "F.Cu" "F.Mask") (net 4 "P4"))
+    (pad "5" smd rect (at 4.425 1.1 270) (size 2.1 3.0) (layers "F.Cu" "F.Mask") (net 5 "GND"))
+    (pad "6" smd rect (at -4.425 1.1 270) (size 2.1 3.0) (layers "F.Cu" "F.Mask") (net 5 "GND"))
+  )
+
+  (footprint "Fixture:4P-B"
+    (layer "F.Cu")
+    (at 30 20 90)
+    (property "Reference" "CON2")
+    (property "Component Value" "CON_11251W00_NPX_SX_4P")
+    (pad "1" smd rect (at 1.875 -1.8 90) (size 0.8 1.6) (layers "F.Cu" "F.Mask") (net 1 "P1"))
+    (pad "2" smd rect (at 0.625 -1.8 90) (size 0.8 1.6) (layers "F.Cu" "F.Mask") (net 2 "P2"))
+    (pad "3" smd rect (at -0.625 -1.8 90) (size 0.8 1.6) (layers "F.Cu" "F.Mask") (net 3 "P3"))
+    (pad "4" smd rect (at -1.875 -1.8 90) (size 0.8 1.6) (layers "F.Cu" "F.Mask") (net 4 "P4"))
+    (pad "5" smd rect (at 4.425 1.1 90) (size 2.1 3.0) (layers "F.Cu" "F.Mask") (net 5 "GND"))
+    (pad "6" smd rect (at -4.425 1.1 90) (size 2.1 3.0) (layers "F.Cu" "F.Mask") (net 5 "GND"))
+  )
+
+  (footprint "Fixture:3P"
+    (layer "F.Cu")
+    (at 50 20 180)
+    (property "Reference" "CON3")
+    (property "Component Value" "CON_51541_003_P1D25")
+    (pad "1" smd rect (at -1.25 -1.7 180) (size 0.6 1.7) (layers "F.Cu" "F.Mask") (net 1 "P1"))
+    (pad "2" smd rect (at 0 -1.7 180) (size 0.6 1.7) (layers "F.Cu" "F.Mask") (net 5 "GND"))
+    (pad "3" smd rect (at 1.25 -1.7 180) (size 0.6 1.7) (layers "F.Cu" "F.Mask") (net 3 "P3"))
+    (pad "4" smd rect (at 3.1 1.375 180) (size 1.0 2.4) (layers "F.Cu" "F.Mask") (net 5 "GND"))
+    (pad "5" smd rect (at -3.1 1.375 180) (size 1.0 2.4) (layers "F.Cu" "F.Mask") (net 5 "GND"))
+  )
+
+  (footprint "Fixture:14P"
+    (layer "F.Cu")
+    (at 75 20 180)
+    (property "Reference" "CON4")
+    (property "Component Value" "CON_3110_14P_P2D54")
+    (pad "1" smd rect (at -7.62 3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 1 "P1"))
+    (pad "2" smd rect (at -7.62 -3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 2 "P2"))
+    (pad "3" smd rect (at -5.08 3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 3 "P3"))
+    (pad "4" smd rect (at -5.08 -3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 4 "P4"))
+    (pad "5" smd rect (at -2.54 3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 5 "P5"))
+    (pad "6" smd rect (at -2.54 -3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 6 "P6"))
+    (pad "7" smd rect (at 0 3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 7 "P7"))
+    (pad "8" smd rect (at 0 -3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 8 "P8"))
+    (pad "9" smd rect (at 2.54 3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 9 "P9"))
+    (pad "10" smd rect (at 2.54 -3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 10 "P10"))
+    (pad "11" smd rect (at 5.08 3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 11 "P11"))
+    (pad "12" smd rect (at 5.08 -3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 12 "P12"))
+    (pad "13" smd rect (at 7.62 3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 13 "P13"))
+    (pad "14" smd rect (at 7.62 -3 180) (size 1 4.5) (layers "F.Cu" "F.Mask") (net 14 "P14"))
+  )
+
+  (footprint "Fixture:Power-A"
+    (layer "F.Cu")
+    (at 105 20 90)
+    (property "Reference" "CON5")
+    (property "Component Value" "CON_C22930_1084N_X")
+    (pad "" np_thru_hole circle (at -7.5 -2.44 90) (size 0 0) (drill 1) (layers "*.Cu" "*.Mask"))
+    (pad "" np_thru_hole circle (at 7.5 -2.44 90) (size 0 0) (drill 1) (layers "*.Cu" "*.Mask"))
+    (pad "1" thru_hole circle (at 4.5 1.5 90) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 1 "P1"))
+    (pad "2" thru_hole circle (at 1.5 1.5 90) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 2 "P2"))
+    (pad "3" thru_hole circle (at -1.5 1.5 90) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 3 "P3"))
+    (pad "4" thru_hole circle (at -4.5 1.5 90) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 4 "P4"))
+    (pad "5" thru_hole circle (at 4.5 -1.5 90) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 5 "P5"))
+    (pad "6" thru_hole circle (at 1.5 -1.5 90) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 6 "P6"))
+    (pad "7" thru_hole circle (at -1.5 -1.5 90) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 7 "P7"))
+    (pad "8" thru_hole circle (at -4.5 -1.5 90) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 8 "P8"))
+    (pad "9" thru_hole rect (at 6.65 0 90) (size 1.3 3) (drill 1) (layers "*.Cu" "*.Mask") (net 15 "GND"))
+    (pad "10" thru_hole rect (at -6.65 0 90) (size 1.3 3) (drill 1) (layers "*.Cu" "*.Mask") (net 15 "GND"))
+  )
+
+  (footprint "Fixture:Power-B"
+    (layer "F.Cu")
+    (at 135 20 -90)
+    (property "Reference" "CON6")
+    (property "Component Value" "CON_C22930_1084N_X")
+    (pad "" np_thru_hole circle (at -7.5 -2.44 270) (size 0 0) (drill 1) (layers "*.Cu" "*.Mask"))
+    (pad "" np_thru_hole circle (at 7.5 -2.44 270) (size 0 0) (drill 1) (layers "*.Cu" "*.Mask"))
+    (pad "1" thru_hole circle (at 4.5 1.5 270) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 1 "P1"))
+    (pad "2" thru_hole circle (at 1.5 1.5 270) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 2 "P2"))
+    (pad "3" thru_hole circle (at -1.5 1.5 270) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 3 "P3"))
+    (pad "4" thru_hole circle (at -4.5 1.5 270) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 4 "P4"))
+    (pad "5" thru_hole circle (at 4.5 -1.5 270) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 5 "P5"))
+    (pad "6" thru_hole circle (at 1.5 -1.5 270) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 6 "P6"))
+    (pad "7" thru_hole circle (at -1.5 -1.5 270) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 7 "P7"))
+    (pad "8" thru_hole circle (at -4.5 -1.5 270) (size 2 2) (drill 1) (layers "*.Cu" "*.Mask") (net 8 "P8"))
+    (pad "9" thru_hole rect (at 6.65 0 270) (size 1.3 3) (drill 1) (layers "*.Cu" "*.Mask") (net 15 "GND"))
+    (pad "10" thru_hole rect (at -6.65 0 270) (size 1.3 3) (drill 1) (layers "*.Cu" "*.Mask") (net 15 "GND"))
+  )
+
+  (footprint "Fixture:Fan"
+    (layer "F.Cu")
+    (at 165 20 90)
+    (property "Reference" "CON7")
+    (property "Component Value" "CON_PZGM_B03_08P")
+    (pad "" np_thru_hole circle (at 0 1.95 90) (size 0 0) (drill 1) (layers "*.Cu" "*.Mask"))
+    (pad "1" thru_hole circle (at -8.75 0 90) (size 1.8 1.8) (drill 1) (layers "*.Cu" "*.Mask") (net 1 "P1"))
+    (pad "2" thru_hole circle (at -6.25 0 90) (size 1.8 1.8) (drill 1) (layers "*.Cu" "*.Mask") (net 2 "P2"))
+    (pad "3" thru_hole circle (at -3.75 0 90) (size 1.8 1.8) (drill 1) (layers "*.Cu" "*.Mask") (net 3 "P3"))
+    (pad "4" thru_hole circle (at -1.25 0 90) (size 1.8 1.8) (drill 1) (layers "*.Cu" "*.Mask") (net 4 "P4"))
+    (pad "5" thru_hole circle (at 1.25 0 90) (size 1.8 1.8) (drill 1) (layers "*.Cu" "*.Mask") (net 5 "P5"))
+    (pad "6" thru_hole circle (at 3.75 0 90) (size 1.8 1.8) (drill 1) (layers "*.Cu" "*.Mask") (net 6 "P6"))
+    (pad "7" thru_hole circle (at 6.25 0 90) (size 1.8 1.8) (drill 1) (layers "*.Cu" "*.Mask") (net 7 "P7"))
+    (pad "8" thru_hole circle (at 8.75 0 90) (size 1.8 1.8) (drill 1) (layers "*.Cu" "*.Mask") (net 8 "P8"))
+  )
+)

+ 7 - 0
tests/board_viewer/fixtures/parser_edge_cases.d356

@@ -0,0 +1,7 @@
+P  CODE 00
+P  UNITS CUST 0
+P  arrayDim   N
+317RS232_TX2        ${REFE-1    D0315PA00X+004331Y+002756X0787Y0394R330S0
+367N/C              ${REFE      D0394UA00X+003937Y+001181X0000Y0000R000S0
+327BACK_SIG         TP1   -1          A02X+009055Y-003150X0591Y0197R330S1
+999

+ 62 - 0
tests/board_viewer/fixtures/parser_edge_cases.kicad_pcb

@@ -0,0 +1,62 @@
+(kicad_pcb
+  (version 20250114)
+  (generator pcbnew)
+  (net 1 "RS232_TX2")
+  (net 2 "BACK_SIG")
+  (gr_rect
+    (start 0 -10)
+    (end 30 0)
+    (stroke (width 0.05) (type default))
+    (fill none)
+    (layer "Edge.Cuts")
+  )
+  (gr_text "CON5"
+    (at 40 -12)
+    (layer "F.SilkS")
+  )
+  (footprint "Fixture:Front"
+    (layer "F.Cu")
+    (at 10 -5 90)
+    (property "Reference" "CON1"
+      (at 0 0 90)
+      (layer "F.SilkS")
+    )
+    (property "Component Value" "Fixture:Front"
+      (at 0 0 90)
+      (layer "F.Fab")
+      (hide yes)
+    )
+    (property "Reference" "${REFERENCE}"
+      (at 0 0 90)
+      (layer "F.Fab")
+      (hide yes)
+    )
+    (pad "1" thru_hole rect
+      (at 2 1 30)
+      (size 2 1)
+      (drill 0.8)
+      (layers "*.Cu" "*.Mask")
+      (net 1 "RS232_TX2")
+    )
+    (pad "" np_thru_hole circle
+      (at -2 0)
+      (size 0 0)
+      (drill 1)
+      (layers "*.Cu" "*.Mask")
+    )
+  )
+  (footprint "Fixture:Back"
+    (layer "B.Cu")
+    (at 20 10 90)
+    (property "Reference" "TP1"
+      (at 0 0 90)
+      (layer "B.SilkS")
+    )
+    (pad "1" smd oval
+      (at 2 3 30)
+      (size 1.5 0.5)
+      (layers "B.Cu" "B.Paste" "B.Mask")
+      (net 2 "BACK_SIG")
+    )
+  )
+)

+ 105 - 0
tests/board_viewer/fixtures/parser_edge_cases.kicad_prl

@@ -0,0 +1,105 @@
+{
+  "board": {
+    "active_layer": 0,
+    "active_layer_preset": "",
+    "auto_track_width": true,
+    "hidden_netclasses": [],
+    "hidden_nets": [],
+    "high_contrast_mode": 0,
+    "net_color_mode": 1,
+    "opacity": {
+      "images": 0.6,
+      "pads": 1.0,
+      "shapes": 1.0,
+      "tracks": 1.0,
+      "vias": 1.0,
+      "zones": 0.6
+    },
+    "prototype_zone_fills": false,
+    "selection_filter": {
+      "dimensions": true,
+      "footprints": true,
+      "graphics": true,
+      "keepouts": true,
+      "lockedItems": false,
+      "otherItems": true,
+      "pads": true,
+      "text": true,
+      "tracks": true,
+      "vias": true,
+      "zones": true
+    },
+    "visible_items": [
+      "vias",
+      "footprint_text",
+      "footprint_anchors",
+      "ratsnest",
+      "grid",
+      "footprints_front",
+      "footprints_back",
+      "footprint_values",
+      "footprint_references",
+      "tracks",
+      "drc_errors",
+      "drawing_sheet",
+      "bitmaps",
+      "pads",
+      "zones",
+      "drc_warnings",
+      "drc_exclusions",
+      "locked_item_shadows",
+      "conflict_shadows",
+      "shapes",
+      "board_outline_area",
+      "ly_points"
+    ],
+    "visible_layers": "ffffffff_ffffffff_ffffffff_ffffffff",
+    "zone_display_mode": 0
+  },
+  "git": {
+    "integration_disabled": false,
+    "repo_type": "",
+    "repo_username": "",
+    "ssh_key": ""
+  },
+  "meta": {
+    "filename": "parser_edge_cases.kicad_prl",
+    "version": 5
+  },
+  "net_inspector_panel": {
+    "col_hidden": [],
+    "col_order": [],
+    "col_widths": [],
+    "custom_group_rules": [],
+    "expanded_rows": [],
+    "filter_by_net_name": true,
+    "filter_by_netclass": true,
+    "filter_text": "",
+    "group_by_constraint": false,
+    "group_by_netclass": false,
+    "show_time_domain_details": false,
+    "show_unconnected_nets": false,
+    "show_zero_pad_nets": false,
+    "sort_ascending": true,
+    "sorting_column": -1
+  },
+  "open_jobsets": [],
+  "project": {
+    "files": []
+  },
+  "schematic": {
+    "hierarchy_collapsed": [],
+    "selection_filter": {
+      "graphics": true,
+      "images": true,
+      "labels": true,
+      "lockedItems": false,
+      "otherItems": true,
+      "pins": true,
+      "ruleAreas": true,
+      "symbols": true,
+      "text": true,
+      "wires": true
+    }
+  }
+}

+ 394 - 0
tests/board_viewer/playwright_e2e.cjs

@@ -0,0 +1,394 @@
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+
+const {chromium} = require(path.resolve(__dirname, "../../tools/board-viewer/node_modules/playwright"));
+
+
+const root = path.resolve(__dirname, "../..");
+const baseUrl = process.env.BOARD_VIEWER_URL || "http://127.0.0.1:8765";
+const origin = new URL(baseUrl).origin;
+const artifacts = process.env.BOARD_VIEWER_E2E_ARTIFACTS || path.resolve(process.env.TEMP || root, "board-viewer-e2e");
+const executablePath = process.env.BOARD_VIEWER_BROWSER || "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe";
+const boardData = JSON.parse(fs.readFileSync(path.join(root, "tools/board-viewer/generated/board-data.json"), "utf8"));
+fs.mkdirSync(artifacts, {recursive: true});
+
+
+function clone(value) {
+  return JSON.parse(JSON.stringify(value));
+}
+
+
+async function createPage(browser, viewport, options = {}) {
+  const context = await browser.newContext({
+    viewport,
+    permissions: ["clipboard-read", "clipboard-write"],
+    locale: "zh-CN",
+  });
+  const consoleErrors = [];
+  const requestFailures = [];
+  const badResponses = [];
+  const page = await context.newPage();
+  page.on("console", (message) => {
+    if (message.type() === "error") consoleErrors.push(message.text());
+  });
+  page.on("requestfailed", (request) => requestFailures.push(`${request.url()}: ${request.failure()?.errorText}`));
+  page.on("response", (response) => {
+    if (response.status() >= 400) badResponses.push(`${response.status()} ${response.url()}`);
+  });
+  await page.route("**/*", async (route) => {
+    const url = new URL(route.request().url());
+    if (url.origin !== origin) {
+      await route.abort("blockedbyclient");
+      return;
+    }
+    if (options.data && url.pathname === "/generated/board-data.json") {
+      await route.fulfill({status: 200, contentType: "application/json", body: JSON.stringify(options.data)});
+      return;
+    }
+    if (options.runtime && url.pathname === "/api/status") {
+      await route.fulfill({status: 200, contentType: "application/json", body: JSON.stringify(options.runtime)});
+      return;
+    }
+    await route.continue();
+  });
+  await page.goto(baseUrl, {waitUntil: "networkidle"});
+  await page.waitForFunction(() => document.querySelectorAll(".hotspot").length === 110);
+  return {context, page, consoleErrors, requestFailures, badResponses};
+}
+
+
+async function assertHealthy(session) {
+  await session.page.waitForTimeout(50);
+  assert.deepEqual(session.consoleErrors, [], `console errors: ${session.consoleErrors.join("\n")}`);
+  assert.deepEqual(session.requestFailures, [], `request failures: ${session.requestFailures.join("\n")}`);
+  assert.deepEqual(session.badResponses, [], `bad responses: ${session.badResponses.join("\n")}`);
+}
+
+
+async function assertNoViewportOverflow(page) {
+  const metrics = await page.evaluate(() => {
+    const viewport = {width: window.innerWidth, height: window.innerHeight};
+    const topbar = document.querySelector(".topbar").getBoundingClientRect();
+    const board = document.querySelector(".board-pane").getBoundingClientRect();
+    const boardViewport = document.querySelector("#board-viewport").getBoundingClientRect();
+    const footer = document.querySelector(".board-footer").getBoundingClientRect();
+    const panel = document.querySelector("#detail-panel").getBoundingClientRect();
+    return {
+      viewport,
+      scrollWidth: document.documentElement.scrollWidth,
+      scrollHeight: document.documentElement.scrollHeight,
+      topbar: {left: topbar.left, right: topbar.right, top: topbar.top, bottom: topbar.bottom},
+      board: {left: board.left, right: board.right, top: board.top, bottom: board.bottom},
+      boardViewport: {top: boardViewport.top, bottom: boardViewport.bottom, height: boardViewport.height},
+      footer: {top: footer.top, bottom: footer.bottom, height: footer.height},
+      panel: {left: panel.left, right: panel.right, top: panel.top, bottom: panel.bottom},
+      loadingDisplay: getComputedStyle(document.querySelector("#board-loading")).display,
+    };
+  });
+  assert.ok(metrics.scrollWidth <= metrics.viewport.width + 1, JSON.stringify(metrics));
+  assert.ok(metrics.scrollHeight <= metrics.viewport.height + 1, JSON.stringify(metrics));
+  assert.ok(metrics.topbar.left >= -1 && metrics.topbar.right <= metrics.viewport.width + 1, JSON.stringify(metrics));
+  assert.ok(metrics.board.left >= -1 && metrics.board.right <= metrics.viewport.width + 1, JSON.stringify(metrics));
+  assert.ok(metrics.panel.left >= -1 && metrics.panel.right <= metrics.viewport.width + 1, JSON.stringify(metrics));
+  assert.equal(metrics.loadingDisplay, "none", JSON.stringify(metrics));
+  if (metrics.viewport.width > 860) {
+    assert.ok(metrics.boardViewport.height > 400, JSON.stringify(metrics));
+    assert.ok(metrics.footer.height <= 34, JSON.stringify(metrics));
+    assert.ok(metrics.footer.bottom >= metrics.viewport.height - 1, JSON.stringify(metrics));
+  }
+}
+
+
+async function selectSearchResult(page, query, expectedKey) {
+  const search = page.locator("#board-search");
+  await search.fill(query);
+  const result = page.locator(".search-result").filter({hasText: expectedKey}).first();
+  await result.waitFor({state: "visible"});
+  await result.click();
+}
+
+
+async function connectorGrid(page) {
+  return page.locator(".connector-grid-row").evaluateAll((rows) =>
+    rows.map((row) => Array.from(row.querySelectorAll(".connector-contact")).map((pin) => pin.textContent.trim())),
+  );
+}
+
+
+async function assertRenderedPinPositionsMatchGeneratedData(page) {
+  const rendered = await page.locator(".pin-group").evaluateAll((groups) => Object.fromEntries(
+    groups.map((group) => {
+      const dot = group.querySelector(".pin-dot");
+      return [group.dataset.pinId, {x: Number(dot.getAttribute("cx")), y: Number(dot.getAttribute("cy"))}];
+    }),
+  ));
+  const expected = Object.fromEntries(boardData.touchpoints.flatMap((touchpoint) =>
+    touchpoint.pins.map((pin) => [pin.id, pin.view_position]),
+  ));
+  assert.equal(Object.keys(rendered).length, 472);
+  assert.deepEqual(Object.keys(rendered).sort(), Object.keys(expected).sort());
+  for (const [id, point] of Object.entries(expected)) {
+    assert.ok(Math.abs(rendered[id].x - point.x) < 1e-9, `${id} x: ${rendered[id].x} != ${point.x}`);
+    assert.ok(Math.abs(rendered[id].y - point.y) < 1e-9, `${id} y: ${rendered[id].y} != ${point.y}`);
+  }
+}
+
+
+async function desktopWorkflow(browser, viewport, name) {
+  const session = await createPage(browser, viewport);
+  const {page} = session;
+  try {
+    await page.getByText("数据已校验", {exact: true}).waitFor();
+    assert.equal(await page.locator(".hotspot").count(), 110);
+    assert.equal(await page.locator(".pin-group").count(), 472);
+    await assertRenderedPinPositionsMatchGeneratedData(page);
+    assert.equal(await page.locator(".pin-group").first().getAttribute("tabindex"), "-1");
+    assert.equal(await page.locator("#photo-layer").isDisabled(), true);
+    assert.equal(await page.locator('#layer-controls input[value="copper"]').isChecked(), true);
+    assert.equal(await page.locator("#layer-copper").isVisible(), true);
+    assert.equal(await page.locator("#layer-mask").getAttribute("href"), "/generated/board-mask-edge.svg");
+    await assertNoViewportOverflow(page);
+    await page.screenshot({path: path.join(artifacts, `${name}-initial.png`), fullPage: true});
+
+    const con78 = page.locator('.hotspot[data-reference="CON78"]');
+    const con78Box = await con78.boundingBox();
+    assert.ok(con78Box);
+    const connectorPosition = {x: con78Box.width / 2, y: Math.min(1, con78Box.height / 4)};
+    await con78.hover({position: connectorPosition});
+    await page.getByRole("tooltip").getByText("CON78", {exact: true}).waitFor();
+    await con78.click({position: connectorPosition});
+    await page.locator(".detail-reference").getByText("CON78", {exact: true}).waitFor();
+    await page.getByText("板正面接触针排列", {exact: true}).waitFor();
+    await page.getByText("板正面俯视", {exact: false}).waitFor();
+    await page.getByText("线缆端或对接面可能是镜像", {exact: false}).waitFor();
+    assert.deepEqual(await connectorGrid(page), [["1"], ["2"], ["3"], ["4"]]);
+    assert.equal(await page.locator('.pin-row[data-pad-role="contact"]').count(), 4);
+    assert.equal(await page.locator('.pin-row[data-pad-role="shield"]').count(), 2);
+    assert.equal(await page.locator('.pin-group[data-reference="CON78"][data-pin="5"]').getAttribute("data-pad-role"), "shield");
+    await page.getByText("屏蔽固定焊盘", {exact: true}).first().waitFor();
+    await page.getByText("上", {exact: true}).first().waitFor();
+    await page.getByText("下", {exact: true}).first().waitFor();
+
+    await selectSearchResult(page, "CON31", "CON31");
+    assert.deepEqual(await connectorGrid(page), [["4"], ["3"], ["2"], ["1"]]);
+    await selectSearchResult(page, "CON18", "CON18");
+    assert.deepEqual(await connectorGrid(page), [
+      ["13", "11", "9", "7", "5", "3", "1"],
+      ["14", "12", "10", "8", "6", "4", "2"],
+    ]);
+    await selectSearchResult(page, "CON23", "CON23");
+    assert.deepEqual(await connectorGrid(page), [["5", "1"], ["6", "2"], ["7", "3"], ["8", "4"]]);
+
+    await selectSearchResult(page, "J3", "J3");
+    await page.getByText("EF2L45BG256B FPGA JTAG 调试/配置接口(专用配置脚)", {exact: true}).waitFor();
+    await page.locator(".category-tag").getByText("调试接口", {exact: true}).waitFor();
+    assert.deepEqual(await connectorGrid(page), [
+      ["6", "1"],
+      ["7", "2"],
+      ["8", "3"],
+      ["9", "4"],
+      ["10", "5"],
+    ]);
+    const j3Pin1Primary = await page.locator('.pin-row[data-pin="1"] .pin-primary > span').allTextContents();
+    assert.match(j3Pin1Primary[0], /TCK/);
+    assert.match(j3Pin1Primary[1], /原始网络.*N9532014/);
+
+    await selectSearchResult(page, "J3.1", "J3.1");
+    await page.getByText("FPGA 专用 JTAG 时钟输入", {exact: false}).first().waitFor();
+    await page.getByText("U3.A7 专用 TCK", {exact: true}).waitFor();
+    await page.getByText("R63 22R 串联", {exact: true}).first().waitFor();
+    await page.getByText("不要在 RTL 顶层声明", {exact: false}).waitFor();
+    await page.getByText("专用配置脚不使用用户 ADC 约束", {exact: true}).waitFor();
+    assert.equal(await page.getByLabel("RTL 端口名").count(), 0);
+    await page.screenshot({path: path.join(artifacts, `${name}-j3.png`), fullPage: true});
+    await assertNoViewportOverflow(page);
+
+    await selectSearchResult(page, "J3.4", "J3.4");
+    await page.getByText("不是给板子供电", {exact: false}).first().waitFor();
+    await page.getByText("R61 0R", {exact: false}).first().waitFor();
+    await page.getByText("不要通过 VREF 反向给板子供电", {exact: false}).waitFor();
+
+    await selectSearchResult(page, "J3.6", "J3.6");
+    await page.getByText("不能把 NC 当作备用 GPIO", {exact: false}).waitFor();
+
+    await selectSearchResult(page, "J11", "J11");
+    await page.locator(".category-tag").getByText("安装孔", {exact: true}).waitFor();
+    await page.getByText("M3 安装孔(非电气接口)", {exact: true}).waitFor();
+
+    await selectSearchResult(page, "J8", "J8");
+    await page.locator(".category-tag").getByText("制造标记", {exact: true}).waitFor();
+
+    await selectSearchResult(page, "PL2001", "PL2001");
+    await page.locator(".category-tag").getByText("电源器件", {exact: true}).waitFor();
+    await page.getByText("+5V 开关电源电感(非连接器)", {exact: true}).waitFor();
+
+    const beforeZoom = await page.locator("#board-svg").getAttribute("viewBox");
+    await page.getByRole("button", {name: "放大"}).click();
+    const afterZoom = await page.locator("#board-svg").getAttribute("viewBox");
+    assert.notEqual(afterZoom, beforeZoom);
+
+    await selectSearchResult(page, "CON78.1", "CON78.1");
+    assert.equal(await page.locator('.pin-group[data-reference="CON78"][data-pin="1"]').getAttribute("tabindex"), "0");
+    await page.getByText("U23 TRSF3232EIPWR", {exact: true}).first().waitFor();
+    await page.locator(".pin-detail .detail-facts").getByText("FPGA M10", {exact: true}).waitFor();
+    await page.locator(".pin-detail").getByText("RS232_TX2", {exact: true}).first().waitFor();
+    await page.getByText("编程结论", {exact: true}).waitFor();
+    await page.getByText("FPGA 输出", {exact: false}).waitFor();
+    await page.getByText("连接到对端设备的接收端(RX)。", {exact: true}).waitFor();
+    await page.getByText("不能直接接 3.3V TTL/CMOS 串口", {exact: false}).waitFor();
+    await page.getByText("LOCATION = M10", {exact: true}).waitFor();
+    await page.getByText("IOSTANDARD = LVCMOS33", {exact: true}).waitFor();
+
+    const groundPin = page.locator('.pin-group[data-reference="CON78"][data-pin="3"] .pin-hit');
+    await groundPin.hover();
+    await page.getByRole("tooltip").getByText("CON78.3", {exact: true}).waitFor();
+    await groundPin.click();
+    assert.ok(await page.locator(".net-highlight").count() > 20);
+
+    await selectSearchResult(page, "CON30.4", "CON30.4");
+    await page.getByText("MOTOR_EN_N", {exact: false}).first().waitFor();
+    await page.getByText("低电平有效", {exact: true}).waitFor();
+    await page.getByText("R937 4.7K to +3V3", {exact: true}).waitFor();
+    await page.getByText("LOCATION = A10", {exact: true}).waitFor();
+
+    await selectSearchResult(page, "CON31.4", "CON31.4");
+    await page.getByText("开集电极", {exact: false}).first().waitFor();
+    await page.getByText("FPGA high", {exact: false}).first().waitFor();
+    await page.getByText("LOCATION = E10", {exact: true}).waitFor();
+
+    await selectSearchResult(page, "CON58.4", "CON58.4");
+    await page.getByText("上升沿计步脉冲", {exact: true}).waitFor();
+    await page.getByText("每个上升沿表示一步事件", {exact: false}).first().waitFor();
+
+    await selectSearchResult(page, "CON65.4", "CON65.4");
+    await page.getByText("状态选择(非有效电平)", {exact: true}).waitFor();
+    await page.getByText("不存在“高电平有效”的通用含义", {exact: false}).waitFor();
+
+    await selectSearchResult(page, "CON53.1", "CON53.1");
+    await page.getByText("open-drain", {exact: false}).waitFor();
+    await page.getByText("只拉低或释放", {exact: false}).waitFor();
+
+    await selectSearchResult(page, "CON2.5", "CON2.5");
+    await page.getByText("板端电源输入", {exact: false}).first().waitFor();
+    await page.getByText("CON2.5 +12V_VIN", {exact: true}).waitFor();
+
+    await selectSearchResult(page, "TP9.1", "TP9.1");
+    await page.locator(".pin-detail .detail-facts").getByText("GD32F303CGT6 U27", {exact: true}).waitFor();
+    await page.locator(".pin-detail .detail-facts").getByText("U27.10 (PA0)", {exact: true}).waitFor();
+    await page.getByText("MCU 固件用法", {exact: true}).waitFor();
+    await page.getByText("不要在 FPGA RTL/ADC 中声明此针", {exact: false}).waitFor();
+
+    await page.locator("#candidate-tab").click();
+    await page.locator("#capability-select").selectOption("pwm");
+    const pwmCandidate = page.locator(".candidate-row").filter({hasText: "CON31.4 · E10"});
+    await pwmCandidate.locator(".candidate-key").getByText("CON31.4 · E10", {exact: true}).waitFor();
+    await pwmCandidate.getByText("FPGA high -> Q105", {exact: false}).waitFor();
+    await page.locator("#capability-select").selectOption("gpio");
+    assert.equal(await page.locator(".candidate-row").count(), 33);
+    assert.equal(await page.locator(".candidate-row").filter({hasText: "CON31.4"}).count(), 0);
+    await page.locator("#capability-select").selectOption("uart_tx");
+    await page.getByText("没有满足全部证据条件的候选", {exact: true}).waitFor();
+    await page.locator("#detail-tab").click();
+
+    await page.locator("#board-search").fill("does-not-exist");
+    await page.getByText("没有匹配的座子或针脚", {exact: true}).waitFor();
+    await page.screenshot({path: path.join(artifacts, `${name}-selected.png`), fullPage: true});
+    await assertNoViewportOverflow(page);
+    await assertHealthy(session);
+  } finally {
+    await session.context.close();
+  }
+}
+
+
+async function mobileWorkflow(browser) {
+  const session = await createPage(browser, {width: 390, height: 844});
+  const {page} = session;
+  try {
+    await assertNoViewportOverflow(page);
+    await page.screenshot({path: path.join(artifacts, "390x844-initial.png"), fullPage: true});
+    assert.equal(await page.locator("#app").evaluate((node) => node.classList.contains("detail-collapsed")), true);
+    await selectSearchResult(page, "CON78", "CON78");
+    assert.equal(await page.locator("#app").evaluate((node) => node.classList.contains("detail-collapsed")), false);
+    await page.locator(".detail-reference").getByText("CON78", {exact: true}).waitFor();
+    await page.screenshot({path: path.join(artifacts, "390x844-selected.png"), fullPage: true});
+    await assertNoViewportOverflow(page);
+    await selectSearchResult(page, "J3.1", "J3.1");
+    await page.getByText("FPGA 专用 JTAG 时钟输入", {exact: false}).first().waitFor();
+    await page.screenshot({path: path.join(artifacts, "390x844-j3.png"), fullPage: true});
+    await assertNoViewportOverflow(page);
+    await assertHealthy(session);
+  } finally {
+    await session.context.close();
+  }
+}
+
+
+async function adcCopyWorkflow(browser) {
+  const data = clone(boardData);
+  const con78 = data.touchpoints.find((item) => item.reference === "CON78");
+  const pin = con78.pins.find((item) => item.number === "1");
+  pin.reserved = false;
+  pin.recommendation = {eligible: true, reasons: ["capability_match", "verified_fpga_path", "external_level_known"]};
+  const runtime = {
+    status: "pass",
+    staleSources: [],
+    recommendationsEnabled: true,
+    adcCopyEnabled: true,
+  };
+  const session = await createPage(browser, {width: 1366, height: 768}, {data, runtime});
+  const {page} = session;
+  try {
+    await selectSearchResult(page, "CON78.1", "CON78.1");
+    const input = page.getByLabel("RTL 端口名");
+    assert.equal(await input.isEnabled(), true);
+    await input.fill("uart2_tx");
+    await page.getByRole("button", {name: "复制 ADC 片段"}).click();
+    await page.getByText("ADC 片段已复制", {exact: true}).waitFor();
+    const clipboard = await page.evaluate(() => navigator.clipboard.readText());
+    assert.equal(clipboard, "set_pin_assignment { uart2_tx } { LOCATION = M10; IOSTANDARD = LVCMOS33; }");
+    await assertHealthy(session);
+  } finally {
+    await session.context.close();
+  }
+}
+
+
+async function staleWorkflow(browser) {
+  const runtime = {
+    status: "stale_sources",
+    staleSources: ["sha256_mismatch:inventory"],
+    recommendationsEnabled: false,
+    adcCopyEnabled: false,
+  };
+  const session = await createPage(browser, {width: 1366, height: 768}, {runtime});
+  const {page} = session;
+  try {
+    await page.getByText("来源已变化", {exact: true}).waitFor();
+    await page.locator("#candidate-tab").click();
+    await page.getByText("源文件状态不是当前值,选脚推荐已关闭。", {exact: true}).waitFor();
+    await page.screenshot({path: path.join(artifacts, "stale-state.png"), fullPage: true});
+    await assertHealthy(session);
+  } finally {
+    await session.context.close();
+  }
+}
+
+
+(async () => {
+  const browser = await chromium.launch({headless: true, executablePath});
+  try {
+    await desktopWorkflow(browser, {width: 1920, height: 1080}, "1920x1080");
+    await desktopWorkflow(browser, {width: 1366, height: 768}, "1366x768");
+    await mobileWorkflow(browser);
+    await adcCopyWorkflow(browser);
+    await staleWorkflow(browser);
+    process.stdout.write(`Playwright board-viewer E2E passed. Artifacts: ${artifacts}\n`);
+  } finally {
+    await browser.close();
+  }
+})().catch((error) => {
+  console.error(error);
+  process.exit(1);
+});

+ 185 - 0
tests/board_viewer/test_annotations_and_eligibility.py

@@ -0,0 +1,185 @@
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[2]
+VIEWER_ROOT = ROOT / "tools" / "board-viewer"
+sys.path.insert(0, str(VIEWER_ROOT))
+
+from board_viewer.annotations import AnnotationError, validate_annotation_references  # noqa: E402
+from board_viewer.eligibility import evaluate_recommendation  # noqa: E402
+
+
+TOUCHPOINTS = {
+    "CON78": {
+        "component_value": "CON_11251W00_NPX_SX_4P",
+        "pins": [
+            {"number": "1"},
+            {"number": "2"},
+            {"number": "3"},
+            {"number": "4"},
+            {"number": "5"},
+            {"number": "6"},
+            {"number": ""},
+        ],
+    },
+}
+
+
+@pytest.mark.parametrize(
+    "annotations, expected_message",
+    [
+        (
+            {"touchpoints": {"CON99": {"pins": {}}}},
+            "unknown touchpoint CON99",
+        ),
+        (
+            {"touchpoints": {"CON78": {"pins": {"99": {"summary": "invalid"}}}}},
+            "unknown pin CON78.99",
+        ),
+    ],
+)
+def test_annotations_must_reference_real_touchpoints_and_pins(
+    annotations: dict[str, object], expected_message: str
+) -> None:
+    with pytest.raises(AnnotationError, match=expected_message):
+        validate_annotation_references(annotations, TOUCHPOINTS)
+
+
+@pytest.mark.parametrize(
+    "profile, expected_message",
+    [
+        (
+            {
+                "references": ["CON99"],
+                "contact_pins": ["1"],
+                "shield_pads": [],
+            },
+            "unknown connector CON99",
+        ),
+        (
+            {
+                "references": ["CON78"],
+                "contact_pins": ["1", "2", "3", "4"],
+                "shield_pads": ["5"],
+            },
+            "unclassified numbered pads CON78: 6",
+        ),
+        (
+            {
+                "references": ["CON78"],
+                "contact_pins": ["1", "2", "3", "4", "5"],
+                "shield_pads": ["5", "6"],
+            },
+            "overlapping contact and shield pads",
+        ),
+        (
+            {
+                "references": ["CON78"],
+                "contact_pins": ["1", "2", "3", "4", "99"],
+                "shield_pads": ["5", "6"],
+            },
+            "unknown classified pads CON78: 99",
+        ),
+    ],
+)
+def test_connector_profiles_fail_closed_on_invalid_pad_classification(
+    profile: dict[str, object], expected_message: str
+) -> None:
+    annotations = {
+        "touchpoints": {},
+        "connector_profiles": {"CON_11251W00_NPX_SX_4P": profile},
+    }
+
+    with pytest.raises(AnnotationError, match=expected_message):
+        validate_annotation_references(annotations, TOUCHPOINTS)
+
+
+def test_connector_profile_component_value_must_match_board_database() -> None:
+    annotations = {
+        "touchpoints": {},
+        "connector_profiles": {
+            "WRONG_VALUE": {
+                "references": ["CON78"],
+                "contact_pins": ["1", "2", "3", "4"],
+                "shield_pads": ["5", "6"],
+            }
+        },
+    }
+
+    with pytest.raises(AnnotationError, match="component value mismatch CON78"):
+        validate_annotation_references(annotations, TOUCHPOINTS)
+
+
+def test_connector_reference_may_only_appear_in_one_profile() -> None:
+    profile = {
+        "references": ["CON78"],
+        "contact_pins": ["1", "2", "3", "4"],
+        "shield_pads": ["5", "6"],
+    }
+    annotations = {
+        "touchpoints": {},
+        "connector_profiles": {"FIRST": profile, "SECOND": profile},
+    }
+
+    with pytest.raises(AnnotationError, match="connector CON78 appears in multiple profiles"):
+        validate_annotation_references(annotations, TOUCHPOINTS)
+
+
+def eligible_pin(**overrides: object) -> dict[str, object]:
+    pin: dict[str, object] = {
+        "number": "1",
+        "pad_role": "contact",
+        "mechanical": False,
+        "electrical": True,
+        "net": "UART2_TX",
+        "function_category": "uart_tx",
+        "reserved": False,
+        "fixed_load_conflict": False,
+        "external_level": "RS232",
+        "evidence_tier": "cross_verified",
+        "fpga": {
+            "ball": "M10",
+            "io_standard": "LVCMOS33",
+            "capabilities": ["gpio", "uart_tx"],
+            "evidence_tier": "cross_verified",
+        },
+    }
+    pin.update(overrides)
+    return pin
+
+
+def test_verified_capability_match_is_recommendable_with_reasons() -> None:
+    result = evaluate_recommendation(eligible_pin(), "uart_tx")
+
+    assert result.eligible is True
+    assert result.reasons == ["capability_match", "verified_fpga_path", "external_level_known"]
+
+
+@pytest.mark.parametrize(
+    "pin, capability, reason",
+    [
+        (eligible_pin(evidence_tier="name_inferred"), "uart_tx", "pin_evidence_not_verified"),
+        (eligible_pin(evidence_tier="unknown"), "uart_tx", "pin_evidence_not_verified"),
+        (eligible_pin(net="GND"), "uart_tx", "power_or_ground"),
+        (eligible_pin(mechanical=True, electrical=False), "uart_tx", "mechanical_or_non_electrical"),
+        (eligible_pin(pad_role="shield"), "uart_tx", "not_connector_contact"),
+        (eligible_pin(pad_role="unknown"), "uart_tx", "not_connector_contact"),
+        (eligible_pin(reserved=True), "uart_tx", "reserved"),
+        (eligible_pin(function_category="power", net="+3V3"), "uart_tx", "power_or_ground"),
+        (eligible_pin(fixed_load_conflict=True), "uart_tx", "fixed_load_conflict"),
+        (eligible_pin(external_level="unknown"), "uart_tx", "external_level_unknown"),
+        (eligible_pin(), "pwm", "capability_mismatch"),
+    ],
+)
+def test_ineligible_pin_classes_are_rejected(
+    pin: dict[str, object], capability: str, reason: str
+) -> None:
+    result = evaluate_recommendation(pin, capability)
+
+    assert result.eligible is False
+    assert reason in result.reasons

+ 131 - 0
tests/board_viewer/test_asset_validation.py

@@ -0,0 +1,131 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[2]
+VIEWER_ROOT = ROOT / "tools" / "board-viewer"
+sys.path.insert(0, str(VIEWER_ROOT))
+
+from board_viewer.assets import (  # noqa: E402
+    AssetIntegrityError,
+    sha256_file,
+    validate_generated_assets,
+)
+
+
+def write(path: Path, content: str) -> str:
+    path.parent.mkdir(parents=True, exist_ok=True)
+    path.write_text(content, encoding="utf-8")
+    return hashlib.sha256(content.encode("utf-8")).hexdigest()
+
+
+def create_asset_set(tmp_path: Path) -> tuple[Path, dict[str, Path]]:
+    generated = tmp_path / "generated"
+    sources = {
+        "brd": tmp_path / "source.brd",
+        "inventory": tmp_path / "inventory.json",
+        "annotations": tmp_path / "annotations.json",
+    }
+    source_hashes = {name: write(path, f"{name}-source") for name, path in sources.items()}
+    assets = {
+        "board-data.json": write(generated / "board-data.json", '{"schema":"board-viewer-data-v1"}'),
+        "board-mask-edge.svg": write(generated / "board-mask-edge.svg", "<svg></svg>"),
+        "board-silkscreen.svg": write(generated / "board-silkscreen.svg", "<svg></svg>"),
+        "board-copper.svg": write(generated / "board-copper.svg", "<svg></svg>"),
+        "import-report.json": write(generated / "import-report.json", '{"errors":[],"warnings":[]}'),
+    }
+    build_info = {
+        "schema": "board-viewer-build-info-v1",
+        "generated_at": "2026-07-21T00:00:00Z",
+        "generator_version": "1.0.0",
+        "toolchain": {"python": "3.12.9", "kicad": "10.0.4"},
+        "sources": {
+            name: {"path": str(path), "sha256": source_hashes[name]}
+            for name, path in sources.items()
+        },
+        "assets": {name: {"sha256": digest, "bytes": (generated / name).stat().st_size} for name, digest in assets.items()},
+        "verification": {
+            "ipcd356": {
+                "numbered_pads": 455,
+                "matched_pads": 455,
+                "record_types": {"317": 72, "327": 383},
+                "tolerance_mm": 0.02,
+            }
+        },
+        "counts": {"footprints": 1052, "touchpoints": 110, "pads": 472},
+    }
+    write(generated / "build-info.json", json.dumps(build_info))
+    return generated, sources
+
+
+def test_sha256_file_streams_exact_file_content(tmp_path: Path) -> None:
+    path = tmp_path / "payload.bin"
+    path.write_bytes(b"abc" * 100_000)
+
+    assert sha256_file(path) == hashlib.sha256(b"abc" * 100_000).hexdigest()
+
+
+def test_generated_assets_pass_when_hashes_and_sources_match(tmp_path: Path) -> None:
+    generated, _ = create_asset_set(tmp_path)
+
+    result = validate_generated_assets(generated)
+
+    assert result.status == "pass"
+    assert result.asset_errors == []
+    assert result.stale_sources == []
+
+
+@pytest.mark.parametrize("problem", ["missing", "hash_mismatch"])
+def test_generated_asset_damage_fails_closed(tmp_path: Path, problem: str) -> None:
+    generated, _ = create_asset_set(tmp_path)
+    asset = generated / "board-data.json"
+    if problem == "missing":
+        asset.unlink()
+    else:
+        asset.write_text("tampered", encoding="utf-8")
+
+    with pytest.raises(AssetIntegrityError, match="board-data.json"):
+        validate_generated_assets(generated)
+
+
+@pytest.mark.parametrize("problem", ["missing", "hash_mismatch"])
+def test_source_change_enters_stale_read_only_mode(tmp_path: Path, problem: str) -> None:
+    generated, sources = create_asset_set(tmp_path)
+    if problem == "missing":
+        sources["brd"].unlink()
+    else:
+        sources["inventory"].write_text("changed", encoding="utf-8")
+
+    result = validate_generated_assets(generated)
+
+    assert result.status == "stale_sources"
+    assert result.asset_errors == []
+    assert result.stale_sources
+    assert result.recommendations_enabled is False
+    assert result.adc_copy_enabled is False
+
+
+def test_missing_build_info_fails_closed(tmp_path: Path) -> None:
+    generated = tmp_path / "generated"
+    generated.mkdir()
+
+    with pytest.raises(AssetIntegrityError, match="build-info.json"):
+        validate_generated_assets(generated)
+
+
+def test_relative_source_paths_resolve_from_repository_root(tmp_path: Path) -> None:
+    generated, _ = create_asset_set(tmp_path)
+    build_info_path = generated / "build-info.json"
+    build_info = json.loads(build_info_path.read_text(encoding="utf-8"))
+    build_info["sources"]["brd"]["path"] = "source.brd"
+    build_info_path.write_text(json.dumps(build_info), encoding="utf-8")
+
+    result = validate_generated_assets(generated, repository_root=tmp_path)
+
+    assert result.status == "pass"

+ 69 - 0
tests/board_viewer/test_cli_launcher.py

@@ -0,0 +1,69 @@
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+VIEWER_ROOT = ROOT / "tools" / "board-viewer"
+sys.path.insert(0, str(VIEWER_ROOT))
+
+from board_viewer.cli import build_parser, default_generation_config, main  # noqa: E402
+
+
+def test_cli_exposes_generate_validate_and_serve_without_host_override() -> None:
+    parser = build_parser()
+
+    assert parser.parse_args(["generate"]).command == "generate"
+    assert parser.parse_args(["validate"]).command == "validate"
+    serve = parser.parse_args(["serve", "--port", "9000", "--open-browser"])
+    assert serve.command == "serve"
+    assert serve.port == 9000
+    assert serve.open_browser is True
+    assert "--host" not in parser.format_help()
+
+
+def test_default_generation_config_targets_reviewed_product_inputs() -> None:
+    config = default_generation_config()
+
+    assert config.brd_path == ROOT / "reference/original/board/FCB_FPGA_MCU_V1.1_20260625/FCB_FPGA+MCU_V1.1_20260625.brd"
+    assert config.inventory_path == ROOT / "config/pin_inventory.fcb_fpga_mcu0611.json"
+    assert config.annotations_path == ROOT / "config/board_viewer_annotations.fcb_fpga_mcu0611.json"
+    assert config.output_dir == VIEWER_ROOT / "generated"
+    assert config.expected_counts == {"footprints": 1052, "touchpoints": 110, "pads": 472}
+    assert config.product_regression is True
+
+
+def test_validate_cli_reports_current_bundle_as_json(capsys) -> None:
+    exit_code = main(["validate", "--json"])
+    payload = json.loads(capsys.readouterr().out)
+
+    assert exit_code == 0
+    assert payload["status"] == "pass"
+    assert payload["counts"] == {"footprints": 1052, "touchpoints": 110, "pads": 472}
+
+
+def test_script_entrypoint_validate_command_runs_from_any_working_directory(tmp_path: Path) -> None:
+    result = subprocess.run(
+        [sys.executable, str(VIEWER_ROOT / "board_viewer.py"), "validate", "--json"],
+        cwd=tmp_path,
+        check=False,
+        capture_output=True,
+        text=True,
+        encoding="utf-8",
+    )
+
+    assert result.returncode == 0, result.stderr
+    assert json.loads(result.stdout)["status"] == "pass"
+
+
+def test_windows_launcher_is_location_independent_and_opens_loopback_server() -> None:
+    launcher = (VIEWER_ROOT / "OPEN_BOARD_VIEWER.cmd").read_text(encoding="ascii")
+
+    assert 'cd /d "%~dp0"' in launcher
+    assert "py -3.12" in launcher
+    assert "board_viewer.py serve --open-browser" in launcher
+    assert "0.0.0.0" not in launcher
+    assert "PROGRAM_" not in launcher

+ 901 - 0
tests/board_viewer/test_data_contract.py

@@ -0,0 +1,901 @@
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+from jsonschema import Draft202012Validator
+
+
+ROOT = Path(__file__).resolve().parents[2]
+VIEWER_ROOT = ROOT / "tools" / "board-viewer"
+FIXTURE = Path(__file__).parent / "fixtures" / "parser_edge_cases.kicad_pcb"
+CONNECTOR_FIXTURE = Path(__file__).parent / "fixtures" / "connector_layouts.kicad_pcb"
+sys.path.insert(0, str(VIEWER_ROOT))
+
+from board_viewer.data import build_board_data  # noqa: E402
+from board_viewer.annotations import AnnotationError  # noqa: E402
+from board_viewer.pcb import Footprint, Pad, ParsedBoard, parse_kicad_pcb  # noqa: E402
+
+
+def fixture_inventory() -> dict[str, object]:
+    return {
+        "schema": "fixture-pin-inventory-v1",
+        "board_id": "fixture-board",
+        "pins": [
+            {
+                "signal": "UART2_TX",
+                "function_net": "UART2_TX",
+                "fpga_ball": "M10",
+                "direction": "output",
+                "io_standard": "LVCMOS33",
+                "capability": ["gpio", "uart_tx", "rs232_via_transceiver"],
+                "reserved": False,
+                "board_connector": "CON1",
+                "connector_pin": 1,
+                "connector_signal": "RS232_TX2",
+                "external_level": "RS232",
+                "transceiver": "U23 TRSF3232EIPWR",
+                "pullup": "RTEST 4.7K to +3V3",
+                "series_link": "RTEST2 0R",
+                "esd": "ESDTEST",
+                "manually_verified": True,
+                "source_pages": [10, 5, 3],
+                "screenshot_index": "fixture-uart2",
+                "source_confidence": "manual_pdf_cross_check",
+            }
+        ],
+    }
+
+
+def fixture_annotations() -> dict[str, object]:
+    return {
+        "schema": "board-viewer-annotations-v1",
+        "board_id": "fixture-board",
+        "connector_profiles": {
+            "Fixture:Front": {
+                "references": ["CON1"],
+                "contact_pins": ["1"],
+                "shield_pads": [],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture connector profile"],
+            }
+        },
+        "touchpoints": {
+            "CON1": {
+                "summary": "UART2 RS-232 接口",
+                "pins": {
+                    "1": {
+                        "summary": "UART2 发送,经电平转换",
+                        "path": ["CON1.1", "U23", "UART2_TX", "FPGA M10"],
+                        "evidence_tier": "cross_verified",
+                        "sources": ["fixture schematic pages 3/5/10"],
+                        "adc_pulltype": "PULLUP",
+                    }
+                },
+            }
+        },
+        "interfaces": [
+            {
+                "id": "uart2-rs232",
+                "name": "UART2 RS-232",
+                "touchpoint": "CON1",
+                "pins": ["1"],
+                "external_level": "RS232",
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture schematic pages 3/5/10"],
+            }
+        ],
+        "photo_overlay": None,
+    }
+
+
+def connector_layout_annotations() -> dict[str, object]:
+    return {
+        "schema": "board-viewer-annotations-v1",
+        "board_id": "connector-layout-fixture",
+        "connector_profiles": {
+            "CON_11251W00_NPX_SX_4P": {
+                "references": ["CON1", "CON2"],
+                "contact_pins": ["1", "2", "3", "4"],
+                "shield_pads": ["5", "6"],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture 4P symbol"],
+            },
+            "CON_51541_003_P1D25": {
+                "references": ["CON3"],
+                "contact_pins": ["1", "2", "3"],
+                "shield_pads": ["4", "5"],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture 3P symbol"],
+            },
+            "CON_3110_14P_P2D54": {
+                "references": ["CON4"],
+                "contact_pins": [str(number) for number in range(1, 15)],
+                "shield_pads": [],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture 14P symbol"],
+            },
+            "CON_C22930_1084N_X": {
+                "references": ["CON5", "CON6"],
+                "contact_pins": [str(number) for number in range(1, 9)],
+                "shield_pads": ["9", "10"],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture power connector symbol"],
+            },
+            "CON_PZGM_B03_08P": {
+                "references": ["CON7"],
+                "contact_pins": [str(number) for number in range(1, 9)],
+                "shield_pads": [],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture fan connector symbol"],
+            },
+        },
+        "touchpoints": {},
+        "interfaces": [],
+        "photo_overlay": None,
+    }
+
+
+def build_connector_layout_payload(annotations: dict[str, object] | None = None) -> dict[str, object]:
+    return build_board_data(
+        parse_kicad_pcb(CONNECTOR_FIXTURE),
+        {"schema": "fixture", "board_id": "connector-layout-fixture", "pins": []},
+        annotations or connector_layout_annotations(),
+        board_name="Connector layout fixture",
+    )
+
+
+def jtag_fixture_board() -> ParsedBoard:
+    nets = {
+        "1": "N9532014",
+        "2": "GND",
+        "3": "N9532092",
+        "4": "N9532034",
+        "5": "N9532142",
+        "6": "Net_649",
+        "7": "Net_650",
+        "8": "Net_648",
+        "9": "N9532240",
+        "10": "GND",
+    }
+    coordinates = {
+        "1": (235.22, -41.08),
+        "2": (235.22, -38.54),
+        "3": (235.22, -36.00),
+        "4": (235.22, -33.46),
+        "5": (235.22, -30.92),
+        "6": (232.68, -41.08),
+        "7": (232.68, -38.54),
+        "8": (232.68, -36.00),
+        "9": (232.68, -33.46),
+        "10": (232.68, -30.92),
+    }
+    pads = [
+        Pad(
+            number=number,
+            pad_type="thru_hole",
+            shape="rect" if number == "1" else "circle",
+            x=coordinates[number][0],
+            y=coordinates[number][1],
+            width=1.6256,
+            height=1.6256,
+            rotation=270.0,
+            net=nets[number],
+            layers=("*.Cu", "*.Mask"),
+            drill_width=1.1176,
+            drill_height=1.1176,
+            mechanical=False,
+            electrical=True,
+        )
+        for number in nets
+    ]
+    footprint = Footprint(
+        reference="J3",
+        component_value="",
+        x=233.95,
+        y=-36.0,
+        rotation=270.0,
+        side="front",
+        layer="F.Cu",
+        pads=pads,
+        bounds={"x": 231.8672, "y": -41.8928, "width": 4.1656, "height": 11.7856},
+    )
+    return ParsedBoard(
+        footprints=[footprint],
+        footprint_count=1,
+        bounds={"x": 231.0, "y": -43.0, "width": 6.0, "height": 14.0},
+    )
+
+
+def jtag_fixture_annotations() -> dict[str, object]:
+    return {
+        "schema": "board-viewer-annotations-v1",
+        "board_id": "jtag-fixture",
+        "connector_profiles": {
+            "J3_FPGA_JTAG_2X5": {
+                "component_value": "",
+                "references": ["J3"],
+                "contact_pins": [str(number) for number in range(1, 11)],
+                "shield_pads": [],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture schematic J3 symbol and board-front coordinates"],
+            }
+        },
+        "touchpoints": {
+            "J3": {
+                "summary": "FPGA JTAG 调试/配置接口(专用配置脚)",
+                "pins": {
+                    "1": {
+                        "summary": "TCK,调试器输出到 FPGA 专用 JTAG 时钟输入",
+                        "path": ["J3.1", "R63 22R", "FPGA_TCK", "U3.A7"],
+                        "evidence_tier": "cross_verified",
+                        "sources": ["fixture schematic and board database"],
+                        "direction": "input",
+                        "external_level": "3.3V JTAG, referenced by J3.4 VREF",
+                        "function_category": "jtag_tck",
+                        "reserved": True,
+                        "board_pull": "R71 4.7K to GND",
+                        "external_components": ["R63 22R series", "D24 ESD", "R71 4.7K pull-down"],
+                        "fpga": {
+                            "ball": "A7",
+                            "board_signal": "FPGA_TCK",
+                            "io_standard": "Dedicated JTAG (VREF 3.3V)",
+                            "capabilities": ["jtag", "jtag_tck"],
+                            "evidence_tier": "cross_verified",
+                            "sources": ["fixture U3 dedicated JTAG pin table"],
+                        },
+                    },
+                    "4": {
+                        "summary": "VREF,目标板 3.3V 参考,不是给板子供电",
+                        "path": ["J3.4", "R61 0R", "+3V3"],
+                        "evidence_tier": "cross_verified",
+                        "sources": ["fixture schematic and board database"],
+                        "direction": "passive",
+                        "external_level": "3.3V target reference",
+                        "function_category": "reference_voltage",
+                        "reserved": True,
+                        "programming": {
+                            "status": "not_programmable",
+                            "conclusion": "VREF is not an FPGA I/O or a board power input.",
+                            "evidence_tier": "cross_verified",
+                            "sources": ["fixture schematic J3 VREF path"],
+                        },
+                    },
+                    "6": {
+                        "summary": "NC,连接器外无板内路径",
+                        "path": ["J3.6", "NC"],
+                        "evidence_tier": "cross_verified",
+                        "sources": ["fixture schematic and board database"],
+                        "direction": "passive",
+                        "external_level": "not connected",
+                        "function_category": "not_connected",
+                        "reserved": True,
+                        "programming": {
+                            "status": "not_programmable",
+                            "conclusion": "NC must remain unconnected.",
+                            "evidence_tier": "cross_verified",
+                            "sources": ["fixture schematic J3 NC symbol"],
+                        },
+                    }
+                },
+            }
+        },
+        "interfaces": [
+            {
+                "id": "fpga-jtag",
+                "name": "FPGA JTAG 调试/配置接口",
+                "touchpoint": "J3",
+                "pins": [str(number) for number in range(1, 11)],
+                "external_level": "3.3V JTAG; VREF is target-sense only",
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture schematic J3 symbol"],
+            }
+        ],
+        "photo_overlay": None,
+    }
+
+
+def test_reviewed_j_header_uses_board_front_matrix_and_curated_fpga_mapping() -> None:
+    payload = build_board_data(
+        jtag_fixture_board(),
+        {"schema": "fixture", "board_id": "jtag-fixture", "pins": []},
+        jtag_fixture_annotations(),
+        board_name="JTAG fixture",
+    )
+
+    j3 = payload["touchpoints"][0]
+    assert j3["connector"]["contact_grid"] == [
+        ["6", "1"],
+        ["7", "2"],
+        ["8", "3"],
+        ["9", "4"],
+        ["10", "5"],
+    ]
+    assert j3["connector"]["review_status"] == "cross_verified"
+    pin1 = next(pin for pin in j3["pins"] if pin["number"] == "1")
+    assert pin1["fpga"]["ball"] == "A7"
+    assert pin1["fpga"]["board_signal"] == "FPGA_TCK"
+    assert pin1["direction"] == "input"
+    assert pin1["programming"]["status"] == "verified_fpga"
+    assert pin1["recommendation"]["eligible"] is False
+    assert "reserved" in pin1["recommendation"]["reasons"]
+
+
+def test_jtag_annotations_schema_allows_reviewed_j_profiles_and_manual_fpga_paths() -> None:
+    schema_path = ROOT / "schemas" / "board_viewer_annotations.schema.json"
+    schema = json.loads(schema_path.read_text(encoding="utf-8"))
+
+    Draft202012Validator(schema).validate(jtag_fixture_annotations())
+
+
+def test_curated_non_io_status_keeps_vref_and_nc_out_of_fpga_programming() -> None:
+    payload = build_board_data(
+        jtag_fixture_board(),
+        {"schema": "fixture", "board_id": "jtag-fixture", "pins": []},
+        jtag_fixture_annotations(),
+        board_name="JTAG fixture",
+    )
+    pins = {pin["number"]: pin for pin in payload["touchpoints"][0]["pins"]}
+
+    assert pins["4"]["programming"]["status"] == "not_programmable"
+    assert pins["6"]["programming"]["status"] == "not_programmable"
+    assert pins["4"]["recommendation"]["eligible"] is False
+    assert pins["6"]["recommendation"]["eligible"] is False
+
+
+def test_connector_layouts_follow_board_front_top_to_bottom_then_left_to_right() -> None:
+    payload = build_connector_layout_payload()
+    by_reference = {item["reference"]: item for item in payload["touchpoints"]}
+    expected_grids = {
+        "CON1": [["4"], ["3"], ["2"], ["1"]],
+        "CON2": [["1"], ["2"], ["3"], ["4"]],
+        "CON3": [["3", "2", "1"]],
+        "CON4": [
+            ["13", "11", "9", "7", "5", "3", "1"],
+            ["14", "12", "10", "8", "6", "4", "2"],
+        ],
+        "CON5": [["5", "1"], ["6", "2"], ["7", "3"], ["8", "4"]],
+        "CON6": [["4", "8"], ["3", "7"], ["2", "6"], ["1", "5"]],
+        "CON7": [[str(number)] for number in range(8, 0, -1)],
+    }
+
+    for reference, expected_grid in expected_grids.items():
+        touchpoint = by_reference[reference]
+        connector = touchpoint["connector"]
+        assert connector["review_status"] == "cross_verified"
+        assert connector["view"] == "board_front"
+        assert connector["contact_grid"] == expected_grid
+        assert connector["rows"] == len(expected_grid)
+        assert connector["columns"] == len(expected_grid[0])
+        expected_order = [number for row in expected_grid for number in row]
+        assert connector["contact_order"] == expected_order
+        assert [pin["number"] for pin in touchpoint["pins"][: len(expected_order)]] == expected_order
+
+        pins = {pin["number"]: pin for pin in touchpoint["pins"] if pin["number"]}
+        for order, number in enumerate(expected_order, start=1):
+            row = next(index for index, values in enumerate(expected_grid, start=1) if number in values)
+            column = expected_grid[row - 1].index(number) + 1
+            assert pins[number]["pad_role"] == "contact"
+            assert pins[number]["board_order"] == order
+            assert pins[number]["row"] == row
+            assert pins[number]["column"] == column
+
+
+def test_connector_layout_separates_shield_and_mechanical_pads_from_contacts() -> None:
+    payload = build_connector_layout_payload()
+    by_reference = {item["reference"]: item for item in payload["touchpoints"]}
+
+    expected = {
+        "CON1": (4, {"5", "6"}, 0),
+        "CON2": (4, {"5", "6"}, 0),
+        "CON3": (3, {"4", "5"}, 0),
+        "CON4": (14, set(), 0),
+        "CON5": (8, {"9", "10"}, 2),
+        "CON6": (8, {"9", "10"}, 2),
+        "CON7": (8, set(), 1),
+    }
+    for reference, (contact_count, shield_numbers, mechanical_count) in expected.items():
+        touchpoint = by_reference[reference]
+        connector = touchpoint["connector"]
+        assert connector["contact_count"] == contact_count
+        assert connector["auxiliary_pad_count"] == len(shield_numbers) + mechanical_count
+        assert {pin["number"] for pin in touchpoint["pins"] if pin["pad_role"] == "shield"} == shield_numbers
+        assert sum(pin["pad_role"] == "mechanical" for pin in touchpoint["pins"]) == mechanical_count
+        assert len({pin["id"] for pin in touchpoint["pins"]}) == len(touchpoint["pins"])
+
+    assert payload["counts"]["connector_contacts"] == 49
+    assert payload["counts"]["connector_auxiliary_pads"] == 15
+
+
+def test_unknown_connector_profile_fails_closed_without_inventing_contact_order() -> None:
+    annotations = connector_layout_annotations()
+    annotations["connector_profiles"] = {}
+    payload = build_connector_layout_payload(annotations)
+    connector = next(item for item in payload["touchpoints"] if item["reference"] == "CON1")
+
+    assert connector["connector"]["review_status"] == "unknown"
+    assert connector["connector"]["contact_count"] == 0
+    assert connector["connector"]["contact_grid"] == []
+    assert all(pin["pad_role"] != "contact" for pin in connector["pins"])
+    assert all(pin["recommendation"]["eligible"] is False for pin in connector["pins"])
+
+
+def test_build_board_data_merges_board_inventory_and_manual_path_evidence() -> None:
+    payload = build_board_data(
+        parse_kicad_pcb(FIXTURE),
+        fixture_inventory(),
+        fixture_annotations(),
+        board_name="Fixture board",
+    )
+
+    assert payload["schema"] == "board-viewer-data-v1"
+    assert payload["board"]["id"] == "fixture-board"
+    assert payload["board"]["source_bounds"] == {"x": 0.0, "y": -10.0, "width": 30.0, "height": 10.0}
+    assert payload["board"]["view_box"] == {"x": 0.0, "y": 0.0, "width": 30.0, "height": 10.0}
+    assert payload["counts"] == {
+        "footprints": 2,
+        "touchpoints": 2,
+        "pads": 3,
+        "connector_contacts": 1,
+        "connector_auxiliary_pads": 1,
+        "categories": {"CON": 1, "J": 0, "PL": 0, "TP": 1},
+        "sides": {"front": 1, "back": 1},
+    }
+
+    connector = next(item for item in payload["touchpoints"] if item["reference"] == "CON1")
+    pin = next(item for item in connector["pins"] if item["number"] == "1")
+    assert connector["summary"] == "UART2 RS-232 接口"
+    assert pin["net"] == "RS232_TX2"
+    assert pin["view_position"] == {"x": 11.0, "y": 3.0}
+    assert pin["direction"] == "output"
+    assert pin["external_level"] == "RS232"
+    assert pin["function_category"] == "uart_tx"
+    assert pin["evidence_tier"] == "cross_verified"
+    assert pin["path"] == ["CON1.1", "U23", "UART2_TX", "FPGA M10"]
+    assert pin["adc_pulltype"] == "PULLUP"
+    assert pin["board_pull"] == "RTEST 4.7K to +3V3"
+    assert pin["external_components"] == ["U23 TRSF3232EIPWR", "RTEST2 0R", "ESDTEST"]
+    assert pin["fpga"] == {
+        "ball": "M10",
+        "board_signal": "UART2_TX",
+        "io_standard": "LVCMOS33",
+        "capabilities": ["gpio", "uart_tx", "rs232_via_transceiver"],
+        "evidence_tier": "cross_verified",
+        "sources": ["inventory:fixture-uart2"],
+    }
+    assert pin["recommendation"]["eligible"] is True
+    programming = pin["programming"]
+    assert programming["status"] == "verified_fpga"
+    assert programming["evidence_tier"] == "cross_verified"
+    assert "FPGA 输出" in programming["conclusion"]
+    assert "M10" in programming["conclusion"]
+    assert "U23 TRSF3232EIPWR" in programming["conclusion"]
+    assert "RS232_TX2" in programming["network_explanation"]
+    assert "UART2_TX" in programming["network_explanation"]
+    assert "output" in programming["hdl_guidance"]
+    assert "LVCMOS33" in programming["hdl_guidance"]
+    assert any("对端设备的接收端" in item for item in programming["connection_guidance"])
+    assert any("不能直接接 3.3V TTL/CMOS" in item for item in programming["connection_guidance"])
+    assert "LOCATION = M10" in programming["constraints"]
+    assert "IOSTANDARD = LVCMOS33" in programming["constraints"]
+    assert any("RTEST 4.7K" in item for item in programming["constraints"])
+    assert any("当前工程约束" in item for item in programming["risks"])
+    assert payload["interfaces"][0]["pins"] == ["1"]
+
+
+def test_raw_and_mechanical_pins_remain_non_recommendable_without_verified_mapping() -> None:
+    payload = build_board_data(
+        parse_kicad_pcb(FIXTURE),
+        fixture_inventory(),
+        fixture_annotations(),
+        board_name="Fixture board",
+    )
+    connector = next(item for item in payload["touchpoints"] if item["reference"] == "CON1")
+    hole = next(item for item in connector["pins"] if item["number"] == "")
+    testpoint = next(item for item in payload["touchpoints"] if item["reference"] == "TP1")
+
+    assert hole["mechanical"] is True
+    assert hole["adc_pulltype"] is None
+    assert hole["summary"] == "机械焊盘"
+    assert hole["evidence_tier"] == "board_database"
+    assert hole["recommendation"]["eligible"] is False
+    assert hole["programming"]["status"] == "not_programmable"
+    assert "机械" in hole["programming"]["conclusion"]
+    assert "不能生成 ADC" in hole["programming"]["hdl_guidance"]
+    assert testpoint["pins"][0]["evidence_tier"] == "board_database"
+    assert testpoint["pins"][0]["summary"] == "板内网络 BACK_SIG"
+    assert testpoint["pins"][0]["fpga"] is None
+    assert testpoint["pins"][0]["recommendation"]["eligible"] is False
+    assert testpoint["pins"][0]["programming"]["status"] == "board_only"
+    assert "BACK_SIG" in testpoint["pins"][0]["programming"]["network_explanation"]
+    assert "没有已验证 FPGA 路径" in testpoint["pins"][0]["programming"]["conclusion"]
+    assert "不能据此写" in testpoint["pins"][0]["programming"]["hdl_guidance"]
+
+
+def test_cross_verified_power_pin_programming_preserves_direction_level_and_path() -> None:
+    annotations = fixture_annotations()
+    annotations["touchpoints"]["CON1"]["pins"]["1"].update(
+        {
+            "summary": "+12V 主电源输入,经 F1 保护",
+            "path": ["CON1.1 +12V_VIN", "F1", "+12V"],
+            "direction": "input",
+            "external_level": "12V power input",
+            "function_category": "power",
+            "reserved": True,
+            "fixed_load_conflict": True,
+        }
+    )
+
+    payload = build_board_data(
+        parse_kicad_pcb(FIXTURE),
+        {"schema": "fixture", "board_id": "fixture-board", "pins": []},
+        annotations,
+        board_name="Fixture board",
+    )
+    connector = next(item for item in payload["touchpoints"] if item["reference"] == "CON1")
+    pin = next(item for item in connector["pins"] if item["number"] == "1")
+    programming = pin["programming"]
+
+    assert programming["status"] == "not_programmable"
+    assert programming["evidence_tier"] == "cross_verified"
+    assert "+12V 主电源输入" in programming["conclusion"]
+    assert "CON1.1 +12V_VIN -> F1 -> +12V" in programming["network_explanation"]
+    assert "12V power input" in programming["network_explanation"]
+    assert any("电源输入" in item for item in programming["connection_guidance"])
+    assert any("不要反向供电" in item for item in programming["risks"])
+
+
+def test_curated_programming_annotation_overrides_copy_but_keeps_evidence_sources() -> None:
+    annotations = fixture_annotations()
+    annotations["touchpoints"]["CON1"]["pins"]["1"]["programming"] = {
+        "conclusion": "人工复核后的编程结论",
+        "connection_guidance": ["按已验证线束定义连接。"],
+        "evidence_tier": "cross_verified",
+        "sources": ["fixture curated programming note"],
+    }
+
+    payload = build_board_data(
+        parse_kicad_pcb(FIXTURE),
+        fixture_inventory(),
+        annotations,
+        board_name="Fixture board",
+    )
+    pin = next(
+        item
+        for touchpoint in payload["touchpoints"]
+        if touchpoint["reference"] == "CON1"
+        for item in touchpoint["pins"]
+        if item["number"] == "1"
+    )
+
+    assert pin["programming"]["conclusion"] == "人工复核后的编程结论"
+    assert pin["programming"]["connection_guidance"] == ["按已验证线束定义连接。"]
+    assert "fixture curated programming note" in pin["programming"]["sources"]
+    assert "LVCMOS33" in pin["programming"]["hdl_guidance"]
+
+
+def test_direct_bidirectional_gpio_guidance_does_not_require_an_inout_port() -> None:
+    inventory = fixture_inventory()
+    inventory["pins"][0]["direction"] = "bidir"
+    inventory["pins"][0]["capability"] = ["gpio", "digital_input", "digital_output"]
+    annotations = fixture_annotations()
+    annotations["touchpoints"]["CON1"]["pins"]["1"].update(
+        {
+            "summary": "可配置的直接 FPGA GPIO",
+            "direction": "bidirectional",
+            "function_category": "gpio",
+        }
+    )
+
+    payload = build_board_data(
+        parse_kicad_pcb(FIXTURE),
+        inventory,
+        annotations,
+        board_name="Fixture board",
+    )
+    connector = next(item for item in payload["touchpoints"] if item["reference"] == "CON1")
+    pin = next(item for item in connector["pins"] if item["number"] == "1")
+    programming = pin["programming"]
+
+    assert programming["status"] == "verified_fpga"
+    assert "input、output 或 inout" in programming["hdl_guidance"]
+    assert "只有真正需要双向共享" in programming["hdl_guidance"]
+    assert "方向应为 bidirectional" not in programming["hdl_guidance"]
+    assert any("不要因为物理上可双向" in item for item in programming["risks"])
+
+
+def test_verified_mapping_keeps_semantic_signal_distinct_from_board_net() -> None:
+    inventory = fixture_inventory()
+    item = inventory["pins"][0]
+    item.update(
+        {
+            "signal": "MOTOR_EN_N",
+            "function_net": "RS232_TX2",
+            "connector_signal": "RS232_TX2",
+            "external_level": "3.3V LVCMOS",
+            "transceiver": None,
+            "capability": ["gpio", "motor_enable_n"],
+        }
+    )
+    annotations = fixture_annotations()
+    annotations["touchpoints"]["CON1"]["pins"] = {}
+
+    payload = build_board_data(
+        parse_kicad_pcb(FIXTURE), inventory, annotations, board_name="Fixture board"
+    )
+    pin = next(
+        item
+        for touchpoint in payload["touchpoints"]
+        if touchpoint["reference"] == "CON1"
+        for item in touchpoint["pins"]
+        if item["number"] == "1"
+    )
+
+    assert pin["net"] == "RS232_TX2"
+    assert pin["fpga"]["board_signal"] == "MOTOR_EN_N"
+    assert "MOTOR_EN_N" in pin["programming"]["conclusion"]
+    assert "RS232_TX2" in pin["programming"]["network_explanation"]
+
+
+def test_direct_inventory_mapping_fails_closed_when_connector_net_does_not_match_board() -> None:
+    inventory = fixture_inventory()
+    inventory["pins"][0]["connector_signal"] = "WRONG_CONNECTOR_NET"
+
+    with pytest.raises(ValueError, match="connector net mismatch CON1.1"):
+        build_board_data(
+            parse_kicad_pcb(FIXTURE),
+            inventory,
+            fixture_annotations(),
+            board_name="Fixture board",
+        )
+
+
+def test_generated_payload_matches_versioned_json_schema() -> None:
+    schema_path = ROOT / "schemas" / "board_viewer_data.schema.json"
+    schema = json.loads(schema_path.read_text(encoding="utf-8"))
+    payload = build_board_data(
+        parse_kicad_pcb(FIXTURE),
+        fixture_inventory(),
+        fixture_annotations(),
+        board_name="Fixture board",
+    )
+
+    Draft202012Validator(schema).validate(payload)
+
+
+def test_versioned_annotations_match_their_json_schema() -> None:
+    schema_path = ROOT / "schemas" / "board_viewer_annotations.schema.json"
+    schema = json.loads(schema_path.read_text(encoding="utf-8"))
+
+    Draft202012Validator(schema).validate(fixture_annotations())
+
+
+def templated_mcu_annotations() -> dict[str, object]:
+    annotations = fixture_annotations()
+    annotations["annotation_templates"] = {
+        "mcu-testpoint": {
+            "summary": "GD32 ${signal} 固件测试点",
+            "pins": {
+                "1": {
+                    "summary": "${signal},直连 ${device}.${package_pin}",
+                    "path": ["${reference}.1 ${signal}", "${device}.${package_pin}"],
+                    "evidence_tier": "cross_verified",
+                    "sources": ["fixture schematic MCU page"],
+                    "direction": "unknown",
+                    "external_level": "3.3V MCU GPIO",
+                    "function_category": "mcu_gpio",
+                    "mcu": {
+                        "device": "${device}",
+                        "family": "GD32F303CGT6",
+                        "pin": "${package_pin}",
+                        "signal": "${signal}",
+                        "capabilities": ["gpio"],
+                        "evidence_tier": "cross_verified",
+                        "sources": ["fixture schematic MCU page"],
+                    },
+                }
+            },
+        }
+    }
+    annotations["template_instances"] = {
+        "TP1": {
+            "template": "mcu-testpoint",
+            "variables": {
+                "reference": "TP1",
+                "device": "U27",
+                "package_pin": "10",
+                "signal": "PA0",
+            },
+        }
+    }
+    annotations["touchpoints"]["TP1"] = {
+        "summary": "GD32 PA0 调试测试点",
+        "pins": {},
+    }
+    return annotations
+
+
+def test_annotation_templates_expand_and_explicit_touchpoint_overrides_win() -> None:
+    payload = build_board_data(
+        parse_kicad_pcb(FIXTURE),
+        fixture_inventory(),
+        templated_mcu_annotations(),
+        board_name="Fixture board",
+    )
+
+    testpoint = next(item for item in payload["touchpoints"] if item["reference"] == "TP1")
+    pin = testpoint["pins"][0]
+    assert testpoint["summary"] == "GD32 PA0 调试测试点"
+    assert pin["summary"] == "PA0,直连 U27.10"
+    assert pin["path"] == ["TP1.1 PA0", "U27.10"]
+    assert pin["mcu"]["device"] == "U27"
+    assert pin["mcu"]["pin"] == "10"
+    assert pin["mcu"]["signal"] == "PA0"
+
+
+def test_annotation_template_missing_variable_fails_closed() -> None:
+    annotations = templated_mcu_annotations()
+    del annotations["template_instances"]["TP1"]["variables"]["package_pin"]
+
+    with pytest.raises(AnnotationError, match="missing template variable package_pin"):
+        build_board_data(
+            parse_kicad_pcb(FIXTURE),
+            fixture_inventory(),
+            annotations,
+            board_name="Fixture board",
+        )
+
+
+def test_verified_mcu_mapping_generates_firmware_guidance_but_never_fpga_adc() -> None:
+    payload = build_board_data(
+        parse_kicad_pcb(FIXTURE),
+        fixture_inventory(),
+        templated_mcu_annotations(),
+        board_name="Fixture board",
+    )
+
+    testpoint = next(item for item in payload["touchpoints"] if item["reference"] == "TP1")
+    pin = testpoint["pins"][0]
+    programming = pin["programming"]
+    assert programming["status"] == "verified_mcu"
+    assert "GD32" in programming["conclusion"]
+    assert "U27.10" in programming["conclusion"]
+    assert "PA0" in programming["hdl_guidance"]
+    assert pin["fpga"] is None
+    assert pin["recommendation"]["eligible"] is False
+
+
+def test_annotation_schema_allows_templates_and_verified_mcu_metadata() -> None:
+    schema_path = ROOT / "schemas" / "board_viewer_annotations.schema.json"
+    schema = json.loads(schema_path.read_text(encoding="utf-8"))
+
+    Draft202012Validator(schema).validate(templated_mcu_annotations())
+
+
+def test_product_annotations_fix_uart1_uart2_connector_paths() -> None:
+    annotation_path = ROOT / "config" / "board_viewer_annotations.fcb_fpga_mcu0611.json"
+    annotations = json.loads(annotation_path.read_text(encoding="utf-8"))
+
+    con77 = annotations["touchpoints"]["CON77"]
+    con78 = annotations["touchpoints"]["CON78"]
+    assert con77["summary"] == "UART1 RS-232 接口,经 U22 电平转换"
+    assert con78["summary"] == "UART2 RS-232 接口,经 U23 电平转换"
+    assert con77["pins"]["1"]["path"] == ["CON77.1 RS232_TX1", "U22 TRSF3232EIPWR", "UART1_TX", "FPGA L10"]
+    assert con77["pins"]["2"]["path"] == ["CON77.2 RS232_RX1", "U22 TRSF3232EIPWR", "UART1_RX", "FPGA M9"]
+    assert con78["pins"]["1"]["path"] == ["CON78.1 RS232_TX2", "U23 TRSF3232EIPWR", "UART2_TX", "FPGA M10"]
+    assert con78["pins"]["2"]["path"] == ["CON78.2 RS232_RX2", "U23 TRSF3232EIPWR", "UART2_RX", "FPGA N11"]
+    for connector in (con77, con78):
+        for number in ("3", "4"):
+            assert connector["pins"][number]["function_category"] == "ground"
+            assert connector["pins"][number]["external_level"] == "0V"
+        for number in ("5", "6"):
+            assert connector["pins"][number]["function_category"] == "ground"
+            assert "shield" in " ".join(connector["pins"][number]["path"]).lower()
+
+    interfaces = {item["id"]: item for item in annotations["interfaces"]}
+    assert set(interfaces) == {
+        "uart1-rs232",
+        "uart2-rs232",
+        "fpga-jtag",
+        "fpga-bank1-debug",
+        "gd32-swd",
+    }
+    assert interfaces["uart1-rs232"]["pins"] == ["1", "2", "3", "4"]
+    assert interfaces["uart2-rs232"]["pins"] == ["1", "2", "3", "4"]
+
+    expected_profile_references = {
+        "CON_11251W00_NPX_SX_4P": {
+            "CON12", "CON30", "CON31", "CON32", "CON33", "CON34", "CON35", "CON36",
+            "CON37", "CON38", "CON39", "CON40", "CON54", "CON58", "CON59", "CON60",
+            "CON61", "CON62", "CON63", "CON64", "CON65", "CON66", "CON67", "CON68",
+            "CON69", "CON70", "CON77", "CON78",
+        },
+        "CON_51541_003_P1D25": {
+            "CON53", "CON55", "CON56", "CON57", "CON79", "CON80", "CON81", "CON82",
+            "CON83", "CON84", "CON85", "CON86", "CON87", "CON88", "CON89", "CON90",
+            "CON91", "CON92", "CON93", "CON94", "CON95", "CON96", "CON97", "CON98",
+        },
+        "CON_3110_14P_P2D54": {"CON18", "CON27", "CON28", "CON29"},
+        "CON_C22930_1084N_X": {"CON2", "CON23"},
+        "CON_PZGM_B03_08P": {"CON8", "CON24", "CON25", "CON26"},
+        "J3_FPGA_JTAG_2X5": {"J3"},
+        "J19_FPGA_BANK1_DEBUG_1X5": {"J19"},
+        "J25_GD32_SWD_1X5": {"J25"},
+    }
+    profiles = annotations["connector_profiles"]
+    assert set(profiles) == set(expected_profile_references)
+    for profile_name, references in expected_profile_references.items():
+        assert set(profiles[profile_name]["references"]) == references
+        assert profiles[profile_name]["evidence_tier"] == "cross_verified"
+    all_profile_references = set().union(*expected_profile_references.values())
+    assert len(all_profile_references) == 65
+    assert sum(reference.startswith("CON") for reference in all_profile_references) == 62
+    assert "CON5" not in all_profile_references
+
+    schema = json.loads((ROOT / "schemas" / "board_viewer_annotations.schema.json").read_text(encoding="utf-8"))
+    Draft202012Validator(schema).validate(annotations)
+
+
+def test_product_annotations_cover_debug_headers_and_non_connector_j_pl_items() -> None:
+    annotation_path = ROOT / "config" / "board_viewer_annotations.fcb_fpga_mcu0611.json"
+    annotations = json.loads(annotation_path.read_text(encoding="utf-8"))
+
+    expected_j_pl = {
+        "J3", "J8", "J9", "J11", "J12", "J13", "J14", "J17", "J18",
+        "J19", "J20", "J21", "J22", "J25", "J26", "J27",
+        "PL2001", "PL2002", "PL2003",
+    }
+    assert expected_j_pl.issubset(annotations["touchpoints"])
+
+    profiles = annotations["connector_profiles"]
+    assert profiles["J3_FPGA_JTAG_2X5"]["references"] == ["J3"]
+    assert profiles["J19_FPGA_BANK1_DEBUG_1X5"]["references"] == ["J19"]
+    assert profiles["J25_GD32_SWD_1X5"]["references"] == ["J25"]
+    assert all(profiles[name]["component_value"] == "" for name in (
+        "J3_FPGA_JTAG_2X5",
+        "J19_FPGA_BANK1_DEBUG_1X5",
+        "J25_GD32_SWD_1X5",
+    ))
+
+    j3 = annotations["touchpoints"]["J3"]
+    assert "FPGA JTAG" in j3["summary"]
+    assert "EF2L45BG256B" in j3["summary"]
+    expected_jtag = {
+        "1": ("TCK", "A7", "input", "R63"),
+        "3": ("TDO", "C6", "output", "R65"),
+        "5": ("TMS", "B8", "input", "R67"),
+        "9": ("TDI", "A6", "input", "R69"),
+    }
+    for number, (signal, ball, direction, series_resistor) in expected_jtag.items():
+        pin = j3["pins"][number]
+        assert signal in pin["summary"]
+        assert pin["fpga"]["ball"] == ball
+        assert pin["direction"] == direction
+        assert pin["reserved"] is True
+        assert series_resistor in " ".join(pin["path"] + pin["external_components"])
+        assert "专用" in pin["programming"]["hdl_guidance"]
+    assert "不是给板子供电" in " ".join(
+        [
+            j3["pins"]["4"]["summary"],
+            j3["pins"]["4"]["programming"]["conclusion"],
+            *j3["pins"]["4"]["programming"]["connection_guidance"],
+        ]
+    )
+    for number in ("6", "7", "8"):
+        assert j3["pins"][number]["function_category"] == "not_connected"
+        assert j3["pins"][number]["reserved"] is True
+
+    assert "非专用JTAG" in annotations["touchpoints"]["J19"]["summary"]
+    j25 = annotations["touchpoints"]["J25"]
+    assert "GD32F303CGT6" in j25["summary"]
+    for number in ("2", "3", "5"):
+        assert "GD32F303CGT6" in j25["pins"][number]["programming"]["conclusion"]
+    for reference in ("PL2001", "PL2002", "PL2003"):
+        assert "非连接器" in annotations["touchpoints"][reference]["summary"]
+
+    interfaces = {item["id"]: item for item in annotations["interfaces"]}
+    assert interfaces["fpga-jtag"]["touchpoint"] == "J3"
+    assert interfaces["fpga-bank1-debug"]["touchpoint"] == "J19"
+    assert interfaces["gd32-swd"]["touchpoint"] == "J25"

+ 247 - 0
tests/board_viewer/test_generator.py

@@ -0,0 +1,247 @@
+from __future__ import annotations
+
+import json
+import hashlib
+import shutil
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[2]
+VIEWER_ROOT = ROOT / "tools" / "board-viewer"
+FIXTURE = Path(__file__).parent / "fixtures" / "parser_edge_cases.kicad_pcb"
+D356_FIXTURE = Path(__file__).parent / "fixtures" / "parser_edge_cases.d356"
+sys.path.insert(0, str(VIEWER_ROOT))
+
+from board_viewer.assets import sha256_file, validate_generated_assets  # noqa: E402
+from board_viewer.generator import (  # noqa: E402
+    GenerationConfig,
+    GenerationError,
+    generate_assets,
+    manifest_source_path,
+)
+
+
+@dataclass
+class FakeResult:
+    returncode: int = 0
+    stdout: str = ""
+    stderr: str = ""
+
+
+class FakeKiCad:
+    def __init__(self, *, fail_export: bool = False) -> None:
+        self.commands: list[list[str]] = []
+        self.fail_export = fail_export
+
+    def __call__(self, command: list[str], cwd: Path) -> FakeResult:
+        self.commands.append(command)
+        if command[-1] == "--version":
+            return FakeResult(stdout="10.0.4\n")
+        if command[1:3] == ["pcb", "import"]:
+            output = Path(command[command.index("--output") + 1])
+            report = Path(command[command.index("--report-file") + 1])
+            shutil.copy2(FIXTURE, output)
+            report.write_text(
+                json.dumps(
+                    {
+                        "errors": [],
+                        "warnings": [],
+                        "statistics": {"footprints": 2, "tracks": 0, "vias": 0, "zones": 0},
+                    }
+                ),
+                encoding="utf-8",
+            )
+            return FakeResult()
+        if command[1:4] == ["pcb", "export", "svg"]:
+            if self.fail_export:
+                return FakeResult(returncode=1, stderr="export failed")
+            output = Path(command[command.index("--output") + 1])
+            layers = command[command.index("--layers") + 1]
+            output.write_text(
+                '<?xml version="1.0"?><svg xmlns="http://www.w3.org/2000/svg" '
+                'width="30mm" height="10mm" viewBox="0 0 30 10">'
+                f'<title>fixture date 2026-07-21T12:00:00</title><desc>{layers}</desc></svg>',
+                encoding="utf-8",
+            )
+            return FakeResult()
+        if command[1:4] == ["pcb", "export", "ipcd356"]:
+            output = Path(command[command.index("--output") + 1])
+            shutil.copy2(D356_FIXTURE, output)
+            return FakeResult()
+        raise AssertionError(f"unexpected command: {command}")
+
+
+def write_json(path: Path, payload: object) -> None:
+    path.write_text(json.dumps(payload), encoding="utf-8")
+
+
+def generation_config(tmp_path: Path) -> GenerationConfig:
+    brd = tmp_path / "fixture.brd"
+    inventory = tmp_path / "inventory.json"
+    annotations = tmp_path / "annotations.json"
+    brd.write_bytes(b"fixture Allegro source")
+    write_json(
+        inventory,
+        {
+            "schema": "fixture-v1",
+            "board_id": "fixture-board",
+            "pins": [],
+        },
+    )
+    write_json(
+        annotations,
+        {
+            "schema": "board-viewer-annotations-v1",
+            "board_id": "fixture-board",
+            "connector_profiles": {},
+            "touchpoints": {},
+            "interfaces": [],
+            "photo_overlay": None,
+        },
+    )
+    return GenerationConfig(
+        brd_path=brd,
+        inventory_path=inventory,
+        annotations_path=annotations,
+        output_dir=tmp_path / "published" / "generated",
+        kicad_cli=tmp_path / "kicad-cli.exe",
+        board_name="Fixture board",
+        required_kicad_version="10.0.4",
+        expected_counts={"footprints": 2, "touchpoints": 2, "pads": 3},
+        expected_front_only=False,
+        temp_parent=tmp_path / "outside-worktree-temp",
+    )
+
+
+def test_generate_builds_valid_hashed_bundle_then_replaces_old_assets(tmp_path: Path) -> None:
+    config = generation_config(tmp_path)
+    config.kicad_cli.write_text("fake", encoding="utf-8")
+    config.output_dir.mkdir(parents=True)
+    (config.output_dir / "old.txt").write_text("old", encoding="utf-8")
+    runner = FakeKiCad()
+
+    result = generate_assets(config, runner=runner)
+
+    assert result["status"] == "pass"
+    assert not (config.output_dir / "old.txt").exists()
+    assert {path.name for path in config.output_dir.iterdir()} == {
+        "board-data.json",
+        "board-mask-edge.svg",
+        "board-silkscreen.svg",
+        "board-copper.svg",
+        "import-report.json",
+        "build-info.json",
+    }
+    build_info = json.loads((config.output_dir / "build-info.json").read_text(encoding="utf-8"))
+    assert build_info["counts"] == {"footprints": 2, "touchpoints": 2, "pads": 3}
+    assert build_info["toolchain"]["kicad"] == "10.0.4"
+    assert build_info["verification"]["ipcd356"] == {
+        "numbered_pads": 2,
+        "matched_pads": 2,
+        "record_types": {"317": 1, "327": 1},
+        "tolerance_mm": 0.02,
+    }
+    assert build_info["sources"]["brd"]["sha256"] == sha256_file(config.brd_path)
+    generator_sources = {
+        "generator_pipeline": VIEWER_ROOT / "board_viewer" / "generator.py",
+        "generator_data": VIEWER_ROOT / "board_viewer" / "data.py",
+        "generator_annotations": VIEWER_ROOT / "board_viewer" / "annotations.py",
+        "generator_eligibility": VIEWER_ROOT / "board_viewer" / "eligibility.py",
+        "generator_pcb": VIEWER_ROOT / "board_viewer" / "pcb.py",
+        "generator_sexpr": VIEWER_ROOT / "board_viewer" / "sexpr.py",
+        "generator_ipcd356": VIEWER_ROOT / "board_viewer" / "ipcd356.py",
+        "generator_photo": VIEWER_ROOT / "board_viewer" / "photo.py",
+        "generator_regression": VIEWER_ROOT / "board_viewer" / "regression.py",
+        "schema_data": ROOT / "schemas" / "board_viewer_data.schema.json",
+        "schema_annotations": ROOT / "schemas" / "board_viewer_annotations.schema.json",
+    }
+    for name, path in generator_sources.items():
+        assert build_info["sources"][name]["path"] == path.relative_to(ROOT).as_posix()
+        assert build_info["sources"][name]["sha256"] == sha256_file(path)
+    assert validate_generated_assets(config.output_dir).status == "pass"
+    for name, metadata in build_info["assets"].items():
+        assert metadata["sha256"] == sha256_file(config.output_dir / name)
+    assert all("F.Fab" not in " ".join(command) for command in runner.commands)
+    export_layers = {
+        command[command.index("--layers") + 1]
+        for command in runner.commands
+        if command[1:4] == ["pcb", "export", "svg"]
+    }
+    assert export_layers == {"F.Mask,Edge.Cuts", "F.SilkS,Edge.Cuts", "F.Cu,Edge.Cuts"}
+    assert "2026-07-21T12:00:00" not in (config.output_dir / "board-mask-edge.svg").read_text(encoding="utf-8")
+
+
+def test_generate_failure_keeps_previous_bundle_untouched(tmp_path: Path) -> None:
+    config = generation_config(tmp_path)
+    config.kicad_cli.write_text("fake", encoding="utf-8")
+    config.output_dir.mkdir(parents=True)
+    sentinel = config.output_dir / "old.txt"
+    sentinel.write_text("must survive", encoding="utf-8")
+
+    with pytest.raises(GenerationError, match="export failed"):
+        generate_assets(config, runner=FakeKiCad(fail_export=True))
+
+    assert sentinel.read_text(encoding="utf-8") == "must survive"
+
+
+def test_generate_rejects_wrong_kicad_version_before_import(tmp_path: Path) -> None:
+    config = generation_config(tmp_path)
+    config.kicad_cli.write_text("fake", encoding="utf-8")
+    runner = FakeKiCad()
+
+    def wrong_version(command: list[str], cwd: Path) -> FakeResult:
+        if command[-1] == "--version":
+            return FakeResult(stdout="9.0.0")
+        return runner(command, cwd)
+
+    with pytest.raises(GenerationError, match="requires KiCad 10.0.4"):
+        generate_assets(config, runner=wrong_version)
+
+    assert runner.commands == []
+
+
+def test_generate_rejects_temp_directory_inside_repository(tmp_path: Path) -> None:
+    config = generation_config(tmp_path)
+    config.kicad_cli.write_text("fake", encoding="utf-8")
+    config.temp_parent = ROOT / "tmp" / "board-viewer-test"
+
+    with pytest.raises(GenerationError, match="temporary directory must be outside repository"):
+        generate_assets(config, runner=FakeKiCad())
+
+
+def test_manifest_uses_portable_paths_for_repository_sources(tmp_path: Path) -> None:
+    assert manifest_source_path(ROOT / "config" / "pin_inventory.fcb_fpga_mcu0611.json") == "config/pin_inventory.fcb_fpga_mcu0611.json"
+    assert manifest_source_path(tmp_path / "external.brd") == str((tmp_path / "external.brd").resolve())
+
+
+def test_generate_includes_optional_hash_bound_photo_overlay(tmp_path: Path) -> None:
+    config = generation_config(tmp_path)
+    config.kicad_cli.write_text("fake", encoding="utf-8")
+    config.photo_root = tmp_path
+    photo = tmp_path / "board-photo.png"
+    photo.write_bytes(b"fixture-photo")
+    annotations = json.loads(config.annotations_path.read_text(encoding="utf-8"))
+    annotations["photo_overlay"] = {
+        "path": "board-photo.png",
+        "sha256": hashlib.sha256(b"fixture-photo").hexdigest(),
+        "control_points": [
+            {"image": {"x": 0, "y": 0}, "board": {"x": 0, "y": -10}},
+            {"image": {"x": 100, "y": 0}, "board": {"x": 30, "y": -10}},
+            {"image": {"x": 0, "y": 100}, "board": {"x": 0, "y": 0}},
+        ],
+    }
+    write_json(config.annotations_path, annotations)
+
+    generate_assets(config, runner=FakeKiCad())
+
+    board_data = json.loads((config.output_dir / "board-data.json").read_text(encoding="utf-8"))
+    build_info = json.loads((config.output_dir / "build-info.json").read_text(encoding="utf-8"))
+    assert (config.output_dir / "board-photo.png").read_bytes() == b"fixture-photo"
+    assert board_data["photo_overlay"]["asset"] == "board-photo.png"
+    assert board_data["photo_overlay"]["matrix"] == pytest.approx([0.3, 0.0, 0.0, 0.1, 0.0, 0.0])
+    assert "board-photo.png" in build_info["assets"]
+    assert build_info["sources"]["photo"]["path"] == str(photo.resolve())

+ 68 - 0
tests/board_viewer/test_ipcd356_alignment.py

@@ -0,0 +1,68 @@
+from __future__ import annotations
+
+import copy
+import sys
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[2]
+VIEWER_ROOT = ROOT / "tools" / "board-viewer"
+PCB_FIXTURE = Path(__file__).parent / "fixtures" / "parser_edge_cases.kicad_pcb"
+D356_FIXTURE = Path(__file__).parent / "fixtures" / "parser_edge_cases.d356"
+sys.path.insert(0, str(VIEWER_ROOT))
+
+from board_viewer.data import build_board_data  # noqa: E402
+from board_viewer.ipcd356 import IpCd356AlignmentError, validate_ipcd356_alignment  # noqa: E402
+from board_viewer.pcb import parse_kicad_pcb  # noqa: E402
+
+
+def fixture_payload() -> dict[str, object]:
+    return build_board_data(
+        parse_kicad_pcb(PCB_FIXTURE),
+        {"schema": "fixture", "board_id": "fixture", "pins": []},
+        {
+            "schema": "board-viewer-annotations-v1",
+            "board_id": "fixture",
+            "connector_profiles": {},
+            "touchpoints": {},
+            "interfaces": [],
+            "photo_overlay": None,
+        },
+        board_name="Fixture",
+    )
+
+
+def test_d356_alignment_independently_matches_every_numbered_pad() -> None:
+    result = validate_ipcd356_alignment(fixture_payload(), D356_FIXTURE)
+
+    assert result == {
+        "numbered_pads": 2,
+        "matched_pads": 2,
+        "record_types": {"317": 1, "327": 1},
+        "tolerance_mm": 0.02,
+    }
+
+
+def test_d356_alignment_reports_zero_for_an_unused_record_type() -> None:
+    payload = fixture_payload()
+    payload["touchpoints"] = [item for item in payload["touchpoints"] if item["reference"] == "CON1"]
+
+    result = validate_ipcd356_alignment(payload, D356_FIXTURE)
+
+    assert result["record_types"] == {"317": 1, "327": 0}
+
+
+@pytest.mark.parametrize("mutation", ["coordinate", "net"])
+def test_d356_alignment_fails_closed_on_coordinate_or_net_drift(tmp_path: Path, mutation: str) -> None:
+    text = D356_FIXTURE.read_text(encoding="ascii")
+    if mutation == "coordinate":
+        text = text.replace("X+004331Y+002756", "X+004731Y+002756")
+    else:
+        text = text.replace("RS232_TX2", "WRONG_NET ")
+    path = tmp_path / "drifted.d356"
+    path.write_text(text, encoding="ascii")
+
+    with pytest.raises(IpCd356AlignmentError, match="D356 alignment failed"):
+        validate_ipcd356_alignment(fixture_payload(), path)

+ 76 - 0
tests/board_viewer/test_pcb_parser.py

@@ -0,0 +1,76 @@
+from __future__ import annotations
+
+import math
+import sys
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[2]
+VIEWER_ROOT = ROOT / "tools" / "board-viewer"
+FIXTURE = Path(__file__).parent / "fixtures" / "parser_edge_cases.kicad_pcb"
+sys.path.insert(0, str(VIEWER_ROOT))
+
+from board_viewer.pcb import parse_kicad_pcb, select_touchpoints  # noqa: E402
+
+
+def test_parser_ignores_hidden_reference_placeholder_and_non_footprint_text() -> None:
+    board = parse_kicad_pcb(FIXTURE)
+
+    references = {footprint.reference for footprint in board.footprints}
+    touchpoints = {footprint.reference for footprint in select_touchpoints(board)}
+
+    assert references == {"CON1", "TP1"}
+    assert "${REFERENCE}" not in references
+    assert touchpoints == {"CON1", "TP1"}
+    assert "CON5" not in touchpoints
+
+
+def test_board_outline_bounds_are_extracted_from_edge_cuts() -> None:
+    board = parse_kicad_pcb(FIXTURE)
+
+    assert board.bounds == {"x": 0.0, "y": -10.0, "width": 30.0, "height": 10.0}
+
+
+def test_front_pad_coordinates_include_footprint_rotation_and_negative_y() -> None:
+    board = parse_kicad_pcb(FIXTURE)
+    connector = board.footprint_by_reference("CON1")
+    pin = connector.pad_by_number("1")
+
+    assert connector.component_value == "Fixture:Front"
+    assert connector.x == 10
+    assert connector.y == -5
+    assert connector.rotation == 90
+    assert connector.side == "front"
+    assert pin.x == pytest.approx(11)
+    assert pin.y == pytest.approx(-7)
+    assert pin.rotation == pytest.approx(30)
+    assert pin.net == "RS232_TX2"
+
+
+def test_back_pad_coordinates_follow_kicad_board_transform_without_extra_mirroring() -> None:
+    board = parse_kicad_pcb(FIXTURE)
+    testpoint = board.footprint_by_reference("TP1")
+    pin = testpoint.pad_by_number("1")
+
+    assert testpoint.side == "back"
+    assert pin.x == pytest.approx(23)
+    assert pin.y == pytest.approx(8)
+    assert pin.rotation == pytest.approx(30)
+
+
+def test_unnumbered_zero_size_np_thru_hole_is_mechanical_and_finite() -> None:
+    board = parse_kicad_pcb(FIXTURE)
+    connector = board.footprint_by_reference("CON1")
+    hole = next(pad for pad in connector.pads if pad.number == "")
+
+    assert hole.mechanical is True
+    assert hole.electrical is False
+    assert hole.width == 0
+    assert hole.height == 0
+    assert hole.drill_width == 1
+    assert hole.drill_height == 1
+    assert all(math.isfinite(value) for value in connector.bounds.values())
+    assert connector.bounds["width"] > 0
+    assert connector.bounds["height"] > 0

+ 102 - 0
tests/board_viewer/test_photo_overlay.py

@@ -0,0 +1,102 @@
+from __future__ import annotations
+
+import hashlib
+import sys
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[2]
+VIEWER_ROOT = ROOT / "tools" / "board-viewer"
+sys.path.insert(0, str(VIEWER_ROOT))
+
+from board_viewer.photo import PhotoOverlayError, prepare_photo_overlay, solve_affine_matrix  # noqa: E402
+
+
+CONTROL_POINTS = [
+    {"image": {"x": 0, "y": 0}, "board": {"x": 10, "y": -5}},
+    {"image": {"x": 100, "y": 0}, "board": {"x": 20, "y": -5}},
+    {"image": {"x": 0, "y": 50}, "board": {"x": 10, "y": 5}},
+]
+
+
+def test_affine_matrix_maps_image_pixels_to_view_coordinates() -> None:
+    matrix = solve_affine_matrix(
+        CONTROL_POINTS,
+        board_bounds={"x": 0, "y": -10, "width": 30, "height": 20},
+    )
+
+    assert matrix == pytest.approx([0.1, 0.0, 0.0, 0.2, 10.0, 5.0])
+
+
+def test_affine_matrix_rejects_collinear_control_points() -> None:
+    points = [
+        {"image": {"x": 0, "y": 0}, "board": {"x": 0, "y": 0}},
+        {"image": {"x": 10, "y": 10}, "board": {"x": 10, "y": 10}},
+        {"image": {"x": 20, "y": 20}, "board": {"x": 20, "y": 20}},
+    ]
+
+    with pytest.raises(PhotoOverlayError, match="non-collinear"):
+        solve_affine_matrix(points, board_bounds={"x": 0, "y": 0, "width": 20, "height": 20})
+
+
+def test_prepare_photo_overlay_checks_hash_copies_asset_and_emits_matrix(tmp_path: Path) -> None:
+    photo = tmp_path / "reference" / "board-photo.png"
+    photo.parent.mkdir(parents=True)
+    photo.write_bytes(b"fixture-photo")
+    digest = hashlib.sha256(b"fixture-photo").hexdigest()
+    assets = tmp_path / "generated"
+    assets.mkdir()
+
+    prepared = prepare_photo_overlay(
+        {
+            "path": "reference/board-photo.png",
+            "sha256": digest,
+            "control_points": CONTROL_POINTS,
+        },
+        repository_root=tmp_path,
+        assets_dir=assets,
+        board_bounds={"x": 0, "y": -10, "width": 30, "height": 20},
+    )
+
+    assert prepared is not None
+    assert prepared.data == {
+        "asset": "board-photo.png",
+        "sha256": digest,
+        "matrix": pytest.approx([0.1, 0.0, 0.0, 0.2, 10.0, 5.0]),
+        "control_point_count": 3,
+    }
+    assert prepared.asset_path.read_bytes() == b"fixture-photo"
+    assert prepared.source_path == photo
+
+
+def test_prepare_photo_overlay_rejects_hash_mismatch_and_path_escape(tmp_path: Path) -> None:
+    photo = tmp_path / "photo.png"
+    photo.write_bytes(b"fixture-photo")
+    assets = tmp_path / "generated"
+    assets.mkdir()
+
+    with pytest.raises(PhotoOverlayError, match="SHA-256"):
+        prepare_photo_overlay(
+            {"path": "photo.png", "sha256": "0" * 64, "control_points": CONTROL_POINTS},
+            repository_root=tmp_path,
+            assets_dir=assets,
+            board_bounds={"x": 0, "y": -10, "width": 30, "height": 20},
+        )
+    with pytest.raises(PhotoOverlayError, match="inside repository"):
+        prepare_photo_overlay(
+            {"path": "../outside.png", "sha256": "0" * 64, "control_points": CONTROL_POINTS},
+            repository_root=tmp_path,
+            assets_dir=assets,
+            board_bounds={"x": 0, "y": -10, "width": 30, "height": 20},
+        )
+
+
+def test_prepare_photo_overlay_accepts_missing_optional_configuration(tmp_path: Path) -> None:
+    assert prepare_photo_overlay(
+        None,
+        repository_root=tmp_path,
+        assets_dir=tmp_path,
+        board_bounds={"x": 0, "y": 0, "width": 1, "height": 1},
+    ) is None

+ 176 - 0
tests/board_viewer/test_product_functional_annotations.py

@@ -0,0 +1,176 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+BOARD_DATA = ROOT / "tools" / "board-viewer" / "generated" / "board-data.json"
+
+
+def load_board_data() -> dict[str, object]:
+    return json.loads(BOARD_DATA.read_text(encoding="utf-8"))
+
+
+def by_reference(payload: dict[str, object]) -> dict[str, dict[str, object]]:
+    return {item["reference"]: item for item in payload["touchpoints"]}
+
+
+def pins(touchpoint: dict[str, object]) -> dict[str, dict[str, object]]:
+    return {item["number"]: item for item in touchpoint["pins"] if item["number"]}
+
+
+def test_every_connector_and_testpoint_has_reviewed_functional_copy() -> None:
+    payload = load_board_data()
+    targets = [
+        item
+        for item in payload["touchpoints"]
+        if item["category"] in {"CON", "TP"}
+    ]
+
+    assert len(targets) == 91
+    assert all("用途未注释" not in item["summary"] for item in targets)
+    for touchpoint in targets:
+        reviewed_pins = [
+            pin
+            for pin in touchpoint["pins"]
+            if touchpoint["category"] == "TP" or pin["pad_role"] == "contact"
+        ]
+        assert reviewed_pins, touchpoint["reference"]
+        assert all(not pin["summary"].startswith("板内网络 ") for pin in reviewed_pins), touchpoint["reference"]
+
+
+def test_power_bmc_rs485_and_fan_connector_semantics_are_anchored() -> None:
+    refs = by_reference(load_board_data())
+
+    con2 = pins(refs["CON2"])
+    assert "+12V 主电源输入 1" in refs["CON2"]["summary"]
+    assert all(con2[number]["function_category"] == "ground" for number in ("1", "2", "3", "4"))
+    assert all("+12V" in con2[number]["summary"] for number in ("5", "6", "7", "8"))
+    assert con2["5"]["programming"]["evidence_tier"] == "cross_verified"
+    assert "板端电源输入" in con2["5"]["programming"]["network_explanation"]
+    assert "CON2.5 +12V_VIN" in con2["5"]["programming"]["network_explanation"]
+
+    con31 = pins(refs["CON31"])
+    assert "+12V_FAN7" in refs["CON31"]["summary"]
+    assert con31["3"]["fpga"]["ball"] == "D10"
+    assert con31["3"]["function_category"] == "fan_tach"
+    assert con31["4"]["fpga"]["ball"] == "E10"
+    assert con31["4"]["function_category"] == "pwm"
+    assert "Q105" in " ".join(con31["4"]["path"])
+    assert "FPGA high" in con31["4"]["polarity"]
+
+    con54 = pins(refs["CON54"])
+    assert "BMC" in refs["CON54"]["summary"]
+    assert con54["1"]["fpga"]["ball"] == "B14"
+    assert con54["2"]["fpga"]["ball"] == "A15"
+    assert con54["3"]["fpga"]["ball"] == "B16"
+    assert "open-drain" in con54["1"]["programming"]["hdl_guidance"]
+
+    con70 = pins(refs["CON70"])
+    assert "RS-485" in refs["CON70"]["summary"]
+    assert con70["1"]["summary"].startswith("RS-485 A")
+    assert con70["2"]["summary"].startswith("RS-485 B")
+    assert "U13" in " ".join(con70["1"]["path"])
+    assert all("R736 0R" in " ".join(con70[number]["path"]) for number in ("3", "4"))
+
+    con8 = pins(refs["CON8"])
+    assert "双风扇" in refs["CON8"]["summary"]
+    assert con8["4"]["fpga"]["ball"] == "D2"
+    assert con8["5"]["fpga"]["ball"] == "D3"
+    assert con8["7"]["fpga"]["ball"] == "C4"
+    assert con8["8"]["fpga"]["ball"] == "N10"
+
+
+def test_four_wire_fan_and_direct_gpio_connector_families_do_not_cross() -> None:
+    refs = by_reference(load_board_data())
+
+    con12_pin3 = pins(refs["CON12"])["3"]
+    assert con12_pin3["function_category"] == "gpio"
+    assert "input、output 或 inout" in con12_pin3["programming"]["hdl_guidance"]
+    assert "只有真正需要双向共享" in con12_pin3["programming"]["hdl_guidance"]
+
+    open_collector_refs = {"CON31", "CON32", "CON33", "CON34", "CON35", "CON68"}
+    for reference in open_collector_refs:
+        pin4 = pins(refs[reference])["4"]
+        assert pin4["function_category"] == "pwm"
+        assert any(item.startswith("Q") for item in pin4["path"]), reference
+        assert "FPGA high" in pin4["polarity"], reference
+
+    con33_pin4 = pins(refs["CON33"])["4"]
+    assert con33_pin4["fpga"]["ball"] == "C7"
+    assert "Q107" in " ".join(con33_pin4["path"])
+
+    con58_pin4 = pins(refs["CON58"])["4"]
+    assert con58_pin4["fpga"]["ball"] == "D15"
+    assert con58_pin4["fpga"]["board_signal"] == "MOTOR_STEP"
+    assert con58_pin4["function_category"] == "motor_step"
+    assert con58_pin4["active_level"] == "rising_edge"
+    assert "上升沿" in con58_pin4["programming"]["hdl_guidance"]
+    assert "高电平有效" not in con58_pin4["programming"]["hdl_guidance"]
+    assert not any(item.startswith("Q") for item in con58_pin4["path"])
+
+    con65_pin4 = pins(refs["CON65"])["4"]
+    assert con65_pin4["fpga"]["ball"] == "H14"
+    assert con65_pin4["fpga"]["board_signal"] == "MOTOR_DIR"
+    assert con65_pin4["active_level"] == "state"
+    assert "方向状态" in con65_pin4["programming"]["hdl_guidance"]
+    assert "高电平有效" not in con65_pin4["programming"]["hdl_guidance"]
+def test_remote_temperature_ptc_and_mcu_testpoint_paths_are_anchored() -> None:
+    refs = by_reference(load_board_data())
+
+    con53 = pins(refs["CON53"])
+    assert "CT7428 U6" in refs["CON53"]["summary"]
+    assert con53["1"]["path"][-1] == "U6.6 DP1"
+    assert con53["3"]["path"][-1] == "U6.7 DN"
+    assert con53["1"]["fpga"] is None
+    assert con53["1"]["programming"]["status"] == "board_only"
+    assert "open-drain" in con53["1"]["programming"]["hdl_guidance"]
+    assert "只拉低或释放" in con53["1"]["programming"]["hdl_guidance"]
+    assert "R811/R812" in " ".join(con53["1"]["programming"]["risks"])
+
+    con84 = pins(refs["CON84"])
+    con85 = pins(refs["CON85"])
+    assert con84["1"]["path"][-1] == "U24.2 DP5"
+    assert con85["1"]["path"][-1] == "U24.5 DP2"
+
+    con18 = pins(refs["CON18"])
+    assert "PTC1-PTC6" in refs["CON18"]["summary"]
+    assert con18["1"]["fpga"]["ball"] == "F16"
+    assert con18["1"]["fpga"]["board_signal"] == "HEAT1"
+    assert "Q52" in " ".join(con18["1"]["path"])
+    assert con18["11"]["net"] == "PTC6"
+    assert con18["13"]["net"] == "PTC6"
+    assert con18["11"]["fpga"]["ball"] == "R7"
+    assert all(con18[number]["function_category"] == "ground" for number in ("2", "4", "6", "8", "10", "12", "14"))
+
+    tp9 = pins(refs["TP9"])["1"]
+    assert refs["TP9"]["summary"] == "GD32 PA0 固件测试点"
+    assert tp9["mcu"]["device"] == "U27"
+    assert tp9["mcu"]["family"] == "GD32F303CGT6"
+    assert tp9["mcu"]["pin"] == "10"
+    assert tp9["programming"]["status"] == "verified_mcu"
+    assert tp9["fpga"] is None
+    assert tp9["recommendation"]["eligible"] is False
+
+    tp2 = pins(refs["TP2"])["1"]
+    tp7 = pins(refs["TP7"])["1"]
+    assert tp2["net"] == "+3V3"
+    assert tp7["net"] == "+3.3V"
+    assert "+3V3" in refs["TP2"]["summary"]
+    assert "+3.3V" in refs["TP7"]["summary"]
+
+
+def test_unverified_or_non_fpga_items_never_become_candidates_or_adc_sources() -> None:
+    payload = load_board_data()
+    for touchpoint in payload["touchpoints"]:
+        for pin in touchpoint["pins"]:
+            if (
+                pin["evidence_tier"] != "cross_verified"
+                or pin["fpga"] is None
+                or pin["function_category"] in {"power", "ground"}
+                or pin["pad_role"] != "contact"
+                or pin["reserved"] is True
+                or pin["fixed_load_conflict"] is True
+            ):
+                assert pin["recommendation"]["eligible"] is False, f"{touchpoint['reference']}.{pin['number']}"

+ 656 - 0
tests/board_viewer/test_product_regression.py

@@ -0,0 +1,656 @@
+from __future__ import annotations
+
+import copy
+import sys
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[2]
+VIEWER_ROOT = ROOT / "tools" / "board-viewer"
+sys.path.insert(0, str(VIEWER_ROOT))
+
+from board_viewer.regression import BoardRegressionError, validate_product_regression  # noqa: E402
+
+
+FOUR_CONTACT_REFS = {
+    "CON12", "CON30", "CON31", "CON32", "CON33", "CON34", "CON35", "CON36",
+    "CON37", "CON38", "CON39", "CON40", "CON54", "CON58", "CON59", "CON60",
+    "CON61", "CON62", "CON63", "CON64", "CON65", "CON66", "CON67", "CON68",
+    "CON69", "CON70", "CON77", "CON78",
+}
+THREE_CONTACT_REFS = {
+    "CON53", "CON55", "CON56", "CON57", "CON79", "CON80", "CON81", "CON82",
+    "CON83", "CON84", "CON85", "CON86", "CON87", "CON88", "CON89", "CON90",
+    "CON91", "CON92", "CON93", "CON94", "CON95", "CON96", "CON97", "CON98",
+}
+FOURTEEN_CONTACT_REFS = {"CON18", "CON27", "CON28", "CON29"}
+POWER_CONTACT_REFS = {"CON2", "CON23"}
+FAN_CONTACT_REFS = {"CON8", "CON24", "CON25", "CON26"}
+J3_GRID = [["6", "1"], ["7", "2"], ["8", "3"], ["9", "4"], ["10", "5"]]
+J3_NETS = {
+    "1": "N9532014",
+    "2": "GND",
+    "3": "N9532092",
+    "4": "N9532034",
+    "5": "N9532142",
+    "6": "Net_649",
+    "7": "Net_650",
+    "8": "Net_648",
+    "9": "N9532240",
+    "10": "GND",
+}
+J3_SIGNALS = {
+    "1": ("FPGA_TCK", "A7", "input", "jtag_tck", "R63"),
+    "3": ("FPGA_TDO", "C6", "output", "jtag_tdo", "R65"),
+    "5": ("FPGA_TMS", "B8", "input", "jtag_tms", "R67"),
+    "9": ("FPGA_TDI", "A6", "input", "jtag_tdi", "R69"),
+}
+
+
+def expected_connector_contract(reference: str) -> tuple[str, list[list[str]], list[str], int]:
+    if reference in FOUR_CONTACT_REFS:
+        order = ["1", "2", "3", "4"] if reference in {"CON54", "CON77", "CON78"} else ["4", "3", "2", "1"]
+        return "CON_11251W00_NPX_SX_4P", [[number] for number in order], ["5", "6"], 0
+    if reference in THREE_CONTACT_REFS:
+        return "CON_51541_003_P1D25", [["3", "2", "1"]], ["4", "5"], 0
+    if reference in FOURTEEN_CONTACT_REFS:
+        return (
+            "CON_3110_14P_P2D54",
+            [
+                ["13", "11", "9", "7", "5", "3", "1"],
+                ["14", "12", "10", "8", "6", "4", "2"],
+            ],
+            [],
+            0,
+        )
+    if reference == "CON23":
+        return "CON_C22930_1084N_X", [["5", "1"], ["6", "2"], ["7", "3"], ["8", "4"]], ["9", "10"], 2
+    if reference == "CON2":
+        return "CON_C22930_1084N_X", [["4", "8"], ["3", "7"], ["2", "6"], ["1", "5"]], ["9", "10"], 2
+    if reference in FAN_CONTACT_REFS:
+        return "CON_PZGM_B03_08P", [[str(number)] for number in range(8, 0, -1)], [], 1
+    raise AssertionError(f"missing test connector contract for {reference}")
+
+
+def connector_fixture(reference: str) -> dict[str, object]:
+    profile, grid, shields, mechanical_count = expected_connector_contract(reference)
+    contact_order = [number for row in grid for number in row]
+    pins: list[dict[str, object]] = []
+    for board_order, number in enumerate(contact_order, start=1):
+        row = next(index for index, values in enumerate(grid, start=1) if number in values)
+        pins.append(
+            {
+                "id": f"{reference}.contact-{number}",
+                "number": number,
+                "pad_role": "contact",
+                "row": row,
+                "column": grid[row - 1].index(number) + 1,
+                "board_order": board_order,
+                "net": f"{reference}_{number}",
+                "path": [],
+                "fpga": None,
+                "mechanical": False,
+                "electrical": True,
+                "reserved": False,
+                "function_category": "unknown",
+                "evidence_tier": "board_database",
+                "programming": {
+                    "status": "board_only",
+                    "conclusion": f"Board-only {reference}.{number}",
+                    "network_explanation": f"Raw network {reference}_{number}",
+                    "hdl_guidance": "No verified FPGA path",
+                    "connection_guidance": ["Verify before connecting"],
+                    "constraints": [],
+                    "risks": ["Name is not proof"],
+                    "evidence_tier": "board_database",
+                    "sources": ["fixture"],
+                },
+                "recommendation": {"eligible": False, "reasons": ["pin_evidence_not_verified"]},
+            }
+        )
+    pins.extend(
+        {
+            "id": f"{reference}.shield-{number}",
+            "number": number,
+            "pad_role": "shield",
+            "row": None,
+            "column": None,
+            "board_order": None,
+            "net": "GND",
+            "path": [],
+            "fpga": None,
+            "mechanical": False,
+            "electrical": True,
+            "reserved": False,
+            "function_category": "ground",
+            "evidence_tier": "board_database",
+            "programming": {
+                "status": "not_programmable",
+                "conclusion": "Shield pad",
+                "network_explanation": "Grounded shell",
+                "hdl_guidance": "No ADC",
+                "connection_guidance": ["Not an external contact"],
+                "constraints": [],
+                "risks": ["Do not count as a pin"],
+                "evidence_tier": "board_database",
+                "sources": ["fixture"],
+            },
+            "recommendation": {"eligible": False, "reasons": ["not_connector_contact"]},
+        }
+        for number in shields
+    )
+    pins.extend(
+        {
+            "id": f"{reference}.mechanical-{index}",
+            "number": "",
+            "pad_role": "mechanical",
+            "row": None,
+            "column": None,
+            "board_order": None,
+            "net": None,
+            "path": [],
+            "fpga": None,
+            "mechanical": True,
+            "electrical": False,
+            "reserved": False,
+            "function_category": "unknown",
+            "evidence_tier": "board_database",
+            "programming": {
+                "status": "not_programmable",
+                "conclusion": "Mechanical hole",
+                "network_explanation": "No electrical net",
+                "hdl_guidance": "No ADC",
+                "connection_guidance": ["Do not wire"],
+                "constraints": [],
+                "risks": ["Mechanical only"],
+                "evidence_tier": "board_database",
+                "sources": ["fixture"],
+            },
+            "recommendation": {"eligible": False, "reasons": ["mechanical_or_non_electrical"]},
+        }
+        for index in range(1, mechanical_count + 1)
+    )
+    return {
+        "reference": reference,
+        "side": "front",
+        "connector": {
+            "profile": profile,
+            "review_status": "cross_verified",
+            "view": "board_front",
+            "contact_count": len(contact_order),
+            "auxiliary_pad_count": len(shields) + mechanical_count,
+            "rows": len(grid),
+            "columns": len(grid[0]),
+            "contact_grid": grid,
+            "contact_order": contact_order,
+            "sources": ["test cross-check"],
+        },
+        "pins": pins,
+    }
+
+
+def j3_fixture() -> dict[str, object]:
+    order = [number for row in J3_GRID for number in row]
+    pins: list[dict[str, object]] = []
+    for board_order, number in enumerate(order, start=1):
+        row = next(index for index, values in enumerate(J3_GRID, start=1) if number in values)
+        signal = J3_SIGNALS.get(number)
+        fpga = None
+        if signal is not None:
+            board_signal, ball, direction, function_category, series_resistor = signal
+            fpga = {
+                "ball": ball,
+                "board_signal": board_signal,
+                "io_standard": "Dedicated JTAG (VREF 3.3V)",
+                "capabilities": ["jtag", function_category],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture schematic and PCB"],
+            }
+            programming = {
+                "status": "verified_fpga",
+                "conclusion": f"{board_signal} dedicated JTAG path to U3.{ball}",
+                "network_explanation": f"J3.{number} reaches {board_signal} through reviewed protection and series parts",
+                "hdl_guidance": "Dedicated FPGA configuration pin; do not declare it as a normal RTL GPIO or ADC pin.",
+                "connection_guidance": ["Connect only to the matching JTAG probe signal."],
+                "constraints": ["No user ADC assignment"],
+                "risks": ["Check cable orientation and target VREF before programming."],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture schematic and PCB"],
+            }
+            summary = board_signal.removeprefix("FPGA_")
+            path = [f"J3.{number}", f"{series_resistor} 22R", board_signal, f"U3.{ball}"]
+        elif number in {"2", "10"}:
+            direction, function_category, summary = "passive", "ground", "GND"
+            path = [f"J3.{number}", "GND"]
+            programming = {
+                "status": "not_programmable",
+                "conclusion": "JTAG ground reference",
+                "network_explanation": f"J3.{number} is board GND",
+                "hdl_guidance": "No RTL or ADC assignment",
+                "connection_guidance": ["Connect to probe ground."],
+                "constraints": [],
+                "risks": ["Maintain a common reference."],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture schematic and PCB"],
+            }
+        elif number == "4":
+            direction, function_category, summary = "passive", "reference_voltage", "VREF"
+            path = ["J3.4", "N9532034", "R61 0R", "+3V3"]
+            programming = {
+                "status": "not_programmable",
+                "conclusion": "VREF is a 3.3V target reference, not board power.",
+                "network_explanation": "J3.4 reaches +3V3 through R61 0R and local decoupling.",
+                "hdl_guidance": "No RTL or ADC assignment",
+                "connection_guidance": ["Probe senses this voltage; do not use it to power the board."],
+                "constraints": [],
+                "risks": ["Back-powering can damage hardware."],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture schematic and PCB"],
+            }
+        else:
+            direction, function_category, summary = "passive", "not_connected", "NC"
+            path = [f"J3.{number}", "NC"]
+            programming = {
+                "status": "not_programmable",
+                "conclusion": "Unconnected JTAG header position",
+                "network_explanation": f"J3.{number} has no path beyond the connector pad.",
+                "hdl_guidance": "No RTL or ADC assignment",
+                "connection_guidance": ["Leave unconnected."],
+                "constraints": [],
+                "risks": ["Do not repurpose without a board revision."],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture schematic and PCB"],
+            }
+        pins.append(
+            {
+                "id": f"J3.pad-{number}",
+                "number": number,
+                "pad_role": "contact",
+                "row": row,
+                "column": J3_GRID[row - 1].index(number) + 1,
+                "board_order": board_order,
+                "net": J3_NETS[number],
+                "path": path,
+                "fpga": fpga,
+                "mechanical": False,
+                "electrical": True,
+                "direction": direction,
+                "external_level": "0V" if function_category == "ground" else "3.3V JTAG",
+                "reserved": True,
+                "fixed_load_conflict": False,
+                "function_category": function_category,
+                "evidence_tier": "cross_verified",
+                "programming": programming,
+                "recommendation": {"eligible": False, "reasons": ["reserved"]},
+                "summary": summary,
+            }
+        )
+    return {
+        "reference": "J3",
+        "side": "front",
+        "summary": "FPGA JTAG 调试/配置接口(专用配置脚)",
+        "connector": {
+            "profile": "J3_FPGA_JTAG_2X5",
+            "review_status": "cross_verified",
+            "view": "board_front",
+            "contact_count": 10,
+            "auxiliary_pad_count": 0,
+            "rows": 5,
+            "columns": 2,
+            "contact_grid": J3_GRID,
+            "contact_order": order,
+            "sources": ["fixture schematic and PCB"],
+        },
+        "pins": pins,
+    }
+
+
+def touchpoint(payload: dict[str, object], reference: str) -> dict[str, object]:
+    return next(item for item in payload["touchpoints"] if item["reference"] == reference)
+
+
+def pin(payload: dict[str, object], reference: str, number: str) -> dict[str, object]:
+    return next(item for item in touchpoint(payload, reference)["pins"] if item["number"] == number)
+
+
+def product_payload() -> dict[str, object]:
+    connector_references = sorted(
+        FOUR_CONTACT_REFS | THREE_CONTACT_REFS | FOURTEEN_CONTACT_REFS | POWER_CONTACT_REFS | FAN_CONTACT_REFS
+    )
+    touchpoints = [connector_fixture(reference) for reference in connector_references]
+    con78 = next(item for item in touchpoints if item["reference"] == "CON78")
+    pins = {pin["number"]: pin for pin in con78["pins"] if pin["number"]}
+    pins["1"].update(
+        {
+            "net": "RS232_TX2",
+            "path": ["CON78.1 RS232_TX2", "U23 TRSF3232EIPWR", "UART2_TX", "FPGA M10"],
+            "fpga": {"ball": "M10", "evidence_tier": "cross_verified"},
+            "reserved": True,
+            "function_category": "uart_tx",
+            "evidence_tier": "cross_verified",
+            "recommendation": {"eligible": False, "reasons": ["reserved"]},
+            "programming": {
+                "status": "verified_fpga",
+                "conclusion": "FPGA output UART2_TX M10 through U23",
+                "network_explanation": "RS232_TX2 through U23 to UART2_TX",
+                "hdl_guidance": "output LVCMOS33",
+                "connection_guidance": ["Connect to peer RX", "Do not connect to 3.3V TTL"],
+                "constraints": ["LOCATION = M10", "IOSTANDARD = LVCMOS33"],
+                "risks": ["reserved", "check current constraints"],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture"],
+            },
+        }
+    )
+    pins["2"].update(
+        {
+            "net": "RS232_RX2",
+            "path": ["CON78.2 RS232_RX2", "U23 TRSF3232EIPWR", "UART2_RX", "FPGA N11"],
+            "fpga": {"ball": "N11", "evidence_tier": "cross_verified"},
+            "reserved": True,
+            "function_category": "uart_rx",
+            "evidence_tier": "cross_verified",
+            "recommendation": {"eligible": False, "reasons": ["reserved"]},
+            "programming": {
+                "status": "verified_fpga",
+                "conclusion": "FPGA input UART2_RX N11 through U23",
+                "network_explanation": "RS232_RX2 through U23 to UART2_RX",
+                "hdl_guidance": "input LVCMOS33",
+                "connection_guidance": ["Connect to peer TX", "Do not connect to 3.3V TTL"],
+                "constraints": ["LOCATION = N11", "IOSTANDARD = LVCMOS33"],
+                "risks": ["reserved", "check current constraints"],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture"],
+            },
+        }
+    )
+    for number in ("3", "4"):
+        pins[number].update({"net": "GND", "path": [f"CON78.{number} GND", "Board ground"], "function_category": "ground"})
+    con30 = next(item for item in touchpoints if item["reference"] == "CON30")
+    con30_pin4 = next(pin for pin in con30["pins"] if pin["number"] == "4")
+    con30_pin4.update(
+        {
+            "net": "FAN_GPIO4",
+            "summary": "MOTOR_EN_N",
+            "direction": "output",
+            "external_level": "3.3V LVCMOS",
+            "active_level": "low",
+            "board_pull": "R937 4.7K to +3V3",
+            "evidence_tier": "cross_verified",
+            "fpga": {"ball": "A10", "board_signal": "MOTOR_EN_N", "io_standard": "LVCMOS33", "evidence_tier": "cross_verified"},
+            "programming": {
+                "status": "verified_fpga",
+                "conclusion": "FPGA output MOTOR_EN_N A10",
+                "network_explanation": "FAN_GPIO4 maps to MOTOR_EN_N",
+                "hdl_guidance": "output LVCMOS33 low active",
+                "connection_guidance": ["board output"],
+                "constraints": ["LOCATION = A10", "IOSTANDARD = LVCMOS33", "有效电平:低电平"],
+                "risks": ["reserved", "check current constraints"],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture"],
+            },
+        }
+    )
+    con31 = next(item for item in touchpoints if item["reference"] == "CON31")
+    con31_pin4 = next(pin for pin in con31["pins"] if pin["number"] == "4")
+    con31_pin4.update(
+        {
+            "net": "N9971986",
+            "summary": "fan PWM open-collector output",
+            "path": ["CON31.4 N9971986", "Q105 collector", "Q105 base = FAN_GPIO6", "R665", "U3.E10"],
+            "evidence_tier": "cross_verified",
+            "external_level": "open-collector fan control",
+            "function_category": "pwm",
+            "reserved": False,
+            "fixed_load_conflict": False,
+            "polarity": "FPGA high -> Q105 on -> connector low",
+            "fpga": {
+                "ball": "E10",
+                "board_signal": "FAN_GPIO6",
+                "io_standard": "LVCMOS33",
+                "capabilities": ["gpio", "pwm_output", "fan_pwm"],
+                "evidence_tier": "cross_verified",
+            },
+            "programming": {
+                "status": "verified_fpga",
+                "conclusion": "FPGA E10 drives FAN_GPIO6 through Q105 to CON31.4",
+                "network_explanation": "N9971986 is the Q105 collector side, not the FPGA logic net",
+                "hdl_guidance": "output LVCMOS33; FPGA high pulls connector low",
+                "connection_guidance": ["use as open-collector fan PWM"],
+                "constraints": ["LOCATION = E10", "IOSTANDARD = LVCMOS33"],
+                "risks": ["inverted at Q105", "check current constraints"],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture"],
+            },
+        }
+    )
+    con58 = next(item for item in touchpoints if item["reference"] == "CON58")
+    con58_pin4 = next(pin for pin in con58["pins"] if pin["number"] == "4")
+    con58_pin4.update(
+        {
+            "net": "FAN_GPIO38",
+            "summary": "MOTOR_STEP rising-edge pulse output",
+            "direction": "output",
+            "external_level": "3.3V LVCMOS",
+            "function_category": "motor_step",
+            "active_level": "rising_edge",
+            "reserved": True,
+            "fixed_load_conflict": True,
+            "evidence_tier": "cross_verified",
+            "fpga": {
+                "ball": "D15",
+                "board_signal": "MOTOR_STEP",
+                "io_standard": "LVCMOS33",
+                "evidence_tier": "cross_verified",
+            },
+            "programming": {
+                "status": "verified_fpga",
+                "conclusion": "MOTOR_STEP D15 is a pulse output, not a level enable",
+                "network_explanation": "FAN_GPIO38 maps to MOTOR_STEP through R698",
+                "hdl_guidance": "output pulses; each 上升沿 is one step event",
+                "connection_guidance": ["connect to STEP input"],
+                "constraints": ["LOCATION = D15", "IOSTANDARD = LVCMOS33"],
+                "risks": ["verify pulse timing"],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture"],
+            },
+        }
+    )
+    con65 = next(item for item in touchpoints if item["reference"] == "CON65")
+    con65_pin4 = next(pin for pin in con65["pins"] if pin["number"] == "4")
+    con65_pin4.update(
+        {
+            "net": "FAN_GPIO32",
+            "summary": "MOTOR_DIR direction state output",
+            "direction": "output",
+            "external_level": "3.3V LVCMOS",
+            "function_category": "motor_direction",
+            "active_level": "state",
+            "reserved": True,
+            "fixed_load_conflict": True,
+            "evidence_tier": "cross_verified",
+            "fpga": {
+                "ball": "H14",
+                "board_signal": "MOTOR_DIR",
+                "io_standard": "LVCMOS33",
+                "evidence_tier": "cross_verified",
+            },
+            "programming": {
+                "status": "verified_fpga",
+                "conclusion": "MOTOR_DIR H14 selects a direction state",
+                "network_explanation": "FAN_GPIO32 maps to MOTOR_DIR through R692",
+                "hdl_guidance": "output 方向状态; stabilize before STEP",
+                "connection_guidance": ["connect to DIR input"],
+                "constraints": ["LOCATION = H14", "IOSTANDARD = LVCMOS33"],
+                "risks": ["0/1 mechanical direction depends on wiring"],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture"],
+            },
+        }
+    )
+    con53 = next(item for item in touchpoints if item["reference"] == "CON53")
+    con53_pin1 = next(pin for pin in con53["pins"] if pin["number"] == "1")
+    con53_pin1.update(
+        {
+            "function_category": "remote_temperature",
+            "reserved": True,
+            "fixed_load_conflict": True,
+            "evidence_tier": "cross_verified",
+            "programming": {
+                "status": "board_only",
+                "conclusion": "CT7428 remote-diode analog input",
+                "network_explanation": "temperature is read through TEMP_SCL/TEMP_SDA",
+                "hdl_guidance": "TEMP I2C must be open-drain and 只拉低或释放",
+                "connection_guidance": ["connect a remote diode pair"],
+                "constraints": [],
+                "risks": ["R811/R812 and other option links require BOM review"],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture"],
+            },
+        }
+    )
+    j_touchpoints = [{"reference": f"J{number}", "side": "front", "pins": []} for number in range(1, 17)]
+    j_touchpoints[2] = j3_fixture()
+    touchpoints.extend(j_touchpoints)
+    touchpoints.extend({"reference": f"PL{number}", "side": "front", "pins": []} for number in range(1, 4))
+    touchpoints.extend(
+        {"reference": f"TP{number}", "side": "front", "pins": []}
+        for number in [*range(1, 8), *range(9, 31)]
+    )
+    tp9 = next(item for item in touchpoints if item["reference"] == "TP9")
+    tp9["pins"] = [
+        {
+            "number": "1",
+            "pad_role": "contact",
+            "mechanical": False,
+            "electrical": True,
+            "function_category": "mcu_gpio",
+            "evidence_tier": "cross_verified",
+            "fpga": None,
+            "mcu": {
+                "device": "U27",
+                "family": "GD32F303CGT6",
+                "pin": "10",
+                "signal": "PA0",
+                "evidence_tier": "cross_verified",
+            },
+            "programming": {
+                "status": "verified_mcu",
+                "conclusion": "GD32F303CGT6 U27.10 PA0 test point",
+                "network_explanation": "TP9 maps to U27.10 PA0",
+                "hdl_guidance": "configure in GD32 firmware",
+                "connection_guidance": ["use a high-impedance probe"],
+                "constraints": [],
+                "risks": ["check current MCU mux"],
+                "evidence_tier": "cross_verified",
+                "sources": ["fixture"],
+            },
+            "recommendation": {"eligible": False, "reasons": ["not_fpga"]},
+        }
+    ]
+    return {
+        "counts": {
+            "footprints": 1052,
+            "touchpoints": 110,
+            "pads": 472,
+            "connector_contacts": 288,
+            "connector_auxiliary_pads": 116,
+            "categories": {"CON": 62, "J": 16, "PL": 3, "TP": 29},
+            "sides": {"front": 110, "back": 0},
+        },
+        "touchpoints": touchpoints,
+    }
+
+
+def test_current_product_regression_accepts_verified_con78_anchor() -> None:
+    validate_product_regression(product_payload())
+
+
+@pytest.mark.parametrize(
+    "mutation, expected",
+    [
+        (lambda payload: payload["counts"].update({"connector_contacts": 287}), "connector_contacts=287"),
+        (lambda payload: payload["touchpoints"][0]["connector"].update({"review_status": "unknown"}), "not cross-verified"),
+        (lambda payload: payload["touchpoints"][0]["connector"]["contact_order"].reverse(), "contact order"),
+        (lambda payload: payload["touchpoints"][0]["pins"][0].update({"pad_role": "shield"}), "contact pin role"),
+    ],
+)
+def test_all_connector_profiles_and_board_front_orders_are_regression_anchors(mutation, expected: str) -> None:
+    payload = copy.deepcopy(product_payload())
+    mutation(payload)
+
+    with pytest.raises(BoardRegressionError, match=expected):
+        validate_product_regression(payload)
+
+
+@pytest.mark.parametrize(
+    "mutation, expected",
+    [
+        (lambda payload: payload["counts"].update({"pads": 471}), "pads=471"),
+        (lambda payload: payload["counts"]["categories"].update({"CON": 61}), "CON=61"),
+        (lambda payload: payload["counts"]["sides"].update({"back": 1}), "back=1"),
+        (lambda payload: payload["touchpoints"][1].update({"reference": "CON5"}), "CON5"),
+        (lambda payload: pin(payload, "CON78", "1").update({"net": "WRONG"}), "CON78.1"),
+        (lambda payload: pin(payload, "CON78", "2")["fpga"].update({"ball": "M10"}), "N11"),
+        (lambda payload: pin(payload, "CON78", "1").update({"path": ["CON78.1", "FPGA M10"]}), "U23"),
+    ],
+)
+def test_product_regression_fails_closed_on_anchor_drift(mutation, expected: str) -> None:
+    payload = copy.deepcopy(product_payload())
+    mutation(payload)
+
+    with pytest.raises(BoardRegressionError, match=expected):
+        validate_product_regression(payload)
+
+
+def test_any_recommendable_pin_must_satisfy_fail_closed_contract() -> None:
+    payload = product_payload()
+    pin = payload["touchpoints"][0]["pins"][2]
+    pin["recommendation"] = {"eligible": True, "reasons": []}
+
+    with pytest.raises(BoardRegressionError, match="recommendable pin violates contract"):
+        validate_product_regression(payload)
+
+
+@pytest.mark.parametrize(
+    "mutation, expected",
+    [
+        (lambda payload: pin(payload, "CON78", "1")["programming"].update({"status": "board_only"}), "CON78.1 programming"),
+        (lambda payload: pin(payload, "CON30", "4")["fpga"].update({"board_signal": "FAN_GPIO4"}), "MOTOR_EN_N"),
+        (lambda payload: pin(payload, "CON30", "4").update({"active_level": "high"}), "low active"),
+        (lambda payload: pin(payload, "CON31", "4")["programming"].update({"status": "board_only"}), "CON31.4 programming"),
+        (lambda payload: pin(payload, "CON58", "4").update({"active_level": "high"}), "MOTOR_STEP"),
+        (lambda payload: pin(payload, "CON65", "4").update({"active_level": "high"}), "MOTOR_DIR"),
+        (lambda payload: pin(payload, "CON53", "1")["programming"].update({"hdl_guidance": "push-pull"}), "CON53.1"),
+        (lambda payload: pin(payload, "TP9", "1")["mcu"].update({"family": "GD32F303CCT6"}), "TP9.1"),
+    ],
+)
+def test_programming_guidance_regression_anchors_fail_closed(mutation, expected: str) -> None:
+    payload = product_payload()
+    mutation(payload)
+
+    with pytest.raises(BoardRegressionError, match=expected):
+        validate_product_regression(payload)
+
+
+@pytest.mark.parametrize(
+    "mutation",
+    [
+        lambda payload: touchpoint(payload, "J3")["connector"].update(
+            {"contact_grid": [["1", "6"], ["2", "7"], ["3", "8"], ["4", "9"], ["5", "10"]]}
+        ),
+        lambda payload: pin(payload, "J3", "1")["fpga"].update({"ball": "A6"}),
+        lambda payload: pin(payload, "J3", "4")["programming"].update(
+            {"conclusion": "Generic 3.3V power pin"}
+        ),
+        lambda payload: pin(payload, "J3", "6").update({"function_category": "gpio"}),
+    ],
+)
+def test_j3_jtag_pinout_and_programming_semantics_are_regression_anchors(mutation) -> None:
+    payload = product_payload()
+    mutation(payload)
+
+    with pytest.raises(BoardRegressionError, match="J3"):
+        validate_product_regression(payload)

+ 126 - 0
tests/board_viewer/test_server.py

@@ -0,0 +1,126 @@
+from __future__ import annotations
+
+import json
+import shutil
+import sys
+import threading
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+import pytest
+
+
+ROOT = Path(__file__).resolve().parents[2]
+VIEWER_ROOT = ROOT / "tools" / "board-viewer"
+WEB_ROOT = VIEWER_ROOT / "web"
+GENERATED = VIEWER_ROOT / "generated"
+sys.path.insert(0, str(VIEWER_ROOT))
+
+from board_viewer.assets import AssetIntegrityError  # noqa: E402
+from board_viewer.server import create_server  # noqa: E402
+
+
+class RunningServer:
+    def __init__(self, generated: Path) -> None:
+        self.server = create_server(WEB_ROOT, generated, port=0, repository_root=ROOT)
+        self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
+
+    def __enter__(self) -> str:
+        self.thread.start()
+        host, port = self.server.server_address[:2]
+        return f"http://{host}:{port}"
+
+    def __exit__(self, exc_type, exc, traceback) -> None:
+        self.server.shutdown()
+        self.server.server_close()
+        self.thread.join(timeout=5)
+
+
+def request(url: str, *, method: str = "GET") -> tuple[int, bytes, dict[str, str]]:
+    req = urllib.request.Request(url, method=method)
+    try:
+        with urllib.request.urlopen(req, timeout=5) as response:
+            return response.status, response.read(), dict(response.headers.items())
+    except urllib.error.HTTPError as error:
+        return error.code, error.read(), dict(error.headers.items())
+
+
+def test_server_binds_loopback_and_serves_only_whitelisted_get_head_paths() -> None:
+    with RunningServer(GENERATED) as base:
+        status, body, headers = request(base + "/")
+        assert status == 200
+        assert "电路板选脚查看器" in body.decode("utf-8")
+        assert headers["X-Content-Type-Options"] == "nosniff"
+        assert "default-src 'self'" in headers["Content-Security-Policy"]
+
+        status, body, _ = request(base + "/generated/board-data.json", method="HEAD")
+        assert status == 200
+        assert body == b""
+
+        status, body, _ = request(base + "/api/status")
+        payload = json.loads(body)
+        assert status == 200
+        assert payload["status"] == "pass"
+        assert payload["recommendationsEnabled"] is True
+        assert payload["adcCopyEnabled"] is True
+
+
+@pytest.mark.parametrize(
+    "path",
+    [
+        "/../AGENTS.md",
+        "/%2e%2e/AGENTS.md",
+        "/generated/../web/index.html",
+        "/generated/%2e%2e/web/index.html",
+        "/C:/Windows/win.ini",
+        "/unknown.txt",
+    ],
+)
+def test_server_rejects_directory_traversal_and_arbitrary_files(path: str) -> None:
+    with RunningServer(GENERATED) as base:
+        status, _, _ = request(base + path)
+
+    assert status == 404
+
+
+@pytest.mark.parametrize("method", ["POST", "PUT", "PATCH", "DELETE"])
+def test_server_rejects_mutating_methods(method: str) -> None:
+    with RunningServer(GENERATED) as base:
+        status, _, headers = request(base + "/", method=method)
+
+    assert status == 405
+    assert headers["Allow"] == "GET, HEAD"
+
+
+def test_server_refuses_non_loopback_bind() -> None:
+    with pytest.raises(ValueError, match="127.0.0.1"):
+        create_server(WEB_ROOT, GENERATED, host="0.0.0.0", port=0, repository_root=ROOT)
+
+
+def test_server_refuses_tampered_generated_asset(tmp_path: Path) -> None:
+    copied = tmp_path / "generated"
+    shutil.copytree(GENERATED, copied)
+    (copied / "board-data.json").write_text("tampered", encoding="utf-8")
+
+    with pytest.raises(AssetIntegrityError, match="board-data.json"):
+        create_server(WEB_ROOT, copied, port=0, repository_root=ROOT)
+
+
+def test_server_starts_read_only_but_disables_recommendations_when_sources_are_stale(tmp_path: Path) -> None:
+    copied = tmp_path / "generated"
+    shutil.copytree(GENERATED, copied)
+    build_info_path = copied / "build-info.json"
+    build_info = json.loads(build_info_path.read_text(encoding="utf-8"))
+    build_info["sources"]["annotations"]["path"] = "config/does-not-exist.json"
+    build_info_path.write_text(json.dumps(build_info), encoding="utf-8")
+
+    with RunningServer(copied) as base:
+        status, body, _ = request(base + "/api/status")
+        payload = json.loads(body)
+
+    assert status == 200
+    assert payload["status"] == "stale_sources"
+    assert payload["recommendationsEnabled"] is False
+    assert payload["adcCopyEnabled"] is False
+    assert payload["staleSources"] == ["missing:annotations"]

+ 87 - 0
tests/board_viewer/test_web_shell.py

@@ -0,0 +1,87 @@
+from __future__ import annotations
+
+from html.parser import HTMLParser
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+WEB = ROOT / "tools" / "board-viewer" / "web"
+
+
+class ShellParser(HTMLParser):
+    def __init__(self) -> None:
+        super().__init__()
+        self.ids: set[str] = set()
+        self.roles: set[str] = set()
+        self.labels: set[str] = set()
+        self.lang = ""
+        self.scripts: list[str] = []
+        self.styles: list[str] = []
+
+    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
+        values = dict(attrs)
+        if tag == "html":
+            self.lang = values.get("lang") or ""
+        if values.get("id"):
+            self.ids.add(values["id"])
+        if values.get("role"):
+            self.roles.add(values["role"])
+        if values.get("aria-label"):
+            self.labels.add(values["aria-label"])
+        if tag == "script" and values.get("src"):
+            self.scripts.append(values["src"])
+        if tag == "link" and values.get("rel") == "stylesheet" and values.get("href"):
+            self.styles.append(values["href"])
+
+
+def test_web_shell_exposes_engineering_workspace_controls() -> None:
+    parser = ShellParser()
+    parser.feed((WEB / "index.html").read_text(encoding="utf-8"))
+
+    assert parser.lang == "zh-CN"
+    assert {
+        "app-status",
+        "board-search",
+        "category-filters",
+        "layer-controls",
+        "zoom-in",
+        "zoom-out",
+        "reset-view",
+        "board-svg",
+        "hotspot-layer",
+        "pin-layer",
+        "board-tooltip",
+        "detail-panel",
+        "detail-content",
+        "candidate-content",
+        "drawer-toggle",
+        "search-results",
+    }.issubset(parser.ids)
+    assert "电路板视图" in parser.labels
+    assert "搜索结果" in parser.labels
+    assert "app.css" in parser.styles
+    assert "app.js" in parser.scripts
+
+
+def test_css_contains_content_driven_desktop_and_bottom_drawer_layouts() -> None:
+    css = (WEB / "app.css").read_text(encoding="utf-8")
+
+    assert "grid-template-columns: minmax(0, 1fr) var(--detail-width)" in css
+    assert "@media (max-width: 860px)" in css
+    assert "position: fixed" in css
+    assert "inset-block-end: 0" in css
+    assert "min-inline-size: 44px" in css
+    assert "letter-spacing: 0" in css
+    assert "prefers-reduced-motion" in css
+
+
+def test_app_module_loads_generated_data_and_pure_board_logic() -> None:
+    app = (WEB / "app.js").read_text(encoding="utf-8")
+
+    assert 'from "./board-logic.mjs"' in app
+    assert 'fetch("/generated/board-data.json"' in app
+    assert 'fetch("/api/status"' in app
+    assert "generateAdcSnippet" in app
+    assert "sameNetPins" in app
+    assert "photo_overlay" in app
+    assert "naturalWidth" in app

Разница между файлами не показана из-за своего большого размера
+ 1570 - 0
tests/unit/test_agent_handoff_package.py


+ 112 - 0
tests/unit/test_cpld_c_drive_audit.py

@@ -0,0 +1,112 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import sys
+import tempfile
+import unittest
+import zipfile
+from pathlib import Path
+
+import jsonschema
+
+ROOT = Path(__file__).resolve().parents[2]
+TOOLS = ROOT / "tools"
+SCHEMA_PATH = ROOT / "schemas" / "cpld_c_drive_audit.schema.json"
+CONFIG_SCHEMA_PATH = ROOT / "schemas" / "cpld_c_drive_audit_config.schema.json"
+
+sys.path.insert(0, str(TOOLS))
+import cpld_c_drive_audit as audit  # noqa: E402
+
+
+class CpldCDriveAuditTests(unittest.TestCase):
+    def test_scan_records_hash_git_fields_and_classification(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            payload = b"cpld evidence\n"
+            candidate = root / "p4-normal-reference.txt"
+            candidate.write_bytes(payload)
+
+            result = audit.scan_paths(
+                [root],
+                config=audit.AuditConfig(
+                    candidate_patterns=("p4", "cpld"),
+                    excluded_patterns=(),
+                ),
+            )
+
+            self.assertEqual(result["schema"], "cpld-c-drive-audit-v1")
+            self.assertEqual(len(result["records"]), 1)
+            record = result["records"][0]
+            self.assertEqual(record["absolute_path"], str(candidate.resolve()))
+            self.assertEqual(record["resolved_path"], str(candidate.resolve()))
+            self.assertEqual(record["size"], len(payload))
+            self.assertEqual(record["sha256"], hashlib.sha256(payload).hexdigest())
+            self.assertIn("git_common_dir", record)
+            self.assertIn("worktree_dirty", record)
+            self.assertIn("reparse_point", record)
+            self.assertEqual(record["classification"], "cpld_related_file")
+            self.assertEqual(record["recommended_action"], "review")
+
+    def test_compare_archive_requires_all_members_to_match_and_allows_extra_directory_files(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            archive = root / "handoff.zip"
+            unpacked = root / "handoff"
+            (unpacked / "package").mkdir(parents=True)
+            (unpacked / "package" / "README.md").write_bytes(b"same")
+            (unpacked / "extra.txt").write_bytes(b"extra")
+            with zipfile.ZipFile(archive, "w") as handle:
+                handle.writestr("package/README.md", b"same")
+
+            result = audit.compare_archive(archive, unpacked)
+
+            self.assertEqual(result["comparison"]["status"], "full_coverage")
+            self.assertEqual(result["comparison"]["recommended_action"], "delete_archive_after_verification")
+            self.assertEqual(result["comparison"]["members"][0]["comparison_result"], "covered_match")
+
+    def test_compare_archive_rejects_unsafe_member(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            archive = root / "unsafe.zip"
+            unpacked = root / "unpacked"
+            unpacked.mkdir()
+            with zipfile.ZipFile(archive, "w") as handle:
+                handle.writestr("../outside.txt", b"unsafe")
+
+            result = audit.compare_archive(archive, unpacked)
+
+            self.assertEqual(result["comparison"]["status"], "unsafe")
+            self.assertEqual(result["comparison"]["recommended_action"], "retain")
+            self.assertEqual(result["comparison"]["members"][0]["comparison_result"], "unsafe_member")
+
+    def test_protected_archive_never_gets_delete_recommendation(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            archive = root / "release-source.zip"
+            unpacked = root / "release-source"
+            unpacked.mkdir()
+            (unpacked / "source.v").write_bytes(b"source")
+            with zipfile.ZipFile(archive, "w") as handle:
+                handle.writestr("source.v", b"source")
+
+            result = audit.compare_archive(archive, unpacked)
+
+            self.assertEqual(result["comparison"]["status"], "full_coverage")
+            self.assertEqual(result["comparison"]["recommended_action"], "retain_protected_archive")
+
+    def test_default_schema_accepts_scan_output_and_parser_has_no_delete_command(self) -> None:
+        schema = json.loads(SCHEMA_PATH.read_text(encoding="utf-8"))
+        output = audit.scan_paths([], config=audit.AuditConfig())
+        jsonschema.validate(output, schema)
+
+        config_payload = json.loads((ROOT / "config" / "cpld_c_drive_audit.json").read_text(encoding="utf-8"))
+        config_schema = json.loads(CONFIG_SCHEMA_PATH.read_text(encoding="utf-8"))
+        jsonschema.validate(config_payload, config_schema)
+
+        parser = audit.build_parser()
+        self.assertNotIn("delete", parser._subparsers._group_actions[0].choices)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 787 - 0
tests/unit/test_package_for_agent_analysis.py

@@ -0,0 +1,787 @@
+#!/usr/bin/env python3
+"""Tests for the root-level complete agent analysis packager."""
+
+from __future__ import annotations
+
+import importlib.util
+import hashlib
+import json
+import random
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+import zipfile
+from pathlib import Path
+from types import ModuleType
+from unittest import mock
+
+import jsonschema
+
+
+ROOT = Path(__file__).resolve().parents[2]
+MODULE_PATH = ROOT / "package_for_agent_analysis.py"
+
+
+def write_file(root: Path, relative: str, data: bytes = b"fixture\n") -> Path:
+    path = root / Path(relative)
+    path.parent.mkdir(parents=True, exist_ok=True)
+    path.write_bytes(data)
+    return path
+
+
+def load_analyzer(testcase: unittest.TestCase) -> ModuleType:
+    testcase.assertTrue(MODULE_PATH.is_file(), "root analysis packager is missing")
+    spec = importlib.util.spec_from_file_location("package_for_agent_analysis", MODULE_PATH)
+    testcase.assertIsNotNone(spec)
+    testcase.assertIsNotNone(spec.loader)
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+class PackageForAgentAnalysisTests(unittest.TestCase):
+    maxDiff = None
+
+    def test_config_expands_source_roots_and_rejects_positive_include_rules(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            config_path = temp / "sources.json"
+            config_path.write_text(
+                json.dumps(
+                    {
+                        "schema": "cpld-agent-analysis-sources-v1",
+                        "max_zip_bytes": 380_000_000,
+                        "target_zip_bytes": 350_000_000,
+                        "external_sources": [
+                            {
+                                "id": "board-viewer",
+                                "category": "hardware",
+                                "kind": "directory",
+                                "path_candidates": ["{user_profile}/board-viewer"],
+                                "archive_policy": "inspect",
+                            }
+                        ],
+                        "extra_exclusions": [],
+                    }
+                ),
+                encoding="utf-8",
+            )
+
+            config = analyzer.load_config(
+                config_path,
+                repo_root=temp / "repo",
+                user_profile=temp / "user",
+            )
+
+            self.assertEqual(config.max_zip_bytes, 380_000_000)
+            self.assertEqual(config.target_zip_bytes, 350_000_000)
+            self.assertEqual(
+                config.external_sources[0].path_candidates,
+                (temp / "user" / "board-viewer",),
+            )
+
+            payload = json.loads(config_path.read_text(encoding="utf-8"))
+            payload["external_sources"][0]["include_globs"] = ["*.brd"]
+            config_path.write_text(json.dumps(payload), encoding="utf-8")
+            with self.assertRaisesRegex(analyzer.PackagingError, "include"):
+                analyzer.load_config(
+                    config_path,
+                    repo_root=temp / "repo",
+                    user_profile=temp / "user",
+                )
+
+            del payload["external_sources"][0]["include_globs"]
+            payload["extra_exclusions"] = [
+                {
+                    "path": "generated/cache",
+                    "reason": "known_rebuildable_cache",
+                    "include_globs": ["*.brd"],
+                }
+            ]
+            config_path.write_text(json.dumps(payload), encoding="utf-8")
+            with self.assertRaisesRegex(analyzer.PackagingError, "include"):
+                analyzer.load_config(
+                    config_path,
+                    repo_root=temp / "repo",
+                    user_profile=temp / "user",
+                )
+
+    def test_default_config_and_output_index_match_versioned_schemas(self) -> None:
+        analyzer = load_analyzer(self)
+        config_path = ROOT / "config" / "agent_analysis_handoff_sources.json"
+        config_schema_path = ROOT / "schemas" / "agent_analysis_handoff_sources.schema.json"
+        index_schema_path = ROOT / "schemas" / "agent_analysis_handoff_index.schema.json"
+        config_payload = json.loads(config_path.read_text(encoding="utf-8"))
+        config_schema = json.loads(config_schema_path.read_text(encoding="utf-8"))
+        jsonschema.validate(config_payload, config_schema)
+        self.assertEqual(
+            {item["id"] for item in config_payload["external_sources"]},
+            {"td-docs", "board-viewer", "p4-review-worktree", "codegraph"},
+        )
+        self.assertIn(
+            {"path": ".codegraph", "reason": "declared_external_reparse_alias"},
+            config_payload["extra_exclusions"],
+        )
+
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            source = temp / "source"
+            item = write_file(source, "data/file.bin", b"fixture")
+            collection = analyzer.AnalysisCollection(
+                status="pass",
+                items=(
+                    analyzer.make_package_item(
+                        item,
+                        relative="workspace-current/data/file.bin",
+                        category="core",
+                        source_id="workspace-current",
+                    ),
+                ),
+                excluded=(),
+                warnings=(),
+                sources=({"id": "workspace-current", "status": "pass"},),
+                git=(),
+            )
+            result = analyzer.create_analysis_package(
+                collection=collection,
+                output_root=temp / "output",
+                package_name="schema-fixture",
+                max_zip_bytes=1_000_000,
+                target_zip_bytes=800_000,
+                force=False,
+            )
+            index = json.loads(
+                (Path(result["output_dir"]) / "HANDOFF-INDEX.json").read_text(encoding="utf-8")
+            )
+            index_schema = json.loads(index_schema_path.read_text(encoding="utf-8"))
+            jsonschema.validate(index, index_schema)
+
+    def test_analysis_scan_keeps_unknown_and_generated_files(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            write_file(root, "src/rtl/core.v")
+            write_file(root, "reference/original/board/main.brd", b"board")
+            write_file(root, "td/build/current/design.bit", b"bitstream")
+            write_file(root, ".codegraph/codegraph.db", b"graph")
+            write_file(root, "tmp/formal/result.vvp", b"simulation")
+            write_file(root, "unknown/evidence.bin", b"unknown")
+            write_file(root, ".venv/Scripts/python.exe", b"venv")
+            write_file(root, "pkg/__pycache__/cache.pyc", b"cache")
+            write_file(root, "reference/original/local_archives/Anlogic.lic", b"license")
+            write_file(root, "tmp/sysinternals-handle-test/handle.exe", b"tool")
+
+            candidates, excluded, _ = analyzer.scan_analysis_root(root)
+
+            included = {item.relative for item in candidates}
+            self.assertIn("src/rtl/core.v", included)
+            self.assertIn("reference/original/board/main.brd", included)
+            self.assertIn("td/build/current/design.bit", included)
+            self.assertIn(".codegraph/codegraph.db", included)
+            self.assertIn("tmp/formal/result.vvp", included)
+            self.assertIn("unknown/evidence.bin", included)
+            excluded_by_path = {item["path"]: item["rule"] for item in excluded}
+            self.assertEqual(excluded_by_path[".venv"], "virtual_environment")
+            self.assertEqual(excluded_by_path["pkg/__pycache__"], "python_bytecode_cache")
+            self.assertEqual(
+                excluded_by_path["reference/original/local_archives/Anlogic.lic"],
+                "credential_or_license_file",
+            )
+            self.assertEqual(
+                excluded_by_path["tmp/sysinternals-handle-test"],
+                "external_tool_cache",
+            )
+
+    def test_missing_external_sources_are_warnings(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            existing = temp / "existing"
+            write_file(existing, "board.xml", b"board")
+            source_type = analyzer.ExternalSource
+            sources = (
+                source_type(
+                    id="existing",
+                    category="hardware",
+                    kind="directory",
+                    path_candidates=(existing,),
+                    archive_policy="inspect",
+                ),
+                source_type(
+                    id="missing",
+                    category="td-docs",
+                    kind="directory",
+                    path_candidates=(temp / "missing",),
+                    archive_policy="inspect",
+                ),
+            )
+
+            resolved, warnings = analyzer.resolve_external_sources(sources)
+
+            self.assertEqual([item.id for item in resolved], ["existing"])
+            self.assertEqual(len(warnings), 1)
+            self.assertEqual(warnings[0]["code"], "missing_external_source")
+            self.assertEqual(warnings[0]["source_id"], "missing")
+
+    def test_collect_analysis_inputs_rebases_sources_and_creates_git_bundles(self) -> None:
+        git = shutil.which("git")
+        if not git:
+            self.skipTest("Git is required")
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            repo = temp / "repo"
+            review = temp / "review"
+            for root, tracked_name in ((repo, "main.txt"), (review, "review.txt")):
+                root.mkdir()
+                subprocess.run([git, "init", "-q", str(root)], check=True)
+                subprocess.run([git, "-C", str(root), "config", "user.name", "Test"], check=True)
+                subprocess.run(
+                    [git, "-C", str(root), "config", "user.email", "test@example.invalid"],
+                    check=True,
+                )
+                write_file(root, tracked_name, tracked_name.encode("ascii"))
+                subprocess.run([git, "-C", str(root), "add", tracked_name], check=True)
+                subprocess.run([git, "-C", str(root), "commit", "-q", "-m", "fixture"], check=True)
+            write_file(repo, "td/build/current/design.bit", b"bitstream")
+            write_file(review, "notes/untracked.txt", b"review notes")
+            config = analyzer.HandoffConfig(
+                max_zip_bytes=380_000_000,
+                target_zip_bytes=350_000_000,
+                external_sources=(
+                    analyzer.ExternalSource(
+                        id="review-worktree",
+                        category="core",
+                        kind="git_worktree",
+                        path_candidates=(review,),
+                        archive_policy="inspect",
+                    ),
+                    analyzer.ExternalSource(
+                        id="missing-docs",
+                        category="td-docs",
+                        kind="directory",
+                        path_candidates=(temp / "missing",),
+                        archive_policy="inspect",
+                    ),
+                ),
+                extra_exclusions=(),
+            )
+
+            collection = analyzer.collect_analysis_inputs(
+                repo_root=repo,
+                config=config,
+                temp_root=temp / "run",
+            )
+
+            item_paths = {item.candidate.relative for item in collection.items}
+            self.assertIn("workspace-current/td/build/current/design.bit", item_paths)
+            self.assertIn("external/review-worktree/notes/untracked.txt", item_paths)
+            self.assertIn("git-history/workspace-current.bundle", item_paths)
+            self.assertIn("git-history/review-worktree.bundle", item_paths)
+            self.assertEqual(collection.status, "pass_with_warnings")
+            self.assertEqual(collection.warnings[0]["source_id"], "missing-docs")
+            sources_by_id = {item["id"]: item for item in collection.sources}
+            self.assertEqual(Path(sources_by_id["workspace-current"]["path"]), repo.resolve())
+            self.assertEqual(Path(sources_by_id["review-worktree"]["path"]), review.resolve())
+            for item in collection.items:
+                if item.candidate.relative.startswith("git-history/"):
+                    result = subprocess.run(
+                        [git, "bundle", "verify", str(item.candidate.absolute)],
+                        capture_output=True,
+                        text=True,
+                        check=False,
+                    )
+                    self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+
+    def test_existing_invalid_external_git_worktree_fails_instead_of_warning(self) -> None:
+        git = shutil.which("git")
+        if not git:
+            self.skipTest("Git is required")
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            repo = temp / "repo"
+            repo.mkdir()
+            subprocess.run([git, "init", "-q", str(repo)], check=True)
+            subprocess.run([git, "-C", str(repo), "config", "user.name", "Test"], check=True)
+            subprocess.run(
+                [git, "-C", str(repo), "config", "user.email", "test@example.invalid"],
+                check=True,
+            )
+            write_file(repo, "tracked.txt", b"tracked")
+            subprocess.run([git, "-C", str(repo), "add", "tracked.txt"], check=True)
+            subprocess.run([git, "-C", str(repo), "commit", "-q", "-m", "fixture"], check=True)
+            invalid = temp / "invalid-worktree"
+            write_file(invalid, "notes.txt", b"not a Git repository")
+            config = analyzer.HandoffConfig(
+                max_zip_bytes=380_000_000,
+                target_zip_bytes=350_000_000,
+                external_sources=(
+                    analyzer.ExternalSource(
+                        id="invalid-worktree",
+                        category="core",
+                        kind="git_worktree",
+                        path_candidates=(invalid,),
+                        archive_policy="inspect",
+                    ),
+                ),
+                extra_exclusions=(),
+            )
+
+            with self.assertRaisesRegex(analyzer.PackagingError, "Git command failed"):
+                analyzer.collect_analysis_inputs(
+                    repo_root=repo,
+                    config=config,
+                    temp_root=temp / "run",
+                )
+
+    def test_unsupported_archive_keeps_safe_raw_and_sanitizes_license_archive(self) -> None:
+        analyzer = load_analyzer(self)
+        seven_zip = analyzer.find_7z()
+        if seven_zip is None:
+            self.skipTest("7-Zip is required")
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+
+            def make_archive(name: str, entries: dict[str, bytes]) -> Path:
+                source = temp / f"{name}-source"
+                for relative, data in entries.items():
+                    write_file(source, relative, data)
+                archive = temp / f"{name}.7z"
+                result = subprocess.run(
+                    [str(seven_zip), "a", "-t7z", str(archive), ".\\*"],
+                    cwd=source,
+                    capture_output=True,
+                    text=True,
+                    check=False,
+                )
+                self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
+                return archive
+
+            safe_archive = make_archive("safe", {"docs/readme.txt": b"safe\n"})
+            sensitive_archive = make_archive(
+                "sensitive",
+                {
+                    "docs/readme.txt": b"safe\n",
+                    "private/Anlogic.lic": b"license\n",
+                },
+            )
+            items = (
+                analyzer.make_package_item(
+                    safe_archive,
+                    relative="external/hardware/safe.7z",
+                    category="hardware",
+                    source_id="hardware",
+                ),
+                analyzer.make_package_item(
+                    sensitive_archive,
+                    relative="external/hardware/sensitive.7z",
+                    category="hardware",
+                    source_id="hardware",
+                ),
+            )
+
+            prepared = analyzer.prepare_unsupported_archives(
+                items,
+                temp_root=temp / "expanded",
+                seven_zip=seven_zip,
+                extra_exclusions=(),
+            )
+
+            paths = {item.candidate.relative for item in prepared.items}
+            self.assertIn("external/hardware/safe.7z", paths)
+            self.assertIn("external/hardware/safe.7z.expanded/docs/readme.txt", paths)
+            self.assertNotIn("external/hardware/sensitive.7z", paths)
+            self.assertIn("external/hardware/sensitive.7z.expanded/docs/readme.txt", paths)
+            self.assertNotIn("external/hardware/sensitive.7z.expanded/private/Anlogic.lic", paths)
+            self.assertTrue(
+                any(
+                    item["path"] == "external/hardware/sensitive.7z"
+                    and item["rule"] == "unsupported_archive_contains_sensitive_content"
+                    for item in prepared.excluded
+                )
+            )
+            raw_safe = next(
+                item for item in prepared.items if item.candidate.relative == "external/hardware/safe.7z"
+            )
+            self.assertFalse(raw_safe.scan_archive)
+
+    def test_supported_archive_rejects_license_member_by_path(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            archive_path = temp / "vendor.zip"
+            with zipfile.ZipFile(archive_path, "w") as archive:
+                archive.writestr("docs/readme.txt", b"safe\n")
+                archive.writestr("private/Anlogic.lic", b"opaque vendor license\n")
+            item = analyzer.make_package_item(
+                archive_path,
+                relative="external/vendor/vendor.zip",
+                category="hardware",
+                source_id="vendor",
+            )
+
+            with self.assertRaisesRegex(analyzer.PackagingError, "license|credential"):
+                analyzer._audit_package_items((item,))
+
+    def test_cli_explain_reports_inclusion_and_fixed_exclusion(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            external = temp / "board-viewer"
+            board = write_file(external, "board.cad", b"board")
+            cached = write_file(external, ".venv/cache.bin", b"cache")
+            config_path = temp / "sources.json"
+            config_path.write_text(
+                json.dumps(
+                    {
+                        "schema": "cpld-agent-analysis-sources-v1",
+                        "max_zip_bytes": 380_000_000,
+                        "target_zip_bytes": 350_000_000,
+                        "external_sources": [
+                            {
+                                "id": "board-viewer",
+                                "category": "hardware",
+                                "kind": "directory",
+                                "path_candidates": [str(external)],
+                                "archive_policy": "inspect",
+                            }
+                        ],
+                        "extra_exclusions": [],
+                    }
+                ),
+                encoding="utf-8",
+            )
+
+            help_result = subprocess.run(
+                [sys.executable, str(MODULE_PATH), "--help"],
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(help_result.returncode, 0, help_result.stderr)
+            for option in (
+                "--audit-only",
+                "--explain",
+                "--config",
+                "--output-dir",
+                "--package-name",
+                "--force-overwrite",
+            ):
+                self.assertIn(option, help_result.stdout)
+
+            included_result = subprocess.run(
+                [
+                    sys.executable,
+                    str(MODULE_PATH),
+                    "--config",
+                    str(config_path),
+                    "--explain",
+                    str(board),
+                ],
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(included_result.returncode, 0, included_result.stderr)
+            included = json.loads(included_result.stdout)
+            self.assertEqual(included["decision"], "include")
+            self.assertEqual(included["source_id"], "board-viewer")
+
+            excluded_result = subprocess.run(
+                [
+                    sys.executable,
+                    str(MODULE_PATH),
+                    "--config",
+                    str(config_path),
+                    "--explain",
+                    str(cached),
+                ],
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(excluded_result.returncode, 0, excluded_result.stderr)
+            excluded = json.loads(excluded_result.stdout)
+            self.assertEqual(excluded["decision"], "exclude")
+            self.assertEqual(excluded["reason"], "virtual_environment")
+
+    def test_create_analysis_package_writes_single_verified_zip_and_index(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            source = temp / "source"
+            first = write_file(source, "src/core.v", b"module core; endmodule\n")
+            second = write_file(source, "reference/original/main.brd", b"board\n")
+            collection = analyzer.AnalysisCollection(
+                status="pass_with_warnings",
+                items=(
+                    analyzer.make_package_item(
+                        first,
+                        relative="workspace-current/src/core.v",
+                        category="core",
+                        source_id="workspace-current",
+                    ),
+                    analyzer.make_package_item(
+                        second,
+                        relative="workspace-current/reference/original/main.brd",
+                        category="hardware",
+                        source_id="workspace-current",
+                    ),
+                ),
+                excluded=(),
+                warnings=(
+                    {
+                        "code": "missing_external_source",
+                        "source_id": "td-docs",
+                        "message": "missing",
+                    },
+                ),
+                sources=({"id": "workspace-current", "status": "pass"},),
+                git=(),
+            )
+
+            result = analyzer.create_analysis_package(
+                collection=collection,
+                output_root=temp / "output",
+                package_name="single-fixture",
+                max_zip_bytes=1_000_000,
+                target_zip_bytes=800_000,
+                force=False,
+            )
+
+            package_dir = Path(result["output_dir"])
+            self.assertEqual(result["status"], "pass_with_warnings")
+            self.assertEqual(len(result["volumes"]), 1)
+            volume = package_dir / result["volumes"][0]["file"]
+            self.assertLess(volume.stat().st_size, 1_000_000)
+            self.assertTrue((package_dir / "HANDOFF-INDEX.json").is_file())
+            self.assertTrue((package_dir / "START-HERE.zh-CN.md").is_file())
+            self.assertTrue((package_dir / "SHA256SUMS.txt").is_file())
+            with zipfile.ZipFile(volume) as archive:
+                self.assertIsNone(archive.testzip())
+                self.assertIn("CPLD/workspace-current/src/core.v", archive.namelist())
+                self.assertIn("CPLD/workspace-current/reference/original/main.brd", archive.namelist())
+                self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
+            index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
+            self.assertEqual(index["status"], "pass_with_warnings")
+            self.assertEqual(index["volumes"][0]["sha256"], hashlib.sha256(volume.read_bytes()).hexdigest())
+
+    def test_create_analysis_package_splits_into_independent_zip_volumes(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            source = temp / "source"
+            randomizer = random.Random(7)
+            items = []
+            for index, category in enumerate(("core", "core", "hardware", "evidence"), start=1):
+                path = write_file(source, f"data/file-{index}.bin", randomizer.randbytes(12_000))
+                items.append(
+                    analyzer.make_package_item(
+                        path,
+                        relative=f"workspace-current/data/file-{index}.bin",
+                        category=category,
+                        source_id="workspace-current",
+                    )
+                )
+            collection = analyzer.AnalysisCollection(
+                status="pass",
+                items=tuple(items),
+                excluded=(),
+                warnings=(),
+                sources=({"id": "workspace-current", "status": "pass"},),
+                git=(),
+            )
+
+            result = analyzer.create_analysis_package(
+                collection=collection,
+                output_root=temp / "output",
+                package_name="multi-fixture",
+                max_zip_bytes=30_000,
+                target_zip_bytes=20_000,
+                force=False,
+            )
+
+            package_dir = Path(result["output_dir"])
+            self.assertGreaterEqual(len(result["volumes"]), 2)
+            seen_entries: set[str] = set()
+            for volume_info in result["volumes"]:
+                volume = package_dir / volume_info["file"]
+                self.assertLess(volume.stat().st_size, 30_000)
+                with zipfile.ZipFile(volume) as archive:
+                    self.assertIsNone(archive.testzip())
+                    self.assertIn("CPLD/HANDOFF-METADATA/VOLUME-MANIFEST.json", archive.namelist())
+                    seen_entries.update(
+                        name for name in archive.namelist() if name.startswith("CPLD/workspace-current/data/")
+                    )
+            self.assertEqual(len(seen_entries), 4)
+
+    def test_create_analysis_package_chunks_and_reassembles_single_large_file(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            source = temp / "source"
+            payload = random.Random(19).randbytes(55_000)
+            large = write_file(source, "data/large.db", payload)
+            collection = analyzer.AnalysisCollection(
+                status="pass",
+                items=(
+                    analyzer.make_package_item(
+                        large,
+                        relative="workspace-current/data/large.db",
+                        category="evidence",
+                        source_id="workspace-current",
+                    ),
+                ),
+                excluded=(),
+                warnings=(),
+                sources=({"id": "workspace-current", "status": "pass"},),
+                git=(),
+            )
+
+            result = analyzer.create_analysis_package(
+                collection=collection,
+                output_root=temp / "output",
+                package_name="large-fixture",
+                max_zip_bytes=30_000,
+                target_zip_bytes=20_000,
+                force=False,
+            )
+
+            package_dir = Path(result["output_dir"])
+            for volume_info in result["volumes"]:
+                self.assertLess((package_dir / volume_info["file"]).stat().st_size, 30_000)
+            index = json.loads((package_dir / "HANDOFF-INDEX.json").read_text(encoding="utf-8"))
+            self.assertEqual(len(index["large_files"]), 1)
+            large_info = index["large_files"][0]
+            self.assertEqual(large_info["path"], "workspace-current/data/large.db")
+            self.assertEqual(large_info["sha256"], hashlib.sha256(payload).hexdigest())
+            self.assertGreaterEqual(len(large_info["chunks"]), 2)
+            reassembler = package_dir / "reassemble_large_files.py"
+            self.assertTrue(reassembler.is_file())
+            reconstructed = temp / "reconstructed"
+            completed = subprocess.run(
+                [
+                    sys.executable,
+                    str(reassembler),
+                    "--package-dir",
+                    str(package_dir),
+                    "--output-dir",
+                    str(reconstructed),
+                ],
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
+            rebuilt = reconstructed / "workspace-current" / "data" / "large.db"
+            self.assertEqual(rebuilt.read_bytes(), payload)
+
+    def test_create_analysis_package_restores_previous_directory_when_publication_fails(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            source = temp / "source"
+            item = write_file(source, "data/file.bin", b"replacement")
+            output_root = temp / "output"
+            final_dir = output_root / "atomic-fixture"
+            final_dir.mkdir(parents=True)
+            marker = write_file(final_dir, "old-marker.txt", b"old package")
+            collection = analyzer.AnalysisCollection(
+                status="pass",
+                items=(
+                    analyzer.make_package_item(
+                        item,
+                        relative="workspace-current/data/file.bin",
+                        category="core",
+                        source_id="workspace-current",
+                    ),
+                ),
+                excluded=(),
+                warnings=(),
+                sources=({"id": "workspace-current", "status": "pass"},),
+                git=(),
+            )
+            real_replace = analyzer.os.replace
+
+            def fail_new_directory(source_path: object, target_path: object) -> None:
+                source_name = Path(source_path).name
+                if (
+                    source_name != "atomic-fixture"
+                    and not source_name.endswith(".backup")
+                    and Path(target_path).name == "atomic-fixture"
+                ):
+                    raise OSError("injected publication failure")
+                real_replace(source_path, target_path)
+
+            with mock.patch.object(analyzer.os, "replace", side_effect=fail_new_directory):
+                with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
+                    analyzer.create_analysis_package(
+                        collection=collection,
+                        output_root=output_root,
+                        package_name="atomic-fixture",
+                        max_zip_bytes=1_000_000,
+                        target_zip_bytes=800_000,
+                        force=True,
+                    )
+
+            self.assertEqual(marker.read_bytes(), b"old package")
+            self.assertEqual(
+                [path.name for path in output_root.iterdir()],
+                ["atomic-fixture"],
+            )
+
+    def test_create_analysis_package_keeps_previous_directory_when_backup_move_fails(self) -> None:
+        analyzer = load_analyzer(self)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            source = temp / "source"
+            item = write_file(source, "data/file.bin", b"replacement")
+            output_root = temp / "output"
+            final_dir = output_root / "backup-failure-fixture"
+            final_dir.mkdir(parents=True)
+            marker = write_file(final_dir, "old-marker.txt", b"old package")
+            collection = analyzer.AnalysisCollection(
+                status="pass",
+                items=(
+                    analyzer.make_package_item(
+                        item,
+                        relative="workspace-current/data/file.bin",
+                        category="core",
+                        source_id="workspace-current",
+                    ),
+                ),
+                excluded=(),
+                warnings=(),
+                sources=({"id": "workspace-current", "status": "pass"},),
+                git=(),
+            )
+            real_replace = analyzer.os.replace
+
+            def fail_backup_move(source_path: object, target_path: object) -> None:
+                if Path(source_path).name == "backup-failure-fixture":
+                    raise OSError("injected backup move failure")
+                real_replace(source_path, target_path)
+
+            with mock.patch.object(analyzer.os, "replace", side_effect=fail_backup_move):
+                with self.assertRaisesRegex(analyzer.PackagingError, "publish"):
+                    analyzer.create_analysis_package(
+                        collection=collection,
+                        output_root=output_root,
+                        package_name="backup-failure-fixture",
+                        max_zip_bytes=1_000_000,
+                        target_zip_bytes=800_000,
+                        force=True,
+                    )
+
+            self.assertEqual(marker.read_bytes(), b"old package")
+            self.assertEqual(
+                [path.name for path in output_root.iterdir()],
+                ["backup-failure-fixture"],
+            )
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 325 - 0
tests/unit/test_pin_inventory.py

@@ -0,0 +1,325 @@
+#!/usr/bin/env python3
+"""Tests for the FCB real FAN/PTC pin inventory and conflict guardrails."""
+
+from __future__ import annotations
+
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+
+sys.dont_write_bytecode = True
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "tools"))
+
+from pin_inventory import (  # noqa: E402
+    build_io_budget,
+    check_locked_uart_conflicts,
+    diagnostic_profile_assignments,
+    generate_adc,
+    load_pin_inventory,
+    real_fan_ptc_assignments,
+)
+
+
+PRODUCT_INVENTORY = ROOT / "config" / "pin_inventory.fcb_fpga_mcu0611.json"
+
+
+class PinInventoryTests(unittest.TestCase):
+    def test_fcb_pdf_is_archived_under_reference_original_schematics(self) -> None:
+        self.assertFalse((ROOT / "FCB_FPGA+MCU0611.pdf").exists())
+        self.assertTrue((ROOT / "reference/original/schematics/FCB_FPGA+MCU0611.pdf").is_file())
+
+    def test_real_fan_ptc_inventory_covers_all_schematic_signals(self) -> None:
+        inventory = load_pin_inventory(PRODUCT_INVENTORY)
+        pins = inventory["pins"]
+        signals = {pin["signal"]: pin for pin in pins}
+
+        self.assertEqual(inventory["board_id"], "fcb_fpga_mcu0611")
+        self.assertEqual(inventory["status"], "reviewed_with_locked_debug_uart_conflicts")
+        self.assertEqual(len([name for name in signals if name.startswith("HEAT")]), 24)
+        self.assertEqual(len([name for name in signals if name.startswith("FAN_PWM")]), 4)
+        self.assertEqual(len([name for name in signals if name.startswith("FAN_FG")]), 8)
+        self.assertEqual(len([name for name in signals if name.startswith("FAN_INSTALL")]), 4)
+
+        for signal, pin in signals.items():
+            if signal.startswith(("HEAT", "FAN_PWM", "FAN_FG", "FAN_INSTALL")):
+                with self.subTest(signal=signal):
+                    self.assertTrue(pin["manually_verified"])
+                    self.assertIn(3, pin["source_pages"])
+                    self.assertIn(10, pin["source_pages"])
+                    self.assertRegex(pin["bank_io_net"], r"^BANK[0-9]_")
+                    self.assertRegex(pin["fpga_ball"], r"^[A-Z][0-9]+$")
+                    self.assertIn(pin["direction"], ["input", "output"])
+                    self.assertTrue(pin["screenshot_index"])
+
+    def test_real_fan_ptc_assignments_use_one_based_channel_names(self) -> None:
+        inventory = load_pin_inventory(PRODUCT_INVENTORY)
+        assignments = real_fan_ptc_assignments(inventory)
+
+        self.assertEqual(assignments["ptc_pwm_out[0]"], "F16")
+        self.assertEqual(assignments["ptc_pwm_out[23]"], "T12")
+        self.assertEqual(assignments["fan_pwm_out[0]"], "C4")
+        self.assertEqual(assignments["fan_pwm_out[3]"], "A14")
+        self.assertEqual(assignments["fan_fg_in[0]"], "D2")
+        self.assertEqual(assignments["fan_fg_in[7]"], "B13")
+        self.assertEqual(assignments["fan_install_in[0]"], "N10")
+        self.assertEqual(assignments["fan_install_in[3]"], "R11")
+
+    def test_locked_debug_uart_conflicts_block_real_pin_bitstream(self) -> None:
+        inventory = load_pin_inventory(PRODUCT_INVENTORY)
+        result = check_locked_uart_conflicts(inventory)
+
+        self.assertEqual(result["status"], "blocked_pin_conflict_with_locked_debug_uart")
+        conflicts = {(item["function_net"], item["fpga_ball"], item["locked_signal"]) for item in result["conflicts"]}
+        for expected in [
+            ("HEAT3", "T4", "bmc_uart_tx"),
+            ("HEAT4", "R5", "bmc_uart_rx"),
+            ("HEAT17", "P8", "host_uart_rx"),
+            ("HEAT18", "P7", "host_uart_tx"),
+            ("HEAT21", "P10", "debug_uart_rx"),
+            ("HEAT22", "R10", "debug_uart_tx"),
+        ]:
+            self.assertIn(expected, conflicts)
+
+    def test_io_budget_matches_real_fan_ptc_signal_counts(self) -> None:
+        budget = build_io_budget(load_pin_inventory(PRODUCT_INVENTORY))
+
+        self.assertEqual(budget["required_signals_total"], 46)
+        self.assertEqual(budget["required_groups"]["ptc_pwm[23:0]"]["count"], 24)
+        self.assertEqual(budget["required_groups"]["fan_pwm[3:0]"]["count"], 4)
+        self.assertEqual(budget["required_groups"]["fan_fg[7:0]"]["count"], 8)
+        self.assertEqual(budget["required_groups"]["fan_install[3:0]"]["count"], 4)
+        self.assertEqual(budget["status"], "blocked_pin_conflict_with_locked_debug_uart")
+
+    def test_adc_generation_is_blocked_when_real_fan_ptc_overlaps_locked_uarts(self) -> None:
+        inventory = load_pin_inventory(PRODUCT_INVENTORY)
+        assignments = {
+            "bmc_uart_tx": "T4",
+            "bmc_uart_rx": "R5",
+            "host_uart_tx": "P7",
+            "host_uart_rx": "P8",
+            "debug_uart_rx": "P10",
+            "debug_uart_tx": "R10",
+        }
+        assignments.update(real_fan_ptc_assignments(inventory))
+
+        with tempfile.TemporaryDirectory() as tmp:
+            target = Path(tmp) / "candidate.adc"
+            result = generate_adc(inventory, assignments=assignments, output=target)
+
+        self.assertEqual(result["status"], "fail_pin_conflict")
+        self.assertFalse(target.exists())
+
+    def test_temp_uart_ptc_remap_profile_keeps_locked_serials_and_substitutes_conflicting_ptc(self) -> None:
+        inventory = load_pin_inventory(PRODUCT_INVENTORY)
+        payload = diagnostic_profile_assignments(inventory, "temp-uart-ptc-remap")
+
+        self.assertEqual(payload["status"], "pass")
+        self.assertEqual(payload["profile"], "temp-uart-ptc-remap")
+        self.assertEqual(payload["uart_assignments"]["bmc_uart_tx"]["fpga_ball"], "T4")
+        self.assertEqual(payload["uart_assignments"]["bmc_uart_rx"]["fpga_ball"], "R5")
+        self.assertEqual(payload["uart_assignments"]["host_uart_tx"]["fpga_ball"], "P7")
+        self.assertEqual(payload["uart_assignments"]["host_uart_rx"]["fpga_ball"], "P8")
+        self.assertEqual(payload["uart_assignments"]["debug_uart_rx"]["fpga_ball"], "P10")
+        self.assertEqual(payload["uart_assignments"]["debug_uart_tx"]["fpga_ball"], "R10")
+
+        ptc = payload["assignments"]
+        self.assertEqual(ptc["ptc_pwm_out[2]"], "P5")
+        self.assertEqual(ptc["ptc_pwm_out[3]"], "T8")
+        self.assertEqual(ptc["ptc_pwm_out[16]"], "M14")
+        self.assertEqual(ptc["ptc_pwm_out[17]"], "M15")
+        self.assertEqual(ptc["ptc_pwm_out[20]"], "P15")
+        self.assertEqual(ptc["ptc_pwm_out[21]"], "N14")
+        self.assertEqual(payload["ptc_substitutions"]["PTC03"]["original_ball"], "T4")
+        self.assertEqual(payload["ptc_substitutions"]["PTC22"]["substitute_ball"], "N14")
+        self.assertFalse(payload["uses_reserved_future_uart"])
+        self.assertEqual(payload["real_fan_ptc_hardware_status"], "not_run")
+        self.assertEqual(payload["conflict_check"]["status"], "pass")
+
+    def test_formal_uart_profile_keeps_real_ptc_and_moves_all_serials_off_real_fan_ptc_pins(self) -> None:
+        inventory = load_pin_inventory(PRODUCT_INVENTORY)
+        payload = diagnostic_profile_assignments(inventory, "formal-uart")
+
+        self.assertEqual(payload["status"], "pass")
+        self.assertEqual(payload["profile"], "formal-uart")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[2]"], "T4")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[3]"], "R5")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[16]"], "P8")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[17]"], "P7")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[20]"], "P10")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[21]"], "R10")
+        self.assertEqual(payload["uart_assignments"]["bmc_uart_tx"]["fpga_ball"], "P5")
+        self.assertEqual(payload["uart_assignments"]["bmc_uart_rx"]["fpga_ball"], "T8")
+        self.assertEqual(payload["uart_assignments"]["host_uart_tx"]["fpga_ball"], "M14")
+        self.assertEqual(payload["uart_assignments"]["host_uart_rx"]["fpga_ball"], "M15")
+        self.assertEqual(payload["uart_assignments"]["debug_uart_rx"]["fpga_ball"], "P15")
+        self.assertEqual(payload["uart_assignments"]["debug_uart_tx"]["fpga_ball"], "N14")
+        self.assertEqual(payload["reserved_future_uart"]["UART1_TX"]["fpga_ball"], "L10")
+        self.assertEqual(payload["reserved_future_uart"]["UART2_RX"]["fpga_ball"], "N11")
+        self.assertFalse(payload["uses_reserved_future_uart"])
+        self.assertEqual(payload["ptc_substitutions"], {})
+        self.assertEqual(payload["conflict_check"]["status"], "pass")
+
+    def test_debug_photo_uart_bmc_replay_profile_keeps_photo_visible_serials_and_marks_bmc_as_pc_replay(self) -> None:
+        inventory = load_pin_inventory(PRODUCT_INVENTORY)
+        payload = diagnostic_profile_assignments(inventory, "debug-photo-uart-bmc-replay")
+
+        self.assertEqual(payload["status"], "pass")
+        self.assertEqual(payload["profile"], "debug-photo-uart-bmc-replay")
+        self.assertEqual(payload["bmc_source"], "pc_replay_from_real_bmc_capture")
+        self.assertEqual(payload["live_bmc_link_status"], "not_used")
+        self.assertEqual(payload["uart_assignments"]["bmc_replay_uart_tx"]["fpga_ball"], "T4")
+        self.assertEqual(payload["uart_assignments"]["bmc_replay_uart_rx"]["fpga_ball"], "R5")
+        self.assertEqual(payload["uart_assignments"]["host_uart_tx"]["fpga_ball"], "P7")
+        self.assertEqual(payload["uart_assignments"]["host_uart_rx"]["fpga_ball"], "P8")
+        self.assertEqual(payload["uart_assignments"]["debug_uart_rx"]["fpga_ball"], "P10")
+        self.assertEqual(payload["uart_assignments"]["debug_uart_tx"]["fpga_ball"], "R10")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[2]"], "P5")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[3]"], "T8")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[16]"], "M14")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[17]"], "M15")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[20]"], "P15")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[21]"], "N14")
+        self.assertEqual(payload["ptc_substitutions"]["PTC03"]["reason"], "photo_visible_uart_overlap_remap")
+        self.assertFalse(payload["uses_reserved_future_uart"])
+        self.assertEqual(payload["hardware_access_status"], "photo_visible_header")
+        self.assertEqual(payload["conflict_check"]["status"], "pass")
+
+    def test_formal_uart1_bmc_replay_profile_uses_uart1_uart2_and_keeps_real_ptc(self) -> None:
+        inventory = load_pin_inventory(PRODUCT_INVENTORY)
+        payload = diagnostic_profile_assignments(inventory, "formal-uart1-bmc-replay")
+
+        self.assertEqual(payload["status"], "pass")
+        self.assertEqual(payload["profile"], "formal-uart1-bmc-replay")
+        self.assertEqual(payload["bmc_source"], "pc_replay_from_real_bmc_capture")
+        self.assertEqual(payload["live_bmc_link_status"], "not_used")
+        self.assertEqual(payload["hardware_access_status"], "blocked_waiting_for_uart1_uart2_access")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[2]"], "T4")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[3]"], "R5")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[16]"], "P8")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[17]"], "P7")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[20]"], "P10")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[21]"], "R10")
+        self.assertEqual(payload["uart_assignments"]["bmc_replay_uart_tx"]["fpga_ball"], "L10")
+        self.assertEqual(payload["uart_assignments"]["bmc_replay_uart_rx"]["fpga_ball"], "M9")
+        self.assertEqual(payload["uart_assignments"]["host_uart_tx"]["fpga_ball"], "M10")
+        self.assertEqual(payload["uart_assignments"]["host_uart_rx"]["fpga_ball"], "N11")
+        self.assertEqual(payload["uart_assignments"]["debug_uart_rx"]["fpga_ball"], "P15")
+        self.assertEqual(payload["uart_assignments"]["debug_uart_tx"]["fpga_ball"], "N14")
+        self.assertIn("SPARE_GPIO44/45", payload["authority_boundary"])
+        self.assertTrue(payload["uses_reserved_future_uart"])
+        self.assertEqual(payload["ptc_substitutions"], {})
+        self.assertEqual(payload["conflict_check"]["status"], "pass")
+
+    def test_binary921_profiles_capture_debug_photo_and_formal_uart1_boundaries(self) -> None:
+        inventory = load_pin_inventory(PRODUCT_INVENTORY)
+        debug_payload = diagnostic_profile_assignments(inventory, "debug-photo-bmc-replay-binary921")
+        formal_payload = diagnostic_profile_assignments(inventory, "formal-uart1-bmc-replay-binary921")
+
+        self.assertEqual(debug_payload["status"], "pass")
+        self.assertEqual(debug_payload["profile"], "debug-photo-bmc-replay-binary921")
+        self.assertEqual(debug_payload["uart_assignments"]["bmc_replay_uart_tx"]["fpga_ball"], "T4")
+        self.assertEqual(debug_payload["uart_assignments"]["bmc_replay_uart_rx"]["fpga_ball"], "R5")
+        self.assertEqual(debug_payload["uart_assignments"]["host_uart_tx"]["fpga_ball"], "P7")
+        self.assertEqual(debug_payload["uart_assignments"]["host_uart_rx"]["fpga_ball"], "P8")
+        self.assertEqual(debug_payload["uart_assignments"]["debug_uart_rx"]["fpga_ball"], "P10")
+        self.assertEqual(debug_payload["uart_assignments"]["debug_uart_tx"]["fpga_ball"], "R10")
+        self.assertEqual(debug_payload["assignments"]["ptc_pwm_out[2]"], "P5")
+        self.assertEqual(debug_payload["assignments"]["ptc_pwm_out[3]"], "T8")
+        self.assertEqual(debug_payload["assignments"]["ptc_pwm_out[16]"], "M14")
+        self.assertEqual(debug_payload["assignments"]["ptc_pwm_out[17]"], "M15")
+        self.assertEqual(debug_payload["assignments"]["ptc_pwm_out[20]"], "P15")
+        self.assertEqual(debug_payload["assignments"]["ptc_pwm_out[21]"], "N14")
+        self.assertIn("binary921", debug_payload["authority_boundary"])
+
+        self.assertEqual(formal_payload["status"], "pass")
+        self.assertEqual(formal_payload["profile"], "formal-uart1-bmc-replay-binary921")
+        self.assertEqual(formal_payload["assignments"]["ptc_pwm_out[2]"], "T4")
+        self.assertEqual(formal_payload["assignments"]["ptc_pwm_out[3]"], "R5")
+        self.assertEqual(formal_payload["assignments"]["ptc_pwm_out[16]"], "P8")
+        self.assertEqual(formal_payload["assignments"]["ptc_pwm_out[17]"], "P7")
+        self.assertEqual(formal_payload["assignments"]["ptc_pwm_out[20]"], "P10")
+        self.assertEqual(formal_payload["assignments"]["ptc_pwm_out[21]"], "R10")
+        self.assertEqual(formal_payload["uart_assignments"]["bmc_replay_uart_tx"]["fpga_ball"], "L10")
+        self.assertEqual(formal_payload["uart_assignments"]["bmc_replay_uart_rx"]["fpga_ball"], "M9")
+        self.assertEqual(formal_payload["uart_assignments"]["host_uart_tx"]["fpga_ball"], "M10")
+        self.assertEqual(formal_payload["uart_assignments"]["host_uart_rx"]["fpga_ball"], "N11")
+        self.assertEqual(formal_payload["uart_assignments"]["debug_uart_rx"]["fpga_ball"], "M14")
+        self.assertEqual(formal_payload["uart_assignments"]["debug_uart_tx"]["fpga_ball"], "M15")
+        self.assertTrue(formal_payload["uses_reserved_future_uart"])
+        self.assertEqual(formal_payload["ptc_substitutions"], {})
+        self.assertIn("binary921", formal_payload["authority_boundary"])
+
+    def test_production_two_uart_binary921_profile_uses_uart1_uart2_combined_port_and_real_load_pins(self) -> None:
+        inventory = load_pin_inventory(PRODUCT_INVENTORY)
+        payload = diagnostic_profile_assignments(inventory, "production-two-uart-bmc-replay-binary921")
+        uart_pins = {row["signal"]: row for row in inventory["pins"] if row["signal"].startswith("UART")}
+
+        self.assertEqual(uart_pins["UART1_TX"]["direction"], "output")
+        self.assertEqual(uart_pins["UART1_TX"]["board_connector"], "CON77")
+        self.assertEqual(uart_pins["UART1_TX"]["connector_pin"], 1)
+        self.assertEqual(uart_pins["UART1_RX"]["connector_pin"], 2)
+        self.assertEqual(uart_pins["UART2_TX"]["board_connector"], "CON78")
+        self.assertEqual(uart_pins["UART2_TX"]["connector_pin"], 1)
+        self.assertEqual(uart_pins["UART2_RX"]["connector_pin"], 2)
+        self.assertEqual(uart_pins["UART2_RX"]["external_level"], "RS232")
+        self.assertEqual(uart_pins["UART2_RX"]["transceiver"], "U23 TRSF3232EIPWR")
+
+        self.assertEqual(payload["status"], "pass")
+        self.assertEqual(payload["profile"], "production-two-uart-bmc-replay-binary921")
+        self.assertEqual(payload["bmc_source"], "pc_replay_from_real_bmc_capture")
+        self.assertEqual(payload["live_bmc_link_status"], "not_used")
+        self.assertEqual(payload["transport"], "combined_host_debug_uart")
+        self.assertEqual(payload["hardware_access_status"], "production_uart1_uart2_access_confirmed_by_user")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[2]"], "T4")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[3]"], "R5")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[16]"], "P8")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[17]"], "P7")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[20]"], "P10")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[21]"], "R10")
+        self.assertEqual(payload["uart_assignments"]["bmc_replay_uart_tx"]["fpga_ball"], "L10")
+        self.assertEqual(payload["uart_assignments"]["bmc_replay_uart_rx"]["fpga_ball"], "M9")
+        self.assertEqual(payload["uart_assignments"]["combined_debug_host_uart_tx"]["fpga_ball"], "M10")
+        self.assertEqual(payload["uart_assignments"]["combined_debug_host_uart_rx"]["fpga_ball"], "N11")
+        self.assertNotIn("debug_uart_rx", payload["uart_assignments"])
+        self.assertTrue(payload["uses_reserved_future_uart"])
+        self.assertEqual(payload["ptc_substitutions"], {})
+        self.assertEqual(payload["conflict_check"]["status"], "pass")
+        self.assertIn("J3", payload["authority_boundary"])
+        self.assertIn("combined", payload["authority_boundary"])
+
+        active = diagnostic_profile_assignments(inventory, "prod2u-bmc-replay-binary921")
+        self.assertEqual(active["status"], "pass")
+        self.assertEqual(active["profile"], "prod2u-bmc-replay-binary921")
+        self.assertEqual(active["assignments"], payload["assignments"])
+        self.assertEqual(active["uart_assignments"], payload["uart_assignments"])
+
+    def test_prod2u_profile4_uses_uart2_combined_port_and_leaves_uart1_idle(self) -> None:
+        inventory = load_pin_inventory(PRODUCT_INVENTORY)
+        payload = diagnostic_profile_assignments(inventory, "prod2u-fan-tach-binary921-v2")
+
+        self.assertEqual(payload["status"], "pass")
+        self.assertEqual(payload["profile"], "prod2u-fan-tach-binary921-v2")
+        self.assertEqual(payload["bmc_source"], "out_of_scope")
+        self.assertEqual(payload["live_bmc_link_status"], "out_of_scope")
+        self.assertEqual(payload["transport"], "combined_host_debug_uart")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[2]"], "T4")
+        self.assertEqual(payload["assignments"]["ptc_pwm_out[21]"], "R10")
+        self.assertEqual(payload["assignments"]["fan_pwm_out[2]"], "B1")
+        self.assertEqual(payload["assignments"]["fan_fg_in[4]"], "C1")
+        self.assertEqual(payload["assignments"]["fan_fg_in[5]"], "C2")
+        self.assertEqual(payload["uart_assignments"]["idle_uart1_tx"]["fpga_ball"], "L10")
+        self.assertEqual(payload["uart_assignments"]["ignored_uart1_rx"]["fpga_ball"], "M9")
+        self.assertEqual(payload["uart_assignments"]["combined_debug_host_uart_tx"]["fpga_ball"], "M10")
+        self.assertEqual(payload["uart_assignments"]["combined_debug_host_uart_rx"]["fpga_ball"], "N11")
+        self.assertEqual(payload["ptc_substitutions"], {})
+        self.assertEqual(payload["conflict_check"]["status"], "pass")
+        self.assertIn("UART1", payload["authority_boundary"])
+        self.assertIn("out of scope", payload["authority_boundary"])
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 18 - 0
tools/board-viewer/OPEN_BOARD_VIEWER.cmd

@@ -0,0 +1,18 @@
+@echo off
+setlocal
+cd /d "%~dp0"
+
+where py >nul 2>nul
+if errorlevel 1 goto use_python
+py -3.12 -c "import sys; raise SystemExit(0 if sys.version_info[:2] == (3, 12) else 1)" >nul 2>nul
+if errorlevel 1 goto use_python
+py -3.12 board_viewer.py serve --open-browser
+goto finished
+
+:use_python
+python board_viewer.py serve --open-browser
+
+:finished
+set "BOARD_VIEWER_EXIT=%ERRORLEVEL%"
+if not "%BOARD_VIEWER_EXIT%"=="0" pause
+exit /b %BOARD_VIEWER_EXIT%

Разница между файлами не показана из-за своего большого размера
+ 131 - 0
tools/board-viewer/README.zh-CN.md


+ 8 - 0
tools/board-viewer/board_viewer.py

@@ -0,0 +1,8 @@
+#!/usr/bin/env python3
+"""Run the local FCB board viewer commands."""
+
+from board_viewer.cli import main
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 1 - 0
tools/board-viewer/board_viewer/__init__.py

@@ -0,0 +1 @@
+"""Local, read-only PCB touchpoint viewer support package."""

+ 180 - 0
tools/board-viewer/board_viewer/annotations.py

@@ -0,0 +1,180 @@
+"""Validation helpers for versioned board-viewer annotations."""
+
+from __future__ import annotations
+
+import copy
+from collections.abc import Mapping
+import re
+
+
+TEMPLATE_VARIABLE = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
+
+
+class AnnotationError(ValueError):
+    """Raised when an annotation points outside the parsed board."""
+
+
+def _substitute_template(
+    value: object,
+    variables: Mapping[str, object],
+    *,
+    context: str,
+) -> object:
+    if isinstance(value, str):
+        def replace(match: re.Match[str]) -> str:
+            name = match.group(1)
+            if name not in variables:
+                raise AnnotationError(
+                    f"missing template variable {name} for {context}"
+                )
+            return str(variables[name])
+
+        return TEMPLATE_VARIABLE.sub(replace, value)
+    if isinstance(value, list):
+        return [
+            _substitute_template(item, variables, context=context)
+            for item in value
+        ]
+    if isinstance(value, Mapping):
+        return {
+            str(key): _substitute_template(item, variables, context=context)
+            for key, item in value.items()
+        }
+    return copy.deepcopy(value)
+
+
+def _deep_merge(base: object, override: object) -> object:
+    if isinstance(base, Mapping) and isinstance(override, Mapping):
+        result = {str(key): copy.deepcopy(value) for key, value in base.items()}
+        for key, value in override.items():
+            name = str(key)
+            result[name] = _deep_merge(result[name], value) if name in result else copy.deepcopy(value)
+        return result
+    return copy.deepcopy(override)
+
+
+def expand_annotation_templates(annotations: Mapping[str, object]) -> dict[str, object]:
+    """Expand versioned repeated annotations without mutating the source mapping."""
+
+    result = {str(key): copy.deepcopy(value) for key, value in annotations.items()}
+    templates = annotations.get("annotation_templates", {})
+    instances = annotations.get("template_instances", {})
+    touchpoints = annotations.get("touchpoints", {})
+    if not isinstance(templates, Mapping):
+        raise AnnotationError("annotation_templates must be an object")
+    if not isinstance(instances, Mapping):
+        raise AnnotationError("template_instances must be an object")
+    if not isinstance(touchpoints, Mapping):
+        raise AnnotationError("touchpoints annotation must be an object")
+
+    expanded_touchpoints = {
+        str(reference): copy.deepcopy(value)
+        for reference, value in touchpoints.items()
+    }
+    for reference_value, instance in instances.items():
+        reference = str(reference_value)
+        if not isinstance(instance, Mapping):
+            raise AnnotationError(f"template instance {reference} must be an object")
+        template_name = str(instance.get("template") or "")
+        template = templates.get(template_name)
+        if not template_name or not isinstance(template, Mapping):
+            raise AnnotationError(
+                f"unknown annotation template {template_name or '<empty>'} for {reference}"
+            )
+        variables = instance.get("variables", {})
+        if not isinstance(variables, Mapping):
+            raise AnnotationError(f"template variables {reference} must be an object")
+        expanded = _substitute_template(
+            template,
+            variables,
+            context=f"{reference} via {template_name}",
+        )
+        explicit = expanded_touchpoints.get(reference, {})
+        expanded_touchpoints[reference] = _deep_merge(expanded, explicit)
+
+    result["touchpoints"] = expanded_touchpoints
+    return result
+
+
+def validate_annotation_references(
+    annotations: Mapping[str, object], touchpoints: Mapping[str, Mapping[str, object]]
+) -> None:
+    annotated_touchpoints = annotations.get("touchpoints", {})
+    if not isinstance(annotated_touchpoints, Mapping):
+        raise AnnotationError("touchpoints annotation must be an object")
+
+    for reference, annotation in annotated_touchpoints.items():
+        if reference not in touchpoints:
+            raise AnnotationError(f"unknown touchpoint {reference}")
+        if not isinstance(annotation, Mapping):
+            raise AnnotationError(f"touchpoint annotation {reference} must be an object")
+        pins = annotation.get("pins", {})
+        if not isinstance(pins, Mapping):
+            raise AnnotationError(f"pins annotation {reference} must be an object")
+        actual_pins = touchpoints[reference].get("pins", [])
+        actual_numbers = {
+            str(pin.get("number"))
+            for pin in actual_pins
+            if isinstance(pin, Mapping) and pin.get("number") is not None
+        }
+        for number in pins:
+            if str(number) not in actual_numbers:
+                raise AnnotationError(f"unknown pin {reference}.{number}")
+
+    connector_profiles = annotations.get("connector_profiles", {})
+    if not isinstance(connector_profiles, Mapping):
+        raise AnnotationError("connector_profiles annotation must be an object")
+
+    owners: dict[str, str] = {}
+    for profile_name, profile in connector_profiles.items():
+        if not isinstance(profile, Mapping):
+            raise AnnotationError(f"connector profile {profile_name} must be an object")
+        references = profile.get("references", [])
+        if not isinstance(references, list):
+            raise AnnotationError(f"connector profile {profile_name} references must be an array")
+        for reference_value in references:
+            reference = str(reference_value)
+            if reference in owners:
+                raise AnnotationError(f"connector {reference} appears in multiple profiles")
+            owners[reference] = str(profile_name)
+
+    for profile_name, profile in connector_profiles.items():
+        if not isinstance(profile, Mapping):
+            continue
+        contact_values = profile.get("contact_pins", [])
+        shield_values = profile.get("shield_pads", [])
+        references = profile.get("references", [])
+        if not isinstance(contact_values, list) or not isinstance(shield_values, list):
+            raise AnnotationError(f"connector profile {profile_name} pin classifications must be arrays")
+        contacts = {str(value) for value in contact_values}
+        shields = {str(value) for value in shield_values}
+        overlap = sorted(contacts.intersection(shields))
+        if overlap:
+            raise AnnotationError(
+                f"connector profile {profile_name} has overlapping contact and shield pads: {', '.join(overlap)}"
+            )
+
+        for reference_value in references if isinstance(references, list) else []:
+            reference = str(reference_value)
+            if reference not in touchpoints:
+                raise AnnotationError(f"unknown connector {reference}")
+            touchpoint = touchpoints[reference]
+            expected_component_value = str(profile.get("component_value", profile_name))
+            if str(touchpoint.get("component_value") or "") != expected_component_value:
+                raise AnnotationError(
+                    f"component value mismatch {reference}: "
+                    f"{touchpoint.get('component_value')} != {expected_component_value}"
+                )
+            actual_pins = touchpoint.get("pins", [])
+            actual_numbers = {
+                str(pin.get("number"))
+                for pin in actual_pins
+                if isinstance(pin, Mapping) and str(pin.get("number") or "")
+            }
+            classified = contacts.union(shields)
+            unknown = sorted(classified.difference(actual_numbers))
+            if unknown:
+                raise AnnotationError(f"unknown classified pads {reference}: {', '.join(unknown)}")
+            unclassified = sorted(actual_numbers.difference(classified))
+            if unclassified:
+                raise AnnotationError(f"unclassified numbered pads {reference}: {', '.join(unclassified)}")

+ 124 - 0
tools/board-viewer/board_viewer/assets.py

@@ -0,0 +1,124 @@
+"""Generated-asset hashing and fail-closed integrity checks."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+from jsonschema import Draft202012Validator
+from jsonschema.exceptions import ValidationError
+
+from .regression import BoardRegressionError, validate_product_regression
+
+
+ROOT = Path(__file__).resolve().parents[3]
+BUILD_INFO_SCHEMA = ROOT / "schemas" / "board_viewer_build_info.schema.json"
+DATA_SCHEMA = ROOT / "schemas" / "board_viewer_data.schema.json"
+
+
+class AssetIntegrityError(RuntimeError):
+    """Raised when generated files cannot be trusted for browsing."""
+
+
+@dataclass(frozen=True)
+class AssetValidationResult:
+    status: str
+    asset_errors: list[str]
+    stale_sources: list[str]
+    recommendations_enabled: bool
+    adc_copy_enabled: bool
+    build_info: dict[str, Any]
+
+
+def sha256_file(path: Path | str, chunk_size: int = 1024 * 1024) -> str:
+    digest = hashlib.sha256()
+    with Path(path).open("rb") as stream:
+        while chunk := stream.read(chunk_size):
+            digest.update(chunk)
+    return digest.hexdigest()
+
+
+def _load_build_info(path: Path) -> dict[str, Any]:
+    if not path.is_file():
+        raise AssetIntegrityError(f"missing generated asset: {path.name}")
+    try:
+        payload = json.loads(path.read_text(encoding="utf-8"))
+        schema = json.loads(BUILD_INFO_SCHEMA.read_text(encoding="utf-8"))
+        Draft202012Validator(schema).validate(payload)
+    except (OSError, json.JSONDecodeError, ValueError, ValidationError) as exc:
+        raise AssetIntegrityError(f"invalid build-info.json: {exc}") from exc
+    return payload
+
+
+def _safe_asset_path(root: Path, name: str) -> Path:
+    relative = Path(name)
+    if relative.is_absolute() or ".." in relative.parts or len(relative.parts) != 1:
+        raise AssetIntegrityError(f"unsafe generated asset path: {name}")
+    return root / relative
+
+
+def validate_generated_assets(
+    generated_dir: Path | str, *, repository_root: Path | str = ROOT
+) -> AssetValidationResult:
+    generated = Path(generated_dir).resolve()
+    repository = Path(repository_root).resolve()
+    build_info = _load_build_info(generated / "build-info.json")
+    asset_errors: list[str] = []
+    for name, metadata in build_info["assets"].items():
+        path = _safe_asset_path(generated, name)
+        if not path.is_file():
+            asset_errors.append(f"missing:{name}")
+            continue
+        expected_size = int(metadata["bytes"])
+        if path.stat().st_size != expected_size:
+            asset_errors.append(f"size_mismatch:{name}")
+            continue
+        if sha256_file(path) != metadata["sha256"]:
+            asset_errors.append(f"sha256_mismatch:{name}")
+    if asset_errors:
+        raise AssetIntegrityError("generated asset integrity failure: " + ", ".join(asset_errors))
+
+    stale_sources: list[str] = []
+    for name, metadata in build_info["sources"].items():
+        path = Path(metadata["path"])
+        if not path.is_absolute():
+            path = repository / path
+        if not path.is_file():
+            stale_sources.append(f"missing:{name}")
+            continue
+        if sha256_file(path) != metadata["sha256"]:
+            stale_sources.append(f"sha256_mismatch:{name}")
+
+    stale = bool(stale_sources)
+    return AssetValidationResult(
+        status="stale_sources" if stale else "pass",
+        asset_errors=[],
+        stale_sources=stale_sources,
+        recommendations_enabled=not stale,
+        adc_copy_enabled=not stale,
+        build_info=build_info,
+    )
+
+
+def validate_generated_bundle(
+    generated_dir: Path | str, *, repository_root: Path | str = ROOT
+) -> AssetValidationResult:
+    generated = Path(generated_dir).resolve()
+    result = validate_generated_assets(generated, repository_root=repository_root)
+    try:
+        board_data = json.loads((generated / "board-data.json").read_text(encoding="utf-8"))
+        data_schema = json.loads(DATA_SCHEMA.read_text(encoding="utf-8"))
+        Draft202012Validator(data_schema).validate(board_data)
+        validate_product_regression(board_data)
+    except (OSError, json.JSONDecodeError, ValidationError, BoardRegressionError) as exc:
+        raise AssetIntegrityError(f"invalid board-data.json contract: {exc}") from exc
+    try:
+        import_report = json.loads((generated / "import-report.json").read_text(encoding="utf-8"))
+    except (OSError, json.JSONDecodeError) as exc:
+        raise AssetIntegrityError(f"invalid import-report.json: {exc}") from exc
+    if import_report.get("errors"):
+        raise AssetIntegrityError(f"import-report.json contains errors: {import_report['errors']}")
+    return result

+ 162 - 0
tools/board-viewer/board_viewer/cli.py

@@ -0,0 +1,162 @@
+"""Command-line entrypoints for generate, validate, and serve."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import shutil
+import sys
+import tempfile
+import webbrowser
+from pathlib import Path
+
+from .assets import AssetIntegrityError, AssetValidationResult, validate_generated_bundle
+from .generator import GenerationConfig, GenerationError, generate_assets
+from .server import create_server
+
+
+ROOT = Path(__file__).resolve().parents[3]
+VIEWER_ROOT = ROOT / "tools" / "board-viewer"
+DEFAULT_BRD = ROOT / "reference/original/board/FCB_FPGA_MCU_V1.1_20260625/FCB_FPGA+MCU_V1.1_20260625.brd"
+DEFAULT_INVENTORY = ROOT / "config/pin_inventory.fcb_fpga_mcu0611.json"
+DEFAULT_ANNOTATIONS = ROOT / "config/board_viewer_annotations.fcb_fpga_mcu0611.json"
+DEFAULT_GENERATED = VIEWER_ROOT / "generated"
+DEFAULT_WEB = VIEWER_ROOT / "web"
+
+
+def find_kicad_cli() -> Path:
+    explicit = os.environ.get("BOARD_VIEWER_KICAD_CLI")
+    if explicit:
+        return Path(explicit)
+    discovered = shutil.which("kicad-cli")
+    if discovered:
+        return Path(discovered)
+    local_app_data = Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData/Local"))
+    return local_app_data / "Programs/KiCad/10.0/bin/kicad-cli.exe"
+
+
+def default_generation_config() -> GenerationConfig:
+    return GenerationConfig(
+        brd_path=DEFAULT_BRD,
+        inventory_path=DEFAULT_INVENTORY,
+        annotations_path=DEFAULT_ANNOTATIONS,
+        output_dir=DEFAULT_GENERATED,
+        kicad_cli=find_kicad_cli(),
+        board_name="FCB FPGA+MCU V1.1 20260625",
+        required_kicad_version="10.0.4",
+        expected_counts={"footprints": 1052, "touchpoints": 110, "pads": 472},
+        expected_front_only=True,
+        product_regression=True,
+        temp_parent=Path(tempfile.gettempdir()),
+    )
+
+
+def _validation_payload(result: AssetValidationResult) -> dict[str, object]:
+    return {
+        "status": result.status,
+        "asset_errors": result.asset_errors,
+        "stale_sources": result.stale_sources,
+        "recommendations_enabled": result.recommendations_enabled,
+        "adc_copy_enabled": result.adc_copy_enabled,
+        "generated_at": result.build_info.get("generated_at"),
+        "counts": result.build_info.get("counts"),
+    }
+
+
+def build_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(description="Local read-only FCB board touchpoint viewer")
+    subparsers = parser.add_subparsers(dest="command", required=True)
+
+    generate = subparsers.add_parser("generate", help="Regenerate SVG and JSON assets through KiCad")
+    generate.add_argument("--brd", type=Path)
+    generate.add_argument("--inventory", type=Path)
+    generate.add_argument("--annotations", type=Path)
+    generate.add_argument("--output", type=Path)
+    generate.add_argument("--kicad-cli", type=Path)
+    generate.add_argument("--temp-parent", type=Path)
+    generate.add_argument("--json", action="store_true")
+
+    validate = subparsers.add_parser("validate", help="Validate generated assets and source freshness")
+    validate.add_argument("--generated", type=Path, default=DEFAULT_GENERATED)
+    validate.add_argument("--json", action="store_true")
+
+    serve = subparsers.add_parser("serve", help="Serve the viewer on loopback only")
+    serve.add_argument("--generated", type=Path, default=DEFAULT_GENERATED)
+    serve.add_argument("--web-root", type=Path, default=DEFAULT_WEB)
+    serve.add_argument("--port", type=int, default=8765)
+    serve.add_argument("--open-browser", action="store_true")
+    return parser
+
+
+def _command_generate(args: argparse.Namespace) -> int:
+    config = default_generation_config()
+    for argument, attribute in (
+        (args.brd, "brd_path"),
+        (args.inventory, "inventory_path"),
+        (args.annotations, "annotations_path"),
+        (args.output, "output_dir"),
+        (args.kicad_cli, "kicad_cli"),
+        (args.temp_parent, "temp_parent"),
+    ):
+        if argument is not None:
+            setattr(config, attribute, argument)
+    result = generate_assets(config)
+    if args.json:
+        print(json.dumps(result, indent=2, ensure_ascii=False))
+    else:
+        print(f"board-viewer generate: pass ({config.output_dir})")
+    return 0
+
+
+def _command_validate(args: argparse.Namespace) -> int:
+    result = validate_generated_bundle(args.generated, repository_root=ROOT)
+    payload = _validation_payload(result)
+    if args.json:
+        print(json.dumps(payload, indent=2, ensure_ascii=False))
+    else:
+        print(f"board-viewer validate: {result.status}")
+        for item in result.stale_sources:
+            print(f"  stale: {item}")
+    return 0 if result.status == "pass" else 2
+
+
+def _available_server(web_root: Path, generated: Path, requested_port: int):
+    if requested_port == 0:
+        return create_server(web_root, generated, port=0, repository_root=ROOT)
+    last_error: OSError | None = None
+    for port in range(requested_port, requested_port + 25):
+        try:
+            return create_server(web_root, generated, port=port, repository_root=ROOT)
+        except OSError as exc:
+            last_error = exc
+    raise OSError(f"no free loopback port in {requested_port}-{requested_port + 24}") from last_error
+
+
+def _command_serve(args: argparse.Namespace) -> int:
+    server = _available_server(args.web_root, args.generated, args.port)
+    host, port = server.server_address[:2]
+    url = f"http://{host}:{port}/"
+    print(f"board-viewer serve: {url}", flush=True)
+    if args.open_browser:
+        webbrowser.open(url, new=2)
+    try:
+        server.serve_forever(poll_interval=0.25)
+    except KeyboardInterrupt:
+        pass
+    finally:
+        server.server_close()
+    return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = build_parser().parse_args(argv)
+    try:
+        if args.command == "generate":
+            return _command_generate(args)
+        if args.command == "validate":
+            return _command_validate(args)
+        return _command_serve(args)
+    except (AssetIntegrityError, GenerationError, OSError, ValueError) as exc:
+        print(f"board-viewer {args.command}: fail: {exc}", file=sys.stderr)
+        return 1

+ 797 - 0
tools/board-viewer/board_viewer/data.py

@@ -0,0 +1,797 @@
+"""Merge parsed board facts, pin inventory, and curated annotations."""
+
+from __future__ import annotations
+
+from collections import Counter
+from collections.abc import Mapping
+import re
+from typing import Any
+
+from .annotations import expand_annotation_templates, validate_annotation_references
+from .eligibility import evaluate_recommendation
+from .pcb import Footprint, Pad, ParsedBoard, select_touchpoints
+
+
+EVIDENCE_TIERS = {"board_database", "cross_verified", "name_inferred", "unknown"}
+CONNECTOR_ROW_TOLERANCE_MM = 0.05
+INTERNAL_NET = re.compile(r"^(?:N\d+|NET_\d+)$", re.IGNORECASE)
+POWER_NET = re.compile(r"^(?:VCC|VDD|VBAT|PWR|\+)", re.IGNORECASE)
+
+
+def _category(reference: str) -> str:
+    for prefix in ("CON", "PL", "TP", "J"):
+        if reference.startswith(prefix):
+            return prefix
+    return "OTHER"
+
+
+def _view_point(x: float, y: float, bounds: Mapping[str, float]) -> dict[str, float]:
+    return {"x": x - bounds["x"], "y": y - bounds["y"]}
+
+
+def _view_bounds(item: Mapping[str, float], board_bounds: Mapping[str, float]) -> dict[str, float]:
+    return {
+        "x": item["x"] - board_bounds["x"],
+        "y": item["y"] - board_bounds["y"],
+        "width": item["width"],
+        "height": item["height"],
+    }
+
+
+def _pin_dict(
+    reference: str,
+    category: str,
+    pad: Pad,
+    board_bounds: Mapping[str, float],
+    source_index: int,
+) -> dict[str, Any]:
+    role = "mechanical" if pad.mechanical else ("unknown" if category == "CON" else "contact")
+    return {
+        "id": f"{reference}.pad-{source_index + 1}",
+        "number": pad.number,
+        "pad_role": role,
+        "row": None,
+        "column": None,
+        "board_order": None,
+        "mechanical": pad.mechanical,
+        "electrical": pad.electrical,
+        "net": pad.net,
+        "position": {"x": pad.x, "y": pad.y},
+        "view_position": _view_point(pad.x, pad.y, board_bounds),
+        "size": {
+            "width": pad.width,
+            "height": pad.height,
+            "drill_width": pad.drill_width,
+            "drill_height": pad.drill_height,
+        },
+        "rotation": pad.rotation,
+        "shape": pad.shape,
+        "layers": list(pad.layers),
+        "direction": "unknown",
+        "external_level": "unknown",
+        "function_category": _classify_function(pad.net, []),
+        "reserved": False,
+        "fixed_load_conflict": False,
+        "board_pull": None,
+        "adc_pulltype": None,
+        "active_level": "unknown",
+        "polarity": "unknown",
+        "external_components": [],
+        "summary": _raw_pin_summary(pad),
+        "path": [],
+        "evidence_tier": "board_database",
+        "evidence_sources": ["board:kicad_import"],
+        "fpga": None,
+        "mcu": None,
+        "programming": {},
+        "recommendation": {"eligible": False, "reasons": ["pin_evidence_not_verified"]},
+    }
+
+
+def _raw_pin_summary(pad: Pad) -> str:
+    if pad.mechanical:
+        return "机械焊盘"
+    if pad.net:
+        return f"板内网络 {pad.net}"
+    return "未命名电气焊盘"
+
+
+def _classify_function(net: str | None, capabilities: list[str]) -> str:
+    ordered = (
+        "uart_tx",
+        "uart_rx",
+        "pwm",
+        "fan_tach",
+        "tach",
+        "presence",
+        "gpio_output",
+        "gpio_input",
+        "gpio",
+    )
+    normalized = {str(item).lower() for item in capabilities}
+    for category in ordered:
+        if category in normalized:
+            return category
+    upper_net = str(net or "").upper()
+    if upper_net in {"GND", "AGND", "DGND", "PGND"}:
+        return "ground"
+    if upper_net.startswith(("+", "VCC", "VDD", "VBAT", "PWR")):
+        return "power"
+    if "PWM" in upper_net:
+        return "pwm"
+    if "TX" in upper_net and "UART" in upper_net:
+        return "uart_tx"
+    if "RX" in upper_net and "UART" in upper_net:
+        return "uart_rx"
+    if "FG" in upper_net or "TACH" in upper_net:
+        return "tach"
+    if "INSTALL" in upper_net or "PRESENT" in upper_net:
+        return "presence"
+    return "unknown"
+
+
+def _touchpoint_dict(footprint: Footprint, board_bounds: Mapping[str, float]) -> dict[str, Any]:
+    category = _category(footprint.reference)
+    category_name = {"CON": "连接器", "J": "接口", "PL": "插座", "TP": "测试点"}.get(category, category)
+    return {
+        "reference": footprint.reference,
+        "category": category,
+        "component_value": footprint.component_value,
+        "position": {"x": footprint.x, "y": footprint.y},
+        "view_position": _view_point(footprint.x, footprint.y, board_bounds),
+        "rotation": footprint.rotation,
+        "bounds": dict(footprint.bounds),
+        "view_bounds": _view_bounds(footprint.bounds, board_bounds),
+        "side": footprint.side,
+        "summary": f"{category_name},用途未注释",
+        "connector": None,
+        "pins": [
+            _pin_dict(footprint.reference, category, pad, board_bounds, index)
+            for index, pad in enumerate(footprint.pads)
+        ],
+    }
+
+
+def _connector_profile_index(
+    annotations: Mapping[str, object],
+) -> dict[str, tuple[str, Mapping[str, object]]]:
+    result: dict[str, tuple[str, Mapping[str, object]]] = {}
+    profiles = annotations.get("connector_profiles", {})
+    if not isinstance(profiles, Mapping):
+        return result
+    for profile_name, profile in profiles.items():
+        if not isinstance(profile, Mapping):
+            continue
+        references = profile.get("references", [])
+        if not isinstance(references, list):
+            continue
+        for reference in references:
+            result[str(reference)] = (str(profile_name), profile)
+    return result
+
+
+def _cluster_contact_rows(pins: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
+    rows: list[list[dict[str, Any]]] = []
+    row_y: list[float] = []
+    ordered = sorted(
+        pins,
+        key=lambda item: (float(item["position"]["y"]), float(item["position"]["x"])),
+    )
+    for pin in ordered:
+        y = float(pin["position"]["y"])
+        if not rows or abs(y - row_y[-1]) > CONNECTOR_ROW_TOLERANCE_MM:
+            rows.append([pin])
+            row_y.append(y)
+            continue
+        rows[-1].append(pin)
+        row_y[-1] = sum(float(item["position"]["y"]) for item in rows[-1]) / len(rows[-1])
+    for row in rows:
+        row.sort(key=lambda item: (float(item["position"]["x"]), str(item["number"])))
+    return rows
+
+
+def _pin_sort_key(pin: Mapping[str, object]) -> tuple[int, int, str]:
+    role_order = {"contact": 0, "shield": 1, "mechanical": 2, "unknown": 3}
+    board_order = pin.get("board_order")
+    return (
+        role_order.get(str(pin.get("pad_role")), 4),
+        int(board_order) if isinstance(board_order, int) else 1_000_000,
+        str(pin.get("id") or ""),
+    )
+
+
+def _apply_connector_profile(
+    touchpoint: dict[str, Any],
+    profile_entry: tuple[str, Mapping[str, object]] | None,
+) -> None:
+    pins = touchpoint["pins"]
+    if profile_entry is None:
+        touchpoint["connector"] = {
+            "profile": None,
+            "review_status": "unknown",
+            "view": "board_front",
+            "contact_count": 0,
+            "auxiliary_pad_count": len(pins),
+            "rows": 0,
+            "columns": 0,
+            "contact_grid": [],
+            "contact_order": [],
+            "sources": [],
+        }
+        pins.sort(key=_pin_sort_key)
+        return
+
+    profile_name, profile = profile_entry
+    contacts = {str(value) for value in profile.get("contact_pins", [])}
+    shields = {str(value) for value in profile.get("shield_pads", [])}
+    for pin in pins:
+        number = str(pin["number"])
+        if pin["mechanical"]:
+            pin["pad_role"] = "mechanical"
+        elif number in contacts:
+            pin["pad_role"] = "contact"
+        elif number in shields:
+            pin["pad_role"] = "shield"
+        else:
+            pin["pad_role"] = "unknown"
+
+    contact_pins = [pin for pin in pins if pin["pad_role"] == "contact"]
+    rows = _cluster_contact_rows(contact_pins)
+    contact_grid: list[list[str]] = []
+    order = 1
+    for row_number, row in enumerate(rows, start=1):
+        grid_row: list[str] = []
+        for column_number, pin in enumerate(row, start=1):
+            pin["row"] = row_number
+            pin["column"] = column_number
+            pin["board_order"] = order
+            grid_row.append(str(pin["number"]))
+            order += 1
+        contact_grid.append(grid_row)
+
+    touchpoint["connector"] = {
+        "profile": profile_name,
+        "review_status": str(profile.get("evidence_tier") or "unknown"),
+        "view": "board_front",
+        "contact_count": len(contact_pins),
+        "auxiliary_pad_count": len(pins) - len(contact_pins),
+        "rows": len(contact_grid),
+        "columns": max((len(row) for row in contact_grid), default=0),
+        "contact_grid": contact_grid,
+        "contact_order": [number for row in contact_grid for number in row],
+        "sources": [str(value) for value in profile.get("sources", [])],
+    }
+    pins.sort(key=_pin_sort_key)
+
+
+def _inventory_indexes(inventory: Mapping[str, object]) -> tuple[dict[tuple[str, str], Mapping[str, object]], dict[str, list[Mapping[str, object]]]]:
+    direct: dict[tuple[str, str], Mapping[str, object]] = {}
+    by_net: dict[str, list[Mapping[str, object]]] = {}
+    pins = inventory.get("pins", [])
+    if not isinstance(pins, list):
+        return direct, by_net
+    for item in pins:
+        if not isinstance(item, Mapping):
+            continue
+        connector = item.get("board_connector")
+        connector_pin = item.get("connector_pin")
+        if connector and connector_pin is not None:
+            direct[(str(connector), str(connector_pin))] = item
+        for name in (item.get("function_net"), item.get("signal")):
+            if name:
+                by_net.setdefault(str(name), []).append(item)
+    return direct, by_net
+
+
+def _inventory_match(
+    reference: str,
+    pin: Mapping[str, object],
+    direct: Mapping[tuple[str, str], Mapping[str, object]],
+    by_net: Mapping[str, list[Mapping[str, object]]],
+) -> Mapping[str, object] | None:
+    key = (reference, str(pin.get("number", "")))
+    if key in direct:
+        item = direct[key]
+        expected_net = item.get("connector_signal") or item.get("function_net") or item.get("signal")
+        actual_net = pin.get("net")
+        if expected_net and actual_net and str(expected_net) != str(actual_net):
+            raise ValueError(
+                f"connector net mismatch {reference}.{pin.get('number')}: "
+                f"board={actual_net} inventory={expected_net}"
+            )
+        return item
+    net = pin.get("net")
+    matches = by_net.get(str(net), []) if net else []
+    return matches[0] if len(matches) == 1 else None
+
+
+def _inventory_source(item: Mapping[str, object]) -> str:
+    marker = item.get("screenshot_index") or item.get("source_confidence") or item.get("signal")
+    return f"inventory:{marker}"
+
+
+def _merge_inventory(pin: dict[str, Any], item: Mapping[str, object]) -> None:
+    capabilities = [str(value) for value in item.get("capability", [])]
+    verified = item.get("manually_verified") is True
+    evidence_tier = "cross_verified" if verified else "name_inferred"
+    source = _inventory_source(item)
+    board_pull = item.get("board_pull")
+    if board_pull is None:
+        board_pull = item.get("pullup")
+    external_components = []
+    for key in ("transceiver", "series_link", "esd"):
+        value = item.get(key)
+        if value and str(value) not in external_components:
+            external_components.append(str(value))
+    pin.update(
+        {
+            "direction": str(item.get("direction") or "unknown"),
+            "external_level": str(item.get("external_level") or "unknown"),
+            "function_category": _classify_function(str(item.get("function_net") or pin.get("net") or ""), capabilities),
+            "reserved": item.get("reserved") is True,
+            "fixed_load_conflict": item.get("fixed_load_conflict") is True,
+            "board_pull": board_pull,
+            "active_level": str(item.get("active_level") or "unknown"),
+            "polarity": str(item.get("polarity") or "unknown"),
+            "external_components": external_components,
+            "evidence_tier": evidence_tier,
+            "evidence_sources": [*pin["evidence_sources"], source],
+            "fpga": {
+                "ball": str(item.get("fpga_ball") or ""),
+                "board_signal": str(item.get("signal") or item.get("function_net") or ""),
+                "io_standard": str(item.get("io_standard") or ""),
+                "capabilities": capabilities,
+                "evidence_tier": evidence_tier,
+                "sources": [source],
+            },
+        }
+    )
+    transceiver = item.get("transceiver")
+    if transceiver:
+        pin["path"] = [str(transceiver)]
+    signal = item.get("signal") or item.get("function_net")
+    if signal:
+        pin["summary"] = str(signal)
+
+
+def _merge_annotation(pin: dict[str, Any], annotation: Mapping[str, object]) -> None:
+    for key in (
+        "summary",
+        "direction",
+        "external_level",
+        "function_category",
+        "reserved",
+        "fixed_load_conflict",
+        "board_pull",
+        "adc_pulltype",
+        "active_level",
+        "polarity",
+        "external_components",
+        "path",
+    ):
+        if key in annotation:
+            pin[key] = annotation[key]
+    fpga = annotation.get("fpga")
+    if isinstance(fpga, Mapping):
+        pin["fpga"] = {
+            "ball": str(fpga.get("ball") or ""),
+            "board_signal": str(fpga.get("board_signal") or ""),
+            "io_standard": str(fpga.get("io_standard") or ""),
+            "capabilities": [str(value) for value in fpga.get("capabilities", [])],
+            "evidence_tier": str(fpga.get("evidence_tier") or "unknown"),
+            "sources": [str(value) for value in fpga.get("sources", [])],
+        }
+    mcu = annotation.get("mcu")
+    if isinstance(mcu, Mapping):
+        pin["mcu"] = {
+            "device": str(mcu.get("device") or ""),
+            "family": str(mcu.get("family") or ""),
+            "pin": str(mcu.get("pin") or ""),
+            "signal": str(mcu.get("signal") or ""),
+            "capabilities": [str(value) for value in mcu.get("capabilities", [])],
+            "evidence_tier": str(mcu.get("evidence_tier") or "unknown"),
+            "sources": [str(value) for value in mcu.get("sources", [])],
+        }
+    tier = annotation.get("evidence_tier")
+    if tier in EVIDENCE_TIERS:
+        pin["evidence_tier"] = tier
+        if isinstance(pin.get("fpga"), dict):
+            pin["fpga"]["evidence_tier"] = tier
+    sources = annotation.get("sources", [])
+    if isinstance(sources, list):
+        pin["evidence_sources"] = [*pin["evidence_sources"], *[str(item) for item in sources]]
+
+
+def _unique_strings(values: list[object]) -> list[str]:
+    result: list[str] = []
+    for value in values:
+        text = str(value)
+        if text and text not in result:
+            result.append(text)
+    return result
+
+
+def _verified_fpga(pin: Mapping[str, object]) -> Mapping[str, object] | None:
+    fpga = pin.get("fpga")
+    if (
+        pin.get("evidence_tier") == "cross_verified"
+        and isinstance(fpga, Mapping)
+        and fpga.get("evidence_tier") == "cross_verified"
+        and fpga.get("ball")
+        and fpga.get("io_standard")
+    ):
+        return fpga
+    return None
+
+
+def _verified_mcu(pin: Mapping[str, object]) -> Mapping[str, object] | None:
+    mcu = pin.get("mcu")
+    if (
+        pin.get("evidence_tier") == "cross_verified"
+        and isinstance(mcu, Mapping)
+        and mcu.get("evidence_tier") == "cross_verified"
+        and mcu.get("device")
+        and mcu.get("family")
+        and mcu.get("pin")
+        and mcu.get("signal")
+    ):
+        return mcu
+    return None
+
+
+def _programming_guidance(reference: str, pin: Mapping[str, object]) -> dict[str, object]:
+    number = str(pin.get("number") or "")
+    net = str(pin.get("net") or "")
+    role = str(pin.get("pad_role") or "unknown")
+    function_category = str(pin.get("function_category") or "unknown")
+    direction = str(pin.get("direction") or "unknown")
+    external_level = str(pin.get("external_level") or "unknown")
+    fpga = _verified_fpga(pin)
+    mcu = _verified_mcu(pin)
+    sources = _unique_strings(list(pin.get("evidence_sources", [])))
+
+    if role == "mechanical" or pin.get("mechanical") is True or pin.get("electrical") is not True:
+        return {
+            "status": "not_programmable",
+            "conclusion": "这是机械定位孔,不是电气针脚。",
+            "network_explanation": "机械孔没有可用于编程的板内网络。",
+            "hdl_guidance": "不要声明 RTL 端口,也不能生成 ADC 约束。",
+            "connection_guidance": ["不要把机械孔作为信号、电源或地连接点。"],
+            "constraints": [],
+            "risks": ["它只承担机械定位或固定作用。"],
+            "evidence_tier": "board_database",
+            "sources": sources,
+        }
+
+    if role == "shield":
+        grounded = net.upper() in {"GND", "AGND", "DGND", "PGND"}
+        network = "并与板级 GND 相连" if grounded else f"板数据库网络为 {net or '未命名'}"
+        return {
+            "status": "not_programmable",
+            "conclusion": "这是屏蔽/固定焊盘,不属于座子对外接触针。",
+            "network_explanation": f"该焊盘用于连接器外壳或固定,{network}。",
+            "hdl_guidance": "不要为它声明 RTL 端口,也不能生成 ADC 约束。",
+            "connection_guidance": ["线束 pinout 只使用标记为“接触针”的焊盘。"],
+            "constraints": [],
+            "risks": ["把屏蔽固定焊盘当作外部 Pin 会造成针脚数量和顺序错误。"],
+            "evidence_tier": str(pin.get("evidence_tier") or "board_database"),
+            "sources": sources,
+        }
+
+    if function_category == "ground" or net.upper() in {"GND", "AGND", "DGND", "PGND"}:
+        return {
+            "status": "not_programmable",
+            "conclusion": "这是接地针,用作信号参考和电流回路,不是 FPGA I/O。",
+            "network_explanation": f"板数据库确认 {reference}.{number} 连接到板级 {net or 'GND'}。",
+            "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。",
+            "connection_guidance": ["作为外部设备的参考地/回流地连接,不要当作逻辑信号脚。"],
+            "constraints": [],
+            "risks": ["接线时仍需遵守整机接地和回流设计。"],
+            "evidence_tier": str(pin.get("evidence_tier") or "board_database"),
+            "sources": sources,
+        }
+
+    if mcu is not None:
+        device = str(mcu.get("device"))
+        family = str(mcu.get("family"))
+        package_pin = str(mcu.get("pin"))
+        signal = str(mcu.get("signal"))
+        return {
+            "status": "verified_mcu",
+            "conclusion": (
+                f"GD32 MCU 固件测试点:{reference}.{number} 直连 "
+                f"{device}.{package_pin}({signal},{family})。"
+            ),
+            "network_explanation": (
+                f"板数据库与原理图共同确认网络 {net or signal} 对应 "
+                f"{device} 封装引脚 {package_pin} / 端口 {signal};它不是 FPGA 球位。"
+            ),
+            "hdl_guidance": (
+                f"不要在 FPGA RTL/ADC 中声明此针;应在 GD32 固件中按 {signal} "
+                "配置 GPIO 或所需复用功能,方向和复用选择由当前 MCU 固件决定。"
+            ),
+            "connection_guidance": [
+                f"外接仪器或信号前按 {external_level} 边界检查,并与板级 GND 共参考。",
+                "作为测量点使用时优先采用高阻探头,避免改变 MCU 引脚状态。",
+            ],
+            "constraints": [
+                f"MCU = {family} {device}",
+                f"PACKAGE_PIN = {package_pin}",
+                f"PORT = {signal}",
+            ],
+            "risks": [
+                "查看器不读取当前 MCU 固件,仍需检查端口复用、启动状态和外设占用。",
+                "此映射不能生成 FPGA ADC 约束。",
+            ],
+            "evidence_tier": "cross_verified",
+            "sources": sources,
+        }
+
+    if fpga is not None:
+        signal = str(fpga.get("board_signal") or pin.get("summary") or net)
+        ball = str(fpga.get("ball"))
+        io_standard = str(fpga.get("io_standard"))
+        components = [str(value) for value in pin.get("external_components", []) if value]
+        transceiver = next((value for value in components if value.upper().startswith("U")), None)
+        if direction == "output":
+            route = f"经 {transceiver} 转换后" if transceiver else "通过板内网络"
+            conclusion = f"FPGA 输出:RTL 驱动 {signal}(球位 {ball}),{route}从 {reference}.{number} 发出。"
+        elif direction == "input":
+            route = f"先经 {transceiver} 转换,再" if transceiver else "通过板内网络"
+            conclusion = f"FPGA 输入:外部信号从 {reference}.{number} 进入,{route}由 {signal}(球位 {ball})采样。"
+        elif direction in {"bidir", "bidirectional"} and function_category == "gpio":
+            conclusion = (
+                f"已验证直连 FPGA GPIO:{reference}.{number} 对应 {signal}(球位 {ball}),"
+                "物理上支持输入或输出。"
+            )
+        else:
+            conclusion = f"已验证 FPGA 路径:{reference}.{number} 对应 {signal}(球位 {ball}),方向为 {direction}。"
+
+        if transceiver:
+            network_explanation = (
+                f"连接器侧原始网络是 {net or '未命名'};经 {transceiver} 后,"
+                f"FPGA 逻辑侧信号是 {signal}。"
+            )
+        else:
+            network_explanation = (
+                f"板数据库网络 {net or '未命名'} 已交叉验证到 FPGA 逻辑信号 {signal}({ball})。"
+            )
+
+        connection_guidance: list[str] = []
+        if direction == "output" and function_category == "uart_tx":
+            connection_guidance.append("连接到对端设备的接收端(RX)。")
+        elif direction == "input" and function_category == "uart_rx":
+            connection_guidance.append("连接到对端设备的发送端(TX)。")
+        elif direction == "output":
+            connection_guidance.append("这是板端输出;外部设备应作为接收端,不要与另一个主动输出直接相连。")
+        elif direction == "input":
+            connection_guidance.append("这是板端输入;由外部设备驱动,接入前确认电平和公共参考地。")
+        elif direction in {"bidir", "bidirectional"} and function_category == "gpio":
+            connection_guidance.append(
+                "按实际用途选择输入或输出;配置为输入时由外部设备驱动,配置为输出时不要与另一个主动输出硬连接。"
+            )
+        else:
+            connection_guidance.append("按已验证方向使用;双向信号需要在 RTL 中正确控制输出使能。")
+        if external_level.upper() == "RS232":
+            connection_guidance.append("连接器侧是 RS-232 电平,不能直接接 3.3V TTL/CMOS 串口。")
+
+        if direction in {"bidir", "bidirectional"} and function_category == "gpio":
+            hdl_guidance = (
+                f"该物理脚支持 input、output 或 inout,按实际功能选择;"
+                f"只有真正需要双向共享并实现输出使能时才使用三态 inout。FPGA 逻辑侧使用 {io_standard}。"
+            )
+        else:
+            hdl_guidance = f"RTL 端口方向应为 {direction};FPGA 逻辑侧使用 {io_standard}。"
+        active_level = str(pin.get("active_level") or "unknown")
+        if active_level in {"high", "low"}:
+            active_cn = "高" if active_level == "high" else "低"
+            hdl_guidance += f" 此功能为{active_cn}电平有效。"
+
+        constraints = [f"LOCATION = {ball}", f"IOSTANDARD = {io_standard}"]
+        board_pull = pin.get("board_pull")
+        if board_pull:
+            constraints.append(f"板上外部 pull:{board_pull}")
+        if active_level in {"high", "low"}:
+            constraints.append(f"有效电平:{'高电平' if active_level == 'high' else '低电平'}")
+        risks = ["这里只证明物理路径和板级证据,仍需检查当前工程约束冲突。"]
+        if direction in {"bidir", "bidirectional"} and function_category == "gpio":
+            risks.insert(0, "不要因为物理上可双向就默认声明 inout;错误的三态控制可能造成总线争用。")
+        if pin.get("reserved") is True:
+            risks.insert(0, "当前 inventory 将此功能标记为保留,不能作为空闲 GPIO 重新分配。")
+        if pin.get("fixed_load_conflict") is True:
+            risks.insert(0, "此针存在已知固定负载冲突。")
+        return {
+            "status": "verified_fpga",
+            "conclusion": conclusion,
+            "network_explanation": network_explanation,
+            "hdl_guidance": hdl_guidance,
+            "connection_guidance": connection_guidance,
+            "constraints": constraints,
+            "risks": risks,
+            "evidence_tier": "cross_verified",
+            "sources": sources,
+        }
+
+    if function_category == "power" or POWER_NET.match(net):
+        if pin.get("evidence_tier") == "cross_verified":
+            summary = str(pin.get("summary") or f"电源网络 {net or '未命名'}").rstrip("。")
+            path = [str(item) for item in pin.get("path", []) if item]
+            path_text = " -> ".join(path) if path else f"{reference}.{number} {net or '未命名'}"
+            direction_text = {
+                "input": "板端电源输入",
+                "output": "板端电源输出",
+                "passive": "电源参考/分配节点",
+            }.get(direction, f"方向 {direction}")
+            if direction == "input":
+                connection_guidance = [
+                    f"这是{direction_text};只能接符合 {external_level} 边界的电源,并核对极性与公共地。"
+                ]
+                direction_risk = "不要反向供电或从该输入针向外取电。"
+            elif direction == "output":
+                connection_guidance = [
+                    f"这是{direction_text};只用于给设计负载提供 {external_level},不要与另一电源输出并接。"
+                ]
+                direction_risk = "不要向该输出针反向供电。"
+            else:
+                connection_guidance = [
+                    f"这是{direction_text};按原理图定义使用,并遵守 {external_level} 电气边界。"
+                ]
+                direction_risk = "不要把电源参考/分配节点当作普通信号或任意供电入口。"
+            return {
+                "status": "not_programmable",
+                "conclusion": f"{summary}。这是{direction_text},不是 FPGA I/O,不能用于逻辑选脚。",
+                "network_explanation": (
+                    f"原理图与板数据库交叉确认路径:{path_text};"
+                    f"外部电气边界为 {external_level},方向为 {direction_text}。"
+                ),
+                "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。",
+                "connection_guidance": connection_guidance,
+                "constraints": [],
+                "risks": [
+                    direction_risk,
+                    "查看器不证明额定电流、线束载流能力或选配保护器件的实际装配状态,仍需核对 BOM 和整机规范。",
+                ],
+                "evidence_tier": "cross_verified",
+                "sources": sources,
+            }
+        return {
+            "status": "not_programmable",
+            "conclusion": "这是电源网络,不是 FPGA I/O,不能用于逻辑选脚。",
+            "network_explanation": (
+                f"按板数据库网名 {net or '未命名'} 可判断它属于电源域;"
+                "供电方向、额定电流和是否允许外供尚未在查看器中交叉验证。"
+            ),
+            "hdl_guidance": "不要为此针声明 RTL 端口,也不能生成 ADC 约束。",
+            "connection_guidance": ["连接前必须查原理图和整机线束,确认电压、方向与电流能力。"],
+            "constraints": [],
+            "risks": ["错误接入 FPGA 3.3V I/O 可能造成硬件损坏。"],
+            "evidence_tier": "name_inferred",
+            "sources": sources,
+        }
+
+    if INTERNAL_NET.match(net):
+        network_explanation = (
+            f"{net} 是 CAD 自动生成的内部网络编号,只能证明同名焊盘电气相连;"
+            "编号本身不包含功能、方向或电平含义。"
+        )
+    elif net:
+        network_explanation = (
+            f"板数据库确认此焊盘连接到 {net};当前没有足够证据把该网名等同于某个 FPGA 端口。"
+        )
+    else:
+        network_explanation = "该电气焊盘没有可解释的网络名,功能保持未知。"
+    return {
+        "status": "board_only" if net else "unknown",
+        "conclusion": f"当前只确认到板内网络 {net or '未知'},没有已验证 FPGA 路径。",
+        "network_explanation": network_explanation,
+        "hdl_guidance": "不能据此写 RTL 方向或 ADC 约束;需要原理图路径或人工交叉验证。",
+        "connection_guidance": ["接线前先确认该网络经过的器件、外部电平和信号方向。"],
+        "constraints": [],
+        "risks": ["网名相似不等于功能相同,禁止仅凭名称推断 FPGA 映射。"],
+        "evidence_tier": "board_database" if net else "unknown",
+        "sources": sources,
+    }
+
+
+def _merge_programming_annotation(
+    programming: dict[str, object], annotation: Mapping[str, object]
+) -> None:
+    for key in (
+        "status",
+        "conclusion",
+        "network_explanation",
+        "hdl_guidance",
+        "connection_guidance",
+        "constraints",
+        "risks",
+    ):
+        if key in annotation:
+            programming[key] = annotation[key]
+    tier = annotation.get("evidence_tier")
+    if tier in EVIDENCE_TIERS:
+        programming["evidence_tier"] = tier
+    sources = annotation.get("sources", [])
+    if isinstance(sources, list):
+        programming["sources"] = _unique_strings(
+            [*list(programming.get("sources", [])), *sources]
+        )
+
+
+def _refresh_recommendation(pin: dict[str, Any]) -> None:
+    fpga = pin.get("fpga")
+    capabilities = fpga.get("capabilities", []) if isinstance(fpga, Mapping) else []
+    useful = [item for item in capabilities if item not in {"gpio", "rs232_via_transceiver"}]
+    capability = str(useful[0] if useful else (capabilities[0] if capabilities else "gpio"))
+    result = evaluate_recommendation(pin, capability)
+    pin["recommendation"] = {"eligible": result.eligible, "reasons": result.reasons}
+
+
+def build_board_data(
+    board: ParsedBoard,
+    inventory: Mapping[str, object],
+    annotations: Mapping[str, object],
+    *,
+    board_name: str,
+) -> dict[str, Any]:
+    annotations = expand_annotation_templates(annotations)
+    touchpoints = [_touchpoint_dict(footprint, board.bounds) for footprint in select_touchpoints(board)]
+    touchpoint_index = {item["reference"]: item for item in touchpoints}
+    validate_annotation_references(annotations, touchpoint_index)
+    connector_profiles = _connector_profile_index(annotations)
+    direct, by_net = _inventory_indexes(inventory)
+    annotated_touchpoints = annotations.get("touchpoints", {})
+
+    for touchpoint in touchpoints:
+        reference = touchpoint["reference"]
+        profile_entry = connector_profiles.get(reference)
+        if touchpoint["category"] == "CON" or profile_entry is not None:
+            _apply_connector_profile(touchpoint, profile_entry)
+        touchpoint_annotation = (
+            annotated_touchpoints.get(reference, {}) if isinstance(annotated_touchpoints, Mapping) else {}
+        )
+        if isinstance(touchpoint_annotation, Mapping) and touchpoint_annotation.get("summary"):
+            touchpoint["summary"] = str(touchpoint_annotation["summary"])
+        pin_annotations = (
+            touchpoint_annotation.get("pins", {}) if isinstance(touchpoint_annotation, Mapping) else {}
+        )
+        for pin in touchpoint["pins"]:
+            inventory_item = _inventory_match(reference, pin, direct, by_net)
+            if inventory_item is not None:
+                _merge_inventory(pin, inventory_item)
+            annotation = pin_annotations.get(pin["number"], {}) if isinstance(pin_annotations, Mapping) else {}
+            if isinstance(annotation, Mapping):
+                _merge_annotation(pin, annotation)
+            pin["programming"] = _programming_guidance(reference, pin)
+            programming_annotation = annotation.get("programming", {}) if isinstance(annotation, Mapping) else {}
+            if isinstance(programming_annotation, Mapping):
+                _merge_programming_annotation(pin["programming"], programming_annotation)
+            _refresh_recommendation(pin)
+
+    category_counts = Counter(item["category"] for item in touchpoints)
+    side_counts = Counter(item["side"] for item in touchpoints)
+    connector_touchpoints = [item for item in touchpoints if item["category"] == "CON"]
+    return {
+        "schema": "board-viewer-data-v1",
+        "board": {
+            "id": str(inventory.get("board_id") or annotations.get("board_id") or "unknown"),
+            "name": board_name,
+            "source_bounds": dict(board.bounds),
+            "view_box": {"x": 0.0, "y": 0.0, "width": board.bounds["width"], "height": board.bounds["height"]},
+        },
+        "counts": {
+            "footprints": board.footprint_count,
+            "touchpoints": len(touchpoints),
+            "pads": sum(len(item["pins"]) for item in touchpoints),
+            "connector_contacts": sum(
+                int(item["connector"]["contact_count"]) for item in connector_touchpoints
+            ),
+            "connector_auxiliary_pads": sum(
+                int(item["connector"]["auxiliary_pad_count"]) for item in connector_touchpoints
+            ),
+            "categories": {key: category_counts.get(key, 0) for key in ("CON", "J", "PL", "TP")},
+            "sides": {key: side_counts.get(key, 0) for key in ("front", "back")},
+        },
+        "touchpoints": touchpoints,
+        "interfaces": list(annotations.get("interfaces", [])) if isinstance(annotations.get("interfaces", []), list) else [],
+        "photo_overlay": annotations.get("photo_overlay"),
+    }

+ 73 - 0
tools/board-viewer/board_viewer/eligibility.py

@@ -0,0 +1,73 @@
+"""Fail-closed pin recommendation eligibility rules."""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import dataclass
+
+
+@dataclass(frozen=True)
+class EligibilityResult:
+    eligible: bool
+    reasons: list[str]
+
+
+def _is_power_or_ground(pin: Mapping[str, object]) -> bool:
+    category = str(pin.get("function_category") or "").lower()
+    net = str(pin.get("net") or "").upper()
+    if category in {"power", "ground"}:
+        return True
+    if net in {"GND", "AGND", "DGND", "PGND", "EARTH"}:
+        return True
+    return net.startswith(("+", "VCC", "VDD", "VBAT", "PWR"))
+
+
+def evaluate_recommendation(pin: Mapping[str, object], capability: str) -> EligibilityResult:
+    reasons: list[str] = []
+    fpga = pin.get("fpga")
+    fpga_map = fpga if isinstance(fpga, Mapping) else {}
+    capabilities = {str(item) for item in fpga_map.get("capabilities", [])}
+
+    if capability in capabilities:
+        reasons.append("capability_match")
+    else:
+        reasons.append("capability_mismatch")
+
+    verified = (
+        pin.get("evidence_tier") == "cross_verified"
+        and fpga_map.get("evidence_tier") == "cross_verified"
+        and bool(fpga_map.get("ball"))
+        and bool(fpga_map.get("io_standard"))
+    )
+    if verified:
+        reasons.append("verified_fpga_path")
+    else:
+        reasons.append("pin_evidence_not_verified")
+
+    if pin.get("external_level") not in {None, "", "unknown"}:
+        reasons.append("external_level_known")
+    else:
+        reasons.append("external_level_unknown")
+
+    if pin.get("mechanical") is True or pin.get("electrical") is not True:
+        reasons.append("mechanical_or_non_electrical")
+    if pin.get("pad_role") != "contact":
+        reasons.append("not_connector_contact")
+    if _is_power_or_ground(pin):
+        reasons.append("power_or_ground")
+    if pin.get("reserved") is True:
+        reasons.append("reserved")
+    if pin.get("fixed_load_conflict") is True:
+        reasons.append("fixed_load_conflict")
+
+    blockers = {
+        "capability_mismatch",
+        "pin_evidence_not_verified",
+        "external_level_unknown",
+        "mechanical_or_non_electrical",
+        "not_connector_contact",
+        "power_or_ground",
+        "reserved",
+        "fixed_load_conflict",
+    }
+    return EligibilityResult(eligible=not blockers.intersection(reasons), reasons=reasons)

+ 423 - 0
tools/board-viewer/board_viewer/generator.py

@@ -0,0 +1,423 @@
+"""Offline KiCad import and generated board-viewer asset pipeline."""
+
+from __future__ import annotations
+
+import json
+import os
+import platform
+import shutil
+import subprocess
+import tempfile
+import uuid
+import xml.etree.ElementTree as ET
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from pathlib import Path
+from typing import Any, Protocol
+
+from jsonschema import Draft202012Validator
+
+from .assets import sha256_file, validate_generated_assets
+from .data import build_board_data
+from .ipcd356 import IpCd356AlignmentError, validate_ipcd356_alignment
+from .pcb import parse_kicad_pcb
+from .photo import PhotoOverlayError, prepare_photo_overlay
+from .regression import BoardRegressionError, validate_product_regression
+
+
+ROOT = Path(__file__).resolve().parents[3]
+DATA_SCHEMA = ROOT / "schemas" / "board_viewer_data.schema.json"
+ANNOTATION_SCHEMA = ROOT / "schemas" / "board_viewer_annotations.schema.json"
+GENERATOR_VERSION = "1.1.0"
+GENERATOR_SOURCE_PATHS = {
+    "generator_pipeline": Path(__file__).resolve(),
+    "generator_data": ROOT / "tools" / "board-viewer" / "board_viewer" / "data.py",
+    "generator_annotations": ROOT / "tools" / "board-viewer" / "board_viewer" / "annotations.py",
+    "generator_eligibility": ROOT / "tools" / "board-viewer" / "board_viewer" / "eligibility.py",
+    "generator_pcb": ROOT / "tools" / "board-viewer" / "board_viewer" / "pcb.py",
+    "generator_sexpr": ROOT / "tools" / "board-viewer" / "board_viewer" / "sexpr.py",
+    "generator_ipcd356": ROOT / "tools" / "board-viewer" / "board_viewer" / "ipcd356.py",
+    "generator_photo": ROOT / "tools" / "board-viewer" / "board_viewer" / "photo.py",
+    "generator_regression": ROOT / "tools" / "board-viewer" / "board_viewer" / "regression.py",
+    "schema_data": DATA_SCHEMA,
+    "schema_annotations": ANNOTATION_SCHEMA,
+}
+
+
+class GenerationError(RuntimeError):
+    """Raised when a generated bundle cannot be completed and validated."""
+
+
+class CommandResult(Protocol):
+    returncode: int
+    stdout: str
+    stderr: str
+
+
+Runner = Callable[[list[str], Path], CommandResult]
+
+
+@dataclass
+class GenerationConfig:
+    brd_path: Path
+    inventory_path: Path
+    annotations_path: Path
+    output_dir: Path
+    kicad_cli: Path
+    board_name: str
+    required_kicad_version: str = "10.0.4"
+    expected_counts: Mapping[str, int] | None = None
+    expected_front_only: bool = True
+    product_regression: bool = False
+    photo_root: Path = ROOT
+    temp_parent: Path | None = None
+
+
+def _default_runner(command: list[str], cwd: Path) -> subprocess.CompletedProcess[str]:
+    return subprocess.run(
+        command,
+        cwd=cwd,
+        check=False,
+        capture_output=True,
+        text=True,
+        encoding="utf-8",
+        errors="replace",
+    )
+
+
+def _run_checked(runner: Runner, command: list[str], cwd: Path) -> CommandResult:
+    result = runner(command, cwd)
+    if result.returncode != 0:
+        detail = (result.stderr or result.stdout or "command failed").strip()
+        raise GenerationError(detail)
+    return result
+
+
+def _load_json(path: Path) -> dict[str, Any]:
+    try:
+        payload = json.loads(path.read_text(encoding="utf-8"))
+    except (OSError, json.JSONDecodeError) as exc:
+        raise GenerationError(f"cannot read JSON {path}: {exc}") from exc
+    if not isinstance(payload, dict):
+        raise GenerationError(f"JSON root must be an object: {path}")
+    return payload
+
+
+def _validate_schema(payload: object, schema_path: Path, label: str) -> None:
+    schema = _load_json(schema_path)
+    errors = sorted(Draft202012Validator(schema).iter_errors(payload), key=lambda item: list(item.path))
+    if errors:
+        locations = [".".join(str(part) for part in error.path) or "<root>" for error in errors[:5]]
+        raise GenerationError(f"{label} schema validation failed at: {', '.join(locations)}")
+
+
+def _ensure_outside_repository(path: Path) -> Path:
+    resolved = path.resolve()
+    try:
+        resolved.relative_to(ROOT.resolve())
+    except ValueError:
+        return resolved
+    raise GenerationError("temporary directory must be outside repository")
+
+
+def _verify_inputs(config: GenerationConfig) -> Path:
+    for path, label in (
+        (config.brd_path, "BRD source"),
+        (config.inventory_path, "pin inventory"),
+        (config.annotations_path, "annotations"),
+        (config.kicad_cli, "KiCad CLI"),
+    ):
+        if not Path(path).is_file():
+            raise GenerationError(f"missing {label}: {path}")
+    temp_parent = config.temp_parent or Path(tempfile.gettempdir())
+    temp_parent = _ensure_outside_repository(Path(temp_parent))
+    temp_parent.mkdir(parents=True, exist_ok=True)
+    return temp_parent
+
+
+def _verify_kicad_version(config: GenerationConfig, runner: Runner, cwd: Path) -> str:
+    result = _run_checked(runner, [str(config.kicad_cli), "--version"], cwd)
+    version = result.stdout.strip().splitlines()[0] if result.stdout.strip() else "unknown"
+    if version != config.required_kicad_version:
+        raise GenerationError(
+            f"board viewer generation requires KiCad {config.required_kicad_version}, found {version}"
+        )
+    return version
+
+
+def _write_json(path: Path, payload: object) -> None:
+    path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
+
+
+def _normalize_svg(path: Path, title: str) -> tuple[float, float]:
+    try:
+        tree = ET.parse(path)
+    except (OSError, ET.ParseError) as exc:
+        raise GenerationError(f"invalid SVG {path.name}: {exc}") from exc
+    root = tree.getroot()
+    if root.tag.rsplit("}", 1)[-1] != "svg":
+        raise GenerationError(f"invalid SVG root: {path.name}")
+    title_element = next((item for item in root if item.tag.rsplit("}", 1)[-1] == "title"), None)
+    if title_element is not None:
+        title_element.text = title
+    view_box = root.get("viewBox", "").replace(",", " ").split()
+    if len(view_box) != 4:
+        raise GenerationError(f"SVG has no usable viewBox: {path.name}")
+    try:
+        width, height = float(view_box[2]), float(view_box[3])
+    except ValueError as exc:
+        raise GenerationError(f"SVG has invalid viewBox: {path.name}") from exc
+    ET.register_namespace("", "http://www.w3.org/2000/svg")
+    ET.register_namespace("xlink", "http://www.w3.org/1999/xlink")
+    tree.write(path, encoding="utf-8", xml_declaration=True)
+    return width, height
+
+
+def _validate_counts(payload: Mapping[str, object], config: GenerationConfig) -> None:
+    counts = payload["counts"]
+    if not isinstance(counts, Mapping):
+        raise GenerationError("generated board counts are missing")
+    if config.expected_counts:
+        mismatches = [
+            f"{name}={counts.get(name)} expected {expected}"
+            for name, expected in config.expected_counts.items()
+            if counts.get(name) != expected
+        ]
+        if mismatches:
+            raise GenerationError("board regression mismatch: " + ", ".join(mismatches))
+    sides = counts.get("sides", {})
+    if config.expected_front_only and isinstance(sides, Mapping) and sides.get("back") != 0:
+        raise GenerationError(f"board regression mismatch: target back-side count is {sides.get('back')}")
+
+
+def _import_board(config: GenerationConfig, runner: Runner, work: Path) -> tuple[Path, dict[str, Any]]:
+    imported = work / "board.kicad_pcb"
+    report_path = work / "import-report.json"
+    command = [
+        str(config.kicad_cli),
+        "pcb",
+        "import",
+        "--format",
+        "auto",
+        "--output",
+        str(imported),
+        "--report-format",
+        "json",
+        "--report-file",
+        str(report_path),
+        str(config.brd_path.resolve()),
+    ]
+    _run_checked(runner, command, work)
+    if not imported.is_file() or not report_path.is_file():
+        raise GenerationError("KiCad import did not create the board and report")
+    report = _load_json(report_path)
+    if report.get("errors"):
+        raise GenerationError(f"KiCad import report contains errors: {report['errors']}")
+    return imported, report
+
+
+SVG_LAYERS = {
+    "board-mask-edge.svg": "F.Mask,Edge.Cuts",
+    "board-silkscreen.svg": "F.SilkS,Edge.Cuts",
+    "board-copper.svg": "F.Cu,Edge.Cuts",
+}
+
+
+def _export_svgs(
+    config: GenerationConfig,
+    runner: Runner,
+    imported: Path,
+    assets_dir: Path,
+    board_data: Mapping[str, object],
+) -> None:
+    board_meta = board_data["board"]
+    if not isinstance(board_meta, Mapping) or not isinstance(board_meta.get("view_box"), Mapping):
+        raise GenerationError("generated board view box is missing")
+    expected_width = float(board_meta["view_box"]["width"])
+    expected_height = float(board_meta["view_box"]["height"])
+    for filename, layers in SVG_LAYERS.items():
+        output = assets_dir / filename
+        command = [
+            str(config.kicad_cli),
+            "pcb",
+            "export",
+            "svg",
+            "--mode-single",
+            "--output",
+            str(output),
+            "--layers",
+            layers,
+            "--page-size-mode",
+            "2",
+            "--fit-page-to-board",
+            "--exclude-drawing-sheet",
+            str(imported),
+        ]
+        _run_checked(runner, command, assets_dir)
+        if not output.is_file():
+            raise GenerationError(f"KiCad SVG export did not create {filename}")
+        width, height = _normalize_svg(output, f"FCB board viewer {filename}")
+        if abs(width - expected_width) > 0.1 or abs(height - expected_height) > 0.1:
+            raise GenerationError(
+                f"SVG viewBox mismatch for {filename}: {width}x{height}, expected {expected_width}x{expected_height}"
+            )
+
+
+def _export_and_validate_ipcd356(
+    config: GenerationConfig,
+    runner: Runner,
+    imported: Path,
+    work: Path,
+    board_data: Mapping[str, object],
+) -> dict[str, object]:
+    output = work / "board.d356"
+    command = [
+        str(config.kicad_cli),
+        "pcb",
+        "export",
+        "ipcd356",
+        "--output",
+        str(output),
+        str(imported),
+    ]
+    _run_checked(runner, command, work)
+    if not output.is_file():
+        raise GenerationError("KiCad IPC-D-356 export did not create board.d356")
+    try:
+        return validate_ipcd356_alignment(board_data, output)
+    except IpCd356AlignmentError as exc:
+        raise GenerationError(f"IPC-D-356 cross-check failed: {exc}") from exc
+
+
+def _asset_metadata(path: Path) -> dict[str, object]:
+    return {"sha256": sha256_file(path), "bytes": path.stat().st_size}
+
+
+def manifest_source_path(path: Path | str, repository_root: Path | str = ROOT) -> str:
+    resolved = Path(path).resolve()
+    repository = Path(repository_root).resolve()
+    try:
+        return resolved.relative_to(repository).as_posix()
+    except ValueError:
+        return str(resolved)
+
+
+def _publish_directory(source: Path, target: Path) -> None:
+    target.parent.mkdir(parents=True, exist_ok=True)
+    suffix = uuid.uuid4().hex
+    staging = target.parent / f".{target.name}.stage-{suffix}"
+    backup = target.parent / f".{target.name}.backup-{suffix}"
+    shutil.copytree(source, staging)
+    validate_generated_assets(staging)
+    moved_old = False
+    try:
+        if target.exists():
+            os.replace(target, backup)
+            moved_old = True
+        os.replace(staging, target)
+    except Exception:
+        if moved_old and backup.exists() and not target.exists():
+            os.replace(backup, target)
+        raise
+    finally:
+        if staging.exists():
+            shutil.rmtree(staging)
+    if backup.exists():
+        shutil.rmtree(backup)
+
+
+def generate_assets(config: GenerationConfig, *, runner: Runner = _default_runner) -> dict[str, object]:
+    temp_parent = _verify_inputs(config)
+    inventory = _load_json(config.inventory_path)
+    annotations = _load_json(config.annotations_path)
+    _validate_schema(annotations, ANNOTATION_SCHEMA, "annotations")
+
+    with tempfile.TemporaryDirectory(prefix="cpld-board-viewer-", dir=temp_parent) as temporary:
+        work = Path(temporary)
+        kicad_version = _verify_kicad_version(config, runner, work)
+        imported, import_report = _import_board(config, runner, work)
+        parsed = parse_kicad_pcb(imported)
+        board_data = build_board_data(
+            parsed,
+            inventory,
+            annotations,
+            board_name=config.board_name,
+        )
+        assets_dir = work / "generated"
+        assets_dir.mkdir()
+        try:
+            prepared_photo = prepare_photo_overlay(
+                annotations.get("photo_overlay"),
+                repository_root=config.photo_root,
+                assets_dir=assets_dir,
+                board_bounds=parsed.bounds,
+            )
+        except PhotoOverlayError as exc:
+            raise GenerationError(f"photo overlay validation failed: {exc}") from exc
+        board_data["photo_overlay"] = prepared_photo.data if prepared_photo else None
+        _validate_counts(board_data, config)
+        if config.product_regression:
+            try:
+                validate_product_regression(board_data)
+            except BoardRegressionError as exc:
+                raise GenerationError(f"product board regression failed: {exc}") from exc
+        _validate_schema(board_data, DATA_SCHEMA, "board data")
+        ipcd356_verification = _export_and_validate_ipcd356(
+            config,
+            runner,
+            imported,
+            work,
+            board_data,
+        )
+
+        _write_json(assets_dir / "board-data.json", board_data)
+        _write_json(assets_dir / "import-report.json", import_report)
+        _export_svgs(config, runner, imported, assets_dir, board_data)
+
+        asset_names = ["board-data.json", *SVG_LAYERS, "import-report.json"]
+        if prepared_photo:
+            asset_names.append(prepared_photo.asset_path.name)
+        counts = board_data["counts"]
+        sources = {
+            "brd": {"path": manifest_source_path(config.brd_path), "sha256": sha256_file(config.brd_path)},
+            "inventory": {
+                "path": manifest_source_path(config.inventory_path),
+                "sha256": sha256_file(config.inventory_path),
+            },
+            "annotations": {
+                "path": manifest_source_path(config.annotations_path),
+                "sha256": sha256_file(config.annotations_path),
+            },
+            **{
+                name: {"path": manifest_source_path(path), "sha256": sha256_file(path)}
+                for name, path in GENERATOR_SOURCE_PATHS.items()
+            },
+        }
+        if prepared_photo:
+            sources["photo"] = {
+                "path": manifest_source_path(prepared_photo.source_path),
+                "sha256": sha256_file(prepared_photo.source_path),
+            }
+        build_info = {
+            "schema": "board-viewer-build-info-v1",
+            "generated_at": datetime.now(UTC).isoformat().replace("+00:00", "Z"),
+            "generator_version": GENERATOR_VERSION,
+            "toolchain": {"python": platform.python_version(), "kicad": kicad_version},
+            "sources": sources,
+            "assets": {name: _asset_metadata(assets_dir / name) for name in asset_names},
+            "verification": {"ipcd356": ipcd356_verification},
+            "counts": {
+                "footprints": counts["footprints"],
+                "touchpoints": counts["touchpoints"],
+                "pads": counts["pads"],
+            },
+        }
+        _write_json(assets_dir / "build-info.json", build_info)
+        validate_generated_assets(assets_dir)
+        try:
+            _publish_directory(assets_dir, config.output_dir)
+        except OSError as exc:
+            raise GenerationError(f"cannot publish generated assets: {exc}") from exc
+
+    return {"status": "pass", "output_dir": str(config.output_dir), "build_info": build_info}

+ 143 - 0
tools/board-viewer/board_viewer/ipcd356.py

@@ -0,0 +1,143 @@
+"""Cross-check generated touchpoint pads against KiCad's IPC-D-356 export."""
+
+from __future__ import annotations
+
+import math
+import re
+from collections import Counter, defaultdict
+from collections.abc import Mapping
+from dataclasses import dataclass
+from pathlib import Path
+
+
+COORDINATE = re.compile(r"X([+-]\d{6})Y([+-]\d{6})")
+UNIT_MM = 0.00254
+DEFAULT_TOLERANCE_MM = 0.02
+
+
+class IpCd356AlignmentError(ValueError):
+    """Raised when generated numbered pads do not align with IPC-D-356."""
+
+
+@dataclass(frozen=True)
+class _Record:
+    record_type: str
+    net: str | None
+    x: float
+    y: float
+
+
+def _normalized_net(value: object) -> str | None:
+    text = str(value or "").strip().upper()
+    return None if text in {"", "N/C"} else text
+
+
+def _records(path: Path) -> list[_Record]:
+    try:
+        lines = path.read_text(encoding="ascii").splitlines()
+    except OSError as exc:
+        raise IpCd356AlignmentError(f"cannot read IPC-D-356 {path}: {exc}") from exc
+
+    records: list[_Record] = []
+    for line in lines:
+        record_type = line[:3]
+        if record_type not in {"317", "327"} or line[17:31].strip() == "VIA":
+            continue
+        match = COORDINATE.search(line)
+        if match is None:
+            continue
+        records.append(
+            _Record(
+                record_type=record_type,
+                net=_normalized_net(line[3:17]),
+                x=int(match.group(1)) * UNIT_MM,
+                y=-int(match.group(2)) * UNIT_MM,
+            )
+        )
+    if not records:
+        raise IpCd356AlignmentError("IPC-D-356 contains no component pad records")
+    return records
+
+
+def _numbered_pads(board_data: Mapping[str, object]) -> list[tuple[str, str, str | None, float, float]]:
+    result: list[tuple[str, str, str | None, float, float]] = []
+    touchpoints = board_data.get("touchpoints", [])
+    if not isinstance(touchpoints, list):
+        return result
+    for touchpoint in touchpoints:
+        if not isinstance(touchpoint, Mapping):
+            continue
+        reference = str(touchpoint.get("reference") or "")
+        pins = touchpoint.get("pins", [])
+        if not isinstance(pins, list):
+            continue
+        for pin in pins:
+            if not isinstance(pin, Mapping) or not str(pin.get("number") or ""):
+                continue
+            position = pin.get("position")
+            if not isinstance(position, Mapping):
+                continue
+            result.append(
+                (
+                    reference,
+                    str(pin.get("number")),
+                    _normalized_net(pin.get("net")),
+                    float(position.get("x", 0.0)),
+                    float(position.get("y", 0.0)),
+                )
+            )
+    return result
+
+
+def validate_ipcd356_alignment(
+    board_data: Mapping[str, object],
+    path: Path | str,
+    *,
+    tolerance_mm: float = DEFAULT_TOLERANCE_MM,
+) -> dict[str, object]:
+    if tolerance_mm <= 0:
+        raise ValueError("tolerance_mm must be positive")
+    records = _records(Path(path))
+    pads = _numbered_pads(board_data)
+    bucket_size = tolerance_mm
+    buckets: dict[tuple[int, int], list[int]] = defaultdict(list)
+    for index, record in enumerate(records):
+        buckets[(round(record.x / bucket_size), round(record.y / bucket_size))].append(index)
+
+    used: set[int] = set()
+    failures: list[str] = []
+    matched_types: Counter[str] = Counter()
+    for reference, number, net, x, y in pads:
+        center = (round(x / bucket_size), round(y / bucket_size))
+        candidates: list[tuple[float, int, _Record]] = []
+        for offset_x in (-1, 0, 1):
+            for offset_y in (-1, 0, 1):
+                for index in buckets.get((center[0] + offset_x, center[1] + offset_y), []):
+                    if index in used:
+                        continue
+                    record = records[index]
+                    distance = math.hypot(x - record.x, y - record.y)
+                    if distance <= tolerance_mm:
+                        candidates.append((distance, index, record))
+        net_matches = [item for item in candidates if item[2].net == net]
+        if not net_matches:
+            nearby_nets = sorted({item[2].net or "N/C" for item in candidates})
+            failures.append(
+                f"{reference}.{number} at {x:.4f},{y:.4f} net={net or 'N/C'} nearby={nearby_nets}"
+            )
+            continue
+        _, index, record = min(net_matches, key=lambda item: item[0])
+        used.add(index)
+        matched_types[record.record_type] += 1
+
+    if failures:
+        detail = "; ".join(failures[:10])
+        raise IpCd356AlignmentError(
+            f"D356 alignment failed for {len(failures)}/{len(pads)} numbered pads: {detail}"
+        )
+    return {
+        "numbered_pads": len(pads),
+        "matched_pads": len(pads),
+        "record_types": {record_type: matched_types.get(record_type, 0) for record_type in ("317", "327")},
+        "tolerance_mm": tolerance_mm,
+    }

+ 391 - 0
tools/board-viewer/board_viewer/pcb.py

@@ -0,0 +1,391 @@
+"""Extract footprint and pad metadata from a KiCad PCB."""
+
+from __future__ import annotations
+
+import math
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import TextIO
+
+from .sexpr import SExpr, iter_root_forms
+
+
+TOUCHPOINT_REFERENCE = re.compile(r"^(?:CON|J|PL|TP)\d+$")
+
+
+def _head(form: list[SExpr]) -> str:
+    return str(form[0]) if form and isinstance(form[0], str) else ""
+
+
+def _children(form: list[SExpr], name: str) -> list[list[SExpr]]:
+    return [item for item in form[1:] if isinstance(item, list) and _head(item) == name]
+
+
+def _child(form: list[SExpr], name: str) -> list[SExpr] | None:
+    return next(iter(_children(form, name)), None)
+
+
+def _float(value: SExpr | None, default: float = 0.0) -> float:
+    try:
+        return float(str(value))
+    except (TypeError, ValueError):
+        return default
+
+
+def _values(form: list[SExpr] | None) -> list[str]:
+    if form is None:
+        return []
+    return [str(item) for item in form[1:] if isinstance(item, str)]
+
+
+def _xy_angle(form: list[SExpr] | None) -> tuple[float, float, float]:
+    values = _values(form)
+    return (
+        _float(values[0]) if values else 0.0,
+        _float(values[1]) if len(values) > 1 else 0.0,
+        _float(values[2]) if len(values) > 2 else 0.0,
+    )
+
+
+def _normalize_angle(value: float) -> float:
+    result = value % 360
+    return 0.0 if math.isclose(result, 360.0) else result
+
+
+def _transform_point(
+    local_x: float,
+    local_y: float,
+    origin_x: float,
+    origin_y: float,
+    rotation: float,
+) -> tuple[float, float]:
+    radians = math.radians(-rotation)
+    cosine, sine = math.cos(radians), math.sin(radians)
+    return (
+        origin_x + local_x * cosine - local_y * sine,
+        origin_y + local_x * sine + local_y * cosine,
+    )
+
+
+@dataclass(frozen=True)
+class Pad:
+    number: str
+    pad_type: str
+    shape: str
+    x: float
+    y: float
+    width: float
+    height: float
+    rotation: float
+    net: str | None
+    layers: tuple[str, ...]
+    drill_width: float
+    drill_height: float
+    mechanical: bool
+    electrical: bool
+
+
+@dataclass
+class Footprint:
+    reference: str
+    component_value: str
+    x: float
+    y: float
+    rotation: float
+    side: str
+    layer: str
+    pads: list[Pad] = field(default_factory=list)
+    bounds: dict[str, float] = field(default_factory=dict)
+
+    def pad_by_number(self, number: str) -> Pad:
+        for pad in self.pads:
+            if pad.number == str(number):
+                return pad
+        raise KeyError(f"unknown pad {self.reference}.{number}")
+
+
+@dataclass
+class ParsedBoard:
+    footprints: list[Footprint]
+    footprint_count: int
+    bounds: dict[str, float]
+
+    def footprint_by_reference(self, reference: str) -> Footprint:
+        for footprint in self.footprints:
+            if footprint.reference == reference:
+                return footprint
+        raise KeyError(f"unknown footprint {reference}")
+
+
+def _reference(form: list[SExpr]) -> str | None:
+    for prop in _children(form, "property"):
+        values = _values(prop)
+        if len(values) < 2 or values[0] != "Reference":
+            continue
+        reference = values[1].strip()
+        if reference and reference != "${REFERENCE}":
+            return reference
+    for text in _children(form, "fp_text"):
+        values = _values(text)
+        if len(values) >= 2 and values[0] == "reference" and values[1] != "${REFERENCE}":
+            return values[1]
+    return None
+
+
+def _component_value(form: list[SExpr]) -> str:
+    properties: dict[str, str] = {}
+    for prop in _children(form, "property"):
+        values = _values(prop)
+        if len(values) >= 2 and values[1] and values[1] != "${REFERENCE}":
+            properties.setdefault(values[0], values[1].strip())
+    for name in ("Component Value", "Value"):
+        if properties.get(name):
+            return properties[name]
+    if len(form) > 1 and isinstance(form[1], str):
+        return form[1].strip()
+    return ""
+
+
+def _drill_size(form: list[SExpr]) -> tuple[float, float]:
+    drill = _child(form, "drill")
+    if drill is None:
+        return 0.0, 0.0
+    numeric: list[float] = []
+    for value in _values(drill):
+        try:
+            numeric.append(float(value))
+        except ValueError:
+            continue
+    if not numeric:
+        return 0.0, 0.0
+    return numeric[0], numeric[1] if len(numeric) > 1 else numeric[0]
+
+
+def _parse_pad(
+    form: list[SExpr],
+    origin_x: float,
+    origin_y: float,
+    footprint_rotation: float,
+) -> Pad:
+    values = _values(form)
+    number = values[0] if values else ""
+    pad_type = values[1] if len(values) > 1 else "unknown"
+    shape = values[2] if len(values) > 2 else "unknown"
+    local_x, local_y, local_rotation = _xy_angle(_child(form, "at"))
+    x, y = _transform_point(
+        local_x,
+        local_y,
+        origin_x,
+        origin_y,
+        footprint_rotation,
+    )
+    size = _values(_child(form, "size"))
+    width = _float(size[0]) if size else 0.0
+    height = _float(size[1]) if len(size) > 1 else width
+    drill_width, drill_height = _drill_size(form)
+    net_values = _values(_child(form, "net"))
+    net = net_values[-1] if net_values else None
+    layers = tuple(_values(_child(form, "layers")))
+    mechanical = pad_type == "np_thru_hole" or not number
+    rotation = local_rotation
+    return Pad(
+        number=number,
+        pad_type=pad_type,
+        shape=shape,
+        x=x,
+        y=y,
+        width=width,
+        height=height,
+        rotation=_normalize_angle(rotation),
+        net=net,
+        layers=layers,
+        drill_width=drill_width,
+        drill_height=drill_height,
+        mechanical=mechanical,
+        electrical=not mechanical,
+    )
+
+
+def _pad_bounds(pad: Pad) -> tuple[float, float, float, float]:
+    width = max(pad.width, pad.drill_width, 0.5)
+    height = max(pad.height, pad.drill_height, 0.5)
+    radians = math.radians(pad.rotation)
+    cosine, sine = abs(math.cos(radians)), abs(math.sin(radians))
+    half_width = (width * cosine + height * sine) / 2
+    half_height = (width * sine + height * cosine) / 2
+    return (
+        pad.x - half_width,
+        pad.y - half_height,
+        pad.x + half_width,
+        pad.y + half_height,
+    )
+
+
+def _footprint_bounds(pads: list[Pad], origin_x: float, origin_y: float) -> dict[str, float]:
+    extents = [_pad_bounds(pad) for pad in pads]
+    if not extents:
+        extents = [(origin_x - 0.5, origin_y - 0.5, origin_x + 0.5, origin_y + 0.5)]
+    minimum_x = min(item[0] for item in extents)
+    minimum_y = min(item[1] for item in extents)
+    maximum_x = max(item[2] for item in extents)
+    maximum_y = max(item[3] for item in extents)
+    return {
+        "x": minimum_x,
+        "y": minimum_y,
+        "width": maximum_x - minimum_x,
+        "height": maximum_y - minimum_y,
+    }
+
+
+def _parse_footprint(form: list[SExpr]) -> Footprint | None:
+    reference = _reference(form)
+    if not reference:
+        return None
+    layer_values = _values(_child(form, "layer"))
+    layer = layer_values[0] if layer_values else ""
+    side = "back" if layer.startswith("B.") else "front"
+    x, y, rotation = _xy_angle(_child(form, "at"))
+    pads = [
+        _parse_pad(pad, x, y, rotation)
+        for pad in _children(form, "pad")
+    ]
+    return Footprint(
+        reference=reference,
+        component_value=_component_value(form),
+        x=x,
+        y=y,
+        rotation=_normalize_angle(rotation),
+        side=side,
+        layer=layer,
+        pads=pads,
+        bounds=_footprint_bounds(pads, x, y),
+    )
+
+
+def _point(form: list[SExpr] | None) -> tuple[float, float]:
+    values = _values(form)
+    return (
+        _float(values[0]) if values else 0.0,
+        _float(values[1]) if len(values) > 1 else 0.0,
+    )
+
+
+def _arc_points(form: list[SExpr]) -> list[tuple[float, float]]:
+    start = _point(_child(form, "start"))
+    middle = _point(_child(form, "mid"))
+    end = _point(_child(form, "end"))
+    points = [start, middle, end]
+    determinant = 2 * (
+        start[0] * (middle[1] - end[1])
+        + middle[0] * (end[1] - start[1])
+        + end[0] * (start[1] - middle[1])
+    )
+    if math.isclose(determinant, 0.0, abs_tol=1e-12):
+        return points
+    start_sq = start[0] ** 2 + start[1] ** 2
+    middle_sq = middle[0] ** 2 + middle[1] ** 2
+    end_sq = end[0] ** 2 + end[1] ** 2
+    center_x = (
+        start_sq * (middle[1] - end[1])
+        + middle_sq * (end[1] - start[1])
+        + end_sq * (start[1] - middle[1])
+    ) / determinant
+    center_y = (
+        start_sq * (end[0] - middle[0])
+        + middle_sq * (start[0] - end[0])
+        + end_sq * (middle[0] - start[0])
+    ) / determinant
+    radius = math.hypot(start[0] - center_x, start[1] - center_y)
+    tau = math.tau
+    start_angle = math.atan2(start[1] - center_y, start[0] - center_x) % tau
+    middle_angle = math.atan2(middle[1] - center_y, middle[0] - center_x) % tau
+    end_angle = math.atan2(end[1] - center_y, end[0] - center_x) % tau
+    ccw_span = (end_angle - start_angle) % tau
+    middle_ccw = (middle_angle - start_angle) % tau
+    counter_clockwise = middle_ccw <= ccw_span + 1e-9
+
+    def included(angle: float) -> bool:
+        if counter_clockwise:
+            return (angle - start_angle) % tau <= ccw_span + 1e-9
+        clockwise_span = (start_angle - end_angle) % tau
+        return (start_angle - angle) % tau <= clockwise_span + 1e-9
+
+    for angle in (0.0, math.pi / 2, math.pi, 3 * math.pi / 2):
+        if included(angle):
+            points.append((center_x + radius * math.cos(angle), center_y + radius * math.sin(angle)))
+    return points
+
+
+def _edge_points(form: list[SExpr]) -> list[tuple[float, float]]:
+    layer = _values(_child(form, "layer"))
+    if not layer or layer[0] != "Edge.Cuts":
+        return []
+    kind = _head(form)
+    if kind == "gr_line":
+        return [_point(_child(form, "start")), _point(_child(form, "end"))]
+    if kind == "gr_rect":
+        start = _point(_child(form, "start"))
+        end = _point(_child(form, "end"))
+        return [start, end, (start[0], end[1]), (end[0], start[1])]
+    if kind == "gr_circle":
+        center = _point(_child(form, "center"))
+        end = _point(_child(form, "end"))
+        radius = math.hypot(end[0] - center[0], end[1] - center[1])
+        return [
+            (center[0] - radius, center[1]),
+            (center[0] + radius, center[1]),
+            (center[0], center[1] - radius),
+            (center[0], center[1] + radius),
+        ]
+    if kind == "gr_arc":
+        return _arc_points(form)
+    if kind in {"gr_poly", "gr_curve"}:
+        points_form = _child(form, "pts")
+        return [_point(item) for item in _children(points_form or [], "xy")]
+    return []
+
+
+def _board_bounds(edge_points: list[tuple[float, float]], footprints: list[Footprint]) -> dict[str, float]:
+    if edge_points:
+        minimum_x = min(point[0] for point in edge_points)
+        minimum_y = min(point[1] for point in edge_points)
+        maximum_x = max(point[0] for point in edge_points)
+        maximum_y = max(point[1] for point in edge_points)
+    elif footprints:
+        minimum_x = min(item.bounds["x"] for item in footprints)
+        minimum_y = min(item.bounds["y"] for item in footprints)
+        maximum_x = max(item.bounds["x"] + item.bounds["width"] for item in footprints)
+        maximum_y = max(item.bounds["y"] + item.bounds["height"] for item in footprints)
+    else:
+        minimum_x = minimum_y = maximum_x = maximum_y = 0.0
+    return {
+        "x": minimum_x,
+        "y": minimum_y,
+        "width": maximum_x - minimum_x,
+        "height": maximum_y - minimum_y,
+    }
+
+
+def parse_kicad_pcb(source: Path | str | TextIO) -> ParsedBoard:
+    footprints: list[Footprint] = []
+    footprint_count = 0
+    edge_points: list[tuple[float, float]] = []
+    for form in iter_root_forms(source):
+        kind = _head(form)
+        if kind != "footprint":
+            edge_points.extend(_edge_points(form))
+            continue
+        footprint_count += 1
+        footprint = _parse_footprint(form)
+        if footprint is not None:
+            footprints.append(footprint)
+    return ParsedBoard(
+        footprints=footprints,
+        footprint_count=footprint_count,
+        bounds=_board_bounds(edge_points, footprints),
+    )
+
+
+def select_touchpoints(board: ParsedBoard) -> list[Footprint]:
+    return [footprint for footprint in board.footprints if TOUCHPOINT_REFERENCE.fullmatch(footprint.reference)]

+ 135 - 0
tools/board-viewer/board_viewer/photo.py

@@ -0,0 +1,135 @@
+"""Optional, hash-bound affine board-photo overlay preparation."""
+
+from __future__ import annotations
+
+import shutil
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from pathlib import Path
+
+from .assets import sha256_file
+
+
+class PhotoOverlayError(RuntimeError):
+    """Raised when optional photo calibration cannot be trusted."""
+
+
+@dataclass(frozen=True)
+class PreparedPhotoOverlay:
+    data: dict[str, object]
+    source_path: Path
+    asset_path: Path
+
+
+def _point(item: Mapping[str, object], name: str) -> tuple[float, float]:
+    value = item.get(name)
+    if not isinstance(value, Mapping):
+        raise PhotoOverlayError(f"control point {name} must be an object")
+    try:
+        return float(value["x"]), float(value["y"])
+    except (KeyError, TypeError, ValueError) as exc:
+        raise PhotoOverlayError(f"control point {name} must contain numeric x/y") from exc
+
+
+def _has_non_collinear(points: Sequence[tuple[float, float]]) -> bool:
+    for first in range(len(points) - 2):
+        for second in range(first + 1, len(points) - 1):
+            for third in range(second + 1, len(points)):
+                a, b, c = points[first], points[second], points[third]
+                area2 = (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
+                if abs(area2) > 1e-9:
+                    return True
+    return False
+
+
+def _solve_three_by_three(matrix: list[list[float]], values: list[float]) -> list[float]:
+    augmented = [row[:] + [value] for row, value in zip(matrix, values, strict=True)]
+    for column in range(3):
+        pivot = max(range(column, 3), key=lambda row: abs(augmented[row][column]))
+        if abs(augmented[pivot][column]) <= 1e-12:
+            raise PhotoOverlayError("control points must include non-collinear coordinates")
+        augmented[column], augmented[pivot] = augmented[pivot], augmented[column]
+        divisor = augmented[column][column]
+        augmented[column] = [value / divisor for value in augmented[column]]
+        for row in range(3):
+            if row == column:
+                continue
+            factor = augmented[row][column]
+            augmented[row] = [
+                value - factor * pivot_value
+                for value, pivot_value in zip(augmented[row], augmented[column], strict=True)
+            ]
+    return [augmented[row][3] for row in range(3)]
+
+
+def solve_affine_matrix(
+    control_points: Sequence[Mapping[str, object]], *, board_bounds: Mapping[str, float]
+) -> list[float]:
+    if len(control_points) < 3:
+        raise PhotoOverlayError("photo overlay requires at least three control points")
+    image_points = [_point(item, "image") for item in control_points]
+    board_points = [_point(item, "board") for item in control_points]
+    if not _has_non_collinear(image_points) or not _has_non_collinear(board_points):
+        raise PhotoOverlayError("control points must include non-collinear coordinates")
+
+    rows = [[x, y, 1.0] for x, y in image_points]
+    normal = [
+        [sum(row[left] * row[right] for row in rows) for right in range(3)]
+        for left in range(3)
+    ]
+    target_x = [point[0] - float(board_bounds["x"]) for point in board_points]
+    target_y = [point[1] - float(board_bounds["y"]) for point in board_points]
+    normal_x = [sum(row[column] * value for row, value in zip(rows, target_x, strict=True)) for column in range(3)]
+    normal_y = [sum(row[column] * value for row, value in zip(rows, target_y, strict=True)) for column in range(3)]
+    x_coefficients = _solve_three_by_three(normal, normal_x)
+    y_coefficients = _solve_three_by_three(normal, normal_y)
+    return [
+        x_coefficients[0],
+        y_coefficients[0],
+        x_coefficients[1],
+        y_coefficients[1],
+        x_coefficients[2],
+        y_coefficients[2],
+    ]
+
+
+def prepare_photo_overlay(
+    configuration: Mapping[str, object] | None,
+    *,
+    repository_root: Path | str,
+    assets_dir: Path | str,
+    board_bounds: Mapping[str, float],
+) -> PreparedPhotoOverlay | None:
+    if configuration is None:
+        return None
+    repository = Path(repository_root).resolve()
+    source = (repository / str(configuration.get("path") or "")).resolve()
+    try:
+        source.relative_to(repository)
+    except ValueError as exc:
+        raise PhotoOverlayError("photo overlay path must stay inside repository") from exc
+    if not source.is_file():
+        raise PhotoOverlayError(f"photo overlay source is missing: {source}")
+    expected_hash = str(configuration.get("sha256") or "")
+    actual_hash = sha256_file(source)
+    if actual_hash != expected_hash:
+        raise PhotoOverlayError(f"photo overlay SHA-256 mismatch: expected {expected_hash}, got {actual_hash}")
+    suffix = source.suffix.lower()
+    if suffix not in {".png", ".jpg", ".jpeg", ".webp"}:
+        raise PhotoOverlayError(f"unsupported photo overlay format: {suffix}")
+    control_points = configuration.get("control_points")
+    if not isinstance(control_points, list):
+        raise PhotoOverlayError("photo overlay control_points must be an array")
+    matrix = solve_affine_matrix(control_points, board_bounds=board_bounds)
+    asset_path = Path(assets_dir) / f"board-photo{suffix}"
+    shutil.copy2(source, asset_path)
+    return PreparedPhotoOverlay(
+        data={
+            "asset": asset_path.name,
+            "sha256": actual_hash,
+            "matrix": matrix,
+            "control_point_count": len(control_points),
+        },
+        source_path=source,
+        asset_path=asset_path,
+    )

+ 573 - 0
tools/board-viewer/board_viewer/regression.py

@@ -0,0 +1,573 @@
+"""Product-specific regression checks for the current FCB board."""
+
+from __future__ import annotations
+
+from collections import Counter
+from collections.abc import Mapping
+
+
+class BoardRegressionError(RuntimeError):
+    """Raised when generated board facts drift from the reviewed board."""
+
+
+EXPECTED_COUNTS = {
+    "footprints": 1052,
+    "touchpoints": 110,
+    "pads": 472,
+    "connector_contacts": 288,
+    "connector_auxiliary_pads": 116,
+}
+EXPECTED_CATEGORIES = {"CON": 62, "J": 16, "PL": 3, "TP": 29}
+FOUR_CONTACT_REFS = {
+    "CON12", "CON30", "CON31", "CON32", "CON33", "CON34", "CON35", "CON36",
+    "CON37", "CON38", "CON39", "CON40", "CON54", "CON58", "CON59", "CON60",
+    "CON61", "CON62", "CON63", "CON64", "CON65", "CON66", "CON67", "CON68",
+    "CON69", "CON70", "CON77", "CON78",
+}
+THREE_CONTACT_REFS = {
+    "CON53", "CON55", "CON56", "CON57", "CON79", "CON80", "CON81", "CON82",
+    "CON83", "CON84", "CON85", "CON86", "CON87", "CON88", "CON89", "CON90",
+    "CON91", "CON92", "CON93", "CON94", "CON95", "CON96", "CON97", "CON98",
+}
+FOURTEEN_CONTACT_REFS = {"CON18", "CON27", "CON28", "CON29"}
+POWER_CONTACT_REFS = {"CON2", "CON23"}
+FAN_CONTACT_REFS = {"CON8", "CON24", "CON25", "CON26"}
+EXPECTED_CONNECTOR_REFERENCES = (
+    FOUR_CONTACT_REFS
+    | THREE_CONTACT_REFS
+    | FOURTEEN_CONTACT_REFS
+    | POWER_CONTACT_REFS
+    | FAN_CONTACT_REFS
+)
+
+
+def _category(reference: str) -> str:
+    return next((prefix for prefix in ("CON", "J", "PL", "TP") if reference.startswith(prefix)), "OTHER")
+
+
+def _pin_index(touchpoint: Mapping[str, object]) -> dict[str, Mapping[str, object]]:
+    pins = touchpoint.get("pins", [])
+    return {
+        str(pin.get("number")): pin
+        for pin in pins
+        if isinstance(pin, Mapping) and pin.get("number") is not None
+    }
+
+
+def _validate_recommendable_pins(touchpoints: list[Mapping[str, object]]) -> None:
+    for touchpoint in touchpoints:
+        for pin in touchpoint.get("pins", []):
+            if not isinstance(pin, Mapping):
+                continue
+            recommendation = pin.get("recommendation")
+            if not isinstance(recommendation, Mapping) or recommendation.get("eligible") is not True:
+                continue
+            fpga = pin.get("fpga")
+            valid = (
+                pin.get("evidence_tier") == "cross_verified"
+                and isinstance(fpga, Mapping)
+                and fpga.get("evidence_tier") == "cross_verified"
+                and bool(fpga.get("ball"))
+                and pin.get("electrical") is True
+                and pin.get("mechanical") is not True
+                and pin.get("pad_role") == "contact"
+                and pin.get("reserved") is not True
+                and pin.get("fixed_load_conflict") is not True
+                and pin.get("function_category") not in {"power", "ground"}
+                and str(pin.get("net") or "").upper() not in {"GND", "AGND", "DGND", "PGND"}
+                and pin.get("external_level") not in {None, "", "unknown"}
+            )
+            if not valid:
+                raise BoardRegressionError(
+                    f"recommendable pin violates contract: {touchpoint.get('reference')}.{pin.get('number')}"
+                )
+
+
+def _expected_connector_contract(reference: str) -> tuple[str, list[list[str]], set[str], int]:
+    if reference in FOUR_CONTACT_REFS:
+        order = ["1", "2", "3", "4"] if reference in {"CON54", "CON77", "CON78"} else ["4", "3", "2", "1"]
+        return "CON_11251W00_NPX_SX_4P", [[number] for number in order], {"5", "6"}, 0
+    if reference in THREE_CONTACT_REFS:
+        return "CON_51541_003_P1D25", [["3", "2", "1"]], {"4", "5"}, 0
+    if reference in FOURTEEN_CONTACT_REFS:
+        return (
+            "CON_3110_14P_P2D54",
+            [
+                ["13", "11", "9", "7", "5", "3", "1"],
+                ["14", "12", "10", "8", "6", "4", "2"],
+            ],
+            set(),
+            0,
+        )
+    if reference == "CON23":
+        return "CON_C22930_1084N_X", [["5", "1"], ["6", "2"], ["7", "3"], ["8", "4"]], {"9", "10"}, 2
+    if reference == "CON2":
+        return "CON_C22930_1084N_X", [["4", "8"], ["3", "7"], ["2", "6"], ["1", "5"]], {"9", "10"}, 2
+    if reference in FAN_CONTACT_REFS:
+        return "CON_PZGM_B03_08P", [[str(number)] for number in range(8, 0, -1)], set(), 1
+    raise BoardRegressionError(f"missing connector regression contract for {reference}")
+
+
+def _validate_connector_contracts(by_reference: Mapping[str, Mapping[str, object]]) -> None:
+    actual_references = {reference for reference in by_reference if reference.startswith("CON")}
+    if actual_references != EXPECTED_CONNECTOR_REFERENCES:
+        missing = sorted(EXPECTED_CONNECTOR_REFERENCES.difference(actual_references))
+        extra = sorted(actual_references.difference(EXPECTED_CONNECTOR_REFERENCES))
+        raise BoardRegressionError(f"connector reference set drifted; missing={missing} extra={extra}")
+
+    for reference in sorted(EXPECTED_CONNECTOR_REFERENCES):
+        touchpoint = by_reference[reference]
+        connector = touchpoint.get("connector")
+        if not isinstance(connector, Mapping):
+            raise BoardRegressionError(f"{reference} connector contract missing")
+        profile, grid, shield_numbers, mechanical_count = _expected_connector_contract(reference)
+        order = [number for row in grid for number in row]
+        if connector.get("review_status") != "cross_verified":
+            raise BoardRegressionError(f"{reference} connector layout is not cross-verified")
+        if connector.get("profile") != profile:
+            raise BoardRegressionError(f"{reference} profile={connector.get('profile')} expected {profile}")
+        if connector.get("view") != "board_front":
+            raise BoardRegressionError(f"{reference} connector view must be board_front")
+        if connector.get("contact_grid") != grid or connector.get("contact_order") != order:
+            raise BoardRegressionError(f"{reference} contact order or grid drifted")
+        expected_columns = len(grid[0]) if grid else 0
+        expected_auxiliary = len(shield_numbers) + mechanical_count
+        if (
+            connector.get("contact_count") != len(order)
+            or connector.get("auxiliary_pad_count") != expected_auxiliary
+            or connector.get("rows") != len(grid)
+            or connector.get("columns") != expected_columns
+        ):
+            raise BoardRegressionError(f"{reference} connector dimensions or pad counts drifted")
+
+        raw_pins = touchpoint.get("pins", [])
+        pins = [pin for pin in raw_pins if isinstance(pin, Mapping)] if isinstance(raw_pins, list) else []
+        pin_ids = [str(pin.get("id") or "") for pin in pins]
+        if not all(pin_ids) or len(pin_ids) != len(set(pin_ids)):
+            raise BoardRegressionError(f"{reference} pin ids are missing or duplicated")
+        numbered = _pin_index(touchpoint)
+        for board_order, number in enumerate(order, start=1):
+            pin = numbered.get(number)
+            if pin is None or pin.get("pad_role") != "contact":
+                raise BoardRegressionError(f"{reference}.{number} contact pin role drifted")
+            row = next(index for index, values in enumerate(grid, start=1) if number in values)
+            column = grid[row - 1].index(number) + 1
+            if (
+                pin.get("board_order") != board_order
+                or pin.get("row") != row
+                or pin.get("column") != column
+            ):
+                raise BoardRegressionError(f"{reference}.{number} board-front position drifted")
+        actual_shields = {
+            str(pin.get("number")) for pin in pins if pin.get("pad_role") == "shield"
+        }
+        if actual_shields != shield_numbers:
+            raise BoardRegressionError(f"{reference} shield pad classification drifted")
+        actual_mechanical = sum(pin.get("pad_role") == "mechanical" for pin in pins)
+        if actual_mechanical != mechanical_count:
+            raise BoardRegressionError(f"{reference} mechanical pad classification drifted")
+        if any(pin.get("pad_role") == "unknown" for pin in pins):
+            raise BoardRegressionError(f"{reference} contains an unknown pad role")
+
+
+def _validate_j3_jtag(by_reference: Mapping[str, Mapping[str, object]]) -> None:
+    touchpoint = by_reference.get("J3")
+    if not isinstance(touchpoint, Mapping):
+        raise BoardRegressionError("J3 FPGA JTAG header missing")
+    if "FPGA JTAG" not in str(touchpoint.get("summary") or ""):
+        raise BoardRegressionError("J3 FPGA JTAG purpose missing")
+
+    connector = touchpoint.get("connector")
+    grid = [["6", "1"], ["7", "2"], ["8", "3"], ["9", "4"], ["10", "5"]]
+    order = [number for row in grid for number in row]
+    if not isinstance(connector, Mapping):
+        raise BoardRegressionError("J3 connector layout missing")
+    if (
+        connector.get("profile") != "J3_FPGA_JTAG_2X5"
+        or connector.get("review_status") != "cross_verified"
+        or connector.get("view") != "board_front"
+        or connector.get("contact_grid") != grid
+        or connector.get("contact_order") != order
+        or connector.get("contact_count") != 10
+        or connector.get("auxiliary_pad_count") != 0
+        or connector.get("rows") != 5
+        or connector.get("columns") != 2
+    ):
+        raise BoardRegressionError("J3 board-front contact grid drifted")
+
+    pins = _pin_index(touchpoint)
+    expected_nets = {
+        "1": "N9532014",
+        "2": "GND",
+        "3": "N9532092",
+        "4": "N9532034",
+        "5": "N9532142",
+        "6": "Net_649",
+        "7": "Net_650",
+        "8": "Net_648",
+        "9": "N9532240",
+        "10": "GND",
+    }
+    if set(pins) != set(expected_nets):
+        raise BoardRegressionError("J3 pin set drifted")
+    for board_order, number in enumerate(order, start=1):
+        pin = pins[number]
+        row = next(index for index, values in enumerate(grid, start=1) if number in values)
+        column = grid[row - 1].index(number) + 1
+        if (
+            pin.get("net") != expected_nets[number]
+            or pin.get("pad_role") != "contact"
+            or pin.get("board_order") != board_order
+            or pin.get("row") != row
+            or pin.get("column") != column
+        ):
+            raise BoardRegressionError(f"J3.{number} net or board-front position drifted")
+
+    signal_specs = {
+        "1": ("FPGA_TCK", "A7", "input", "jtag_tck", "R63"),
+        "3": ("FPGA_TDO", "C6", "output", "jtag_tdo", "R65"),
+        "5": ("FPGA_TMS", "B8", "input", "jtag_tms", "R67"),
+        "9": ("FPGA_TDI", "A6", "input", "jtag_tdi", "R69"),
+    }
+    for number, (signal, ball, direction, category, series_resistor) in signal_specs.items():
+        pin = pins[number]
+        fpga = pin.get("fpga")
+        programming = pin.get("programming")
+        path_text = " ".join(str(value) for value in pin.get("path", []))
+        programming_text = " ".join(
+            str(value)
+            for value in (
+                programming.get("conclusion", "") if isinstance(programming, Mapping) else "",
+                programming.get("network_explanation", "") if isinstance(programming, Mapping) else "",
+                programming.get("hdl_guidance", "") if isinstance(programming, Mapping) else "",
+                *(programming.get("connection_guidance", []) if isinstance(programming, Mapping) else []),
+                *(programming.get("risks", []) if isinstance(programming, Mapping) else []),
+            )
+        )
+        if (
+            pin.get("direction") != direction
+            or pin.get("function_category") != category
+            or pin.get("reserved") is not True
+            or pin.get("evidence_tier") != "cross_verified"
+            or not isinstance(fpga, Mapping)
+            or fpga.get("ball") != ball
+            or fpga.get("board_signal") != signal
+            or fpga.get("evidence_tier") != "cross_verified"
+            or signal not in path_text
+            or f"U3.{ball}" not in path_text
+            or series_resistor not in path_text
+            or not isinstance(programming, Mapping)
+            or programming.get("status") != "verified_fpga"
+            or ("专用" not in programming_text and "dedicated" not in programming_text.lower())
+        ):
+            raise BoardRegressionError(f"J3.{number} dedicated JTAG path drifted")
+
+    vref = pins["4"]
+    vref_programming = vref.get("programming")
+    vref_text = " ".join(
+        str(value)
+        for value in (
+            vref.get("summary", ""),
+            *vref.get("path", []),
+            vref_programming.get("conclusion", "") if isinstance(vref_programming, Mapping) else "",
+            vref_programming.get("network_explanation", "") if isinstance(vref_programming, Mapping) else "",
+            *(vref_programming.get("connection_guidance", []) if isinstance(vref_programming, Mapping) else []),
+        )
+    )
+    if (
+        vref.get("function_category") != "reference_voltage"
+        or vref.get("fpga") is not None
+        or "R61" not in vref_text
+        or "+3V3" not in vref_text
+        or not isinstance(vref_programming, Mapping)
+        or vref_programming.get("status") != "not_programmable"
+        or ("不是给板子供电" not in vref_text and "not board power" not in vref_text.lower())
+    ):
+        raise BoardRegressionError("J3.4 VREF purpose drifted")
+
+    for number in ("6", "7", "8"):
+        pin = pins[number]
+        programming = pin.get("programming")
+        if (
+            pin.get("function_category") != "not_connected"
+            or pin.get("fpga") is not None
+            or pin.get("reserved") is not True
+            or not isinstance(programming, Mapping)
+            or programming.get("status") != "not_programmable"
+        ):
+            raise BoardRegressionError(f"J3.{number} NC status drifted")
+
+
+def _validate_programming_guidance(by_reference: Mapping[str, Mapping[str, object]]) -> None:
+    for reference, touchpoint in by_reference.items():
+        pins = touchpoint.get("pins", [])
+        for pin in pins if isinstance(pins, list) else []:
+            if not isinstance(pin, Mapping):
+                continue
+            programming = pin.get("programming")
+            if not isinstance(programming, Mapping):
+                raise BoardRegressionError(f"{reference}.{pin.get('number')} programming guidance missing")
+            if programming.get("status") not in {
+                "verified_fpga",
+                "verified_mcu",
+                "board_only",
+                "not_programmable",
+                "unknown",
+            }:
+                raise BoardRegressionError(f"{reference}.{pin.get('number')} programming status invalid")
+            for field in ("conclusion", "network_explanation", "hdl_guidance"):
+                if not str(programming.get(field) or "").strip():
+                    raise BoardRegressionError(
+                        f"{reference}.{pin.get('number')} programming {field} missing"
+                    )
+            for field in ("connection_guidance", "constraints", "risks", "sources"):
+                if not isinstance(programming.get(field), list):
+                    raise BoardRegressionError(
+                        f"{reference}.{pin.get('number')} programming {field} must be an array"
+                    )
+            if programming.get("status") == "verified_fpga":
+                fpga = pin.get("fpga")
+                if (
+                    pin.get("evidence_tier") != "cross_verified"
+                    or not isinstance(fpga, Mapping)
+                    or fpga.get("evidence_tier") != "cross_verified"
+                    or not fpga.get("ball")
+                ):
+                    raise BoardRegressionError(
+                        f"{reference}.{pin.get('number')} programming claims an unverified FPGA path"
+                    )
+            if programming.get("status") == "verified_mcu":
+                mcu = pin.get("mcu")
+                if (
+                    pin.get("evidence_tier") != "cross_verified"
+                    or not isinstance(mcu, Mapping)
+                    or mcu.get("evidence_tier") != "cross_verified"
+                    or not mcu.get("device")
+                    or not mcu.get("pin")
+                    or not mcu.get("signal")
+                    or pin.get("fpga") is not None
+                ):
+                    raise BoardRegressionError(
+                        f"{reference}.{pin.get('number')} programming claims an invalid MCU path"
+                    )
+                if mcu.get("device") == "U27" and mcu.get("family") != "GD32F303CGT6":
+                    raise BoardRegressionError(
+                        f"{reference}.{pin.get('number')} U27 family must remain GD32F303CGT6"
+                    )
+
+    con78 = _pin_index(by_reference["CON78"])
+    for number, signal, ball, peer in (
+        ("1", "UART2_TX", "M10", "RX"),
+        ("2", "UART2_RX", "N11", "TX"),
+    ):
+        pin = con78[number]
+        programming = pin.get("programming")
+        text = " ".join(
+            str(value)
+            for value in (
+                programming.get("conclusion", ""),
+                programming.get("network_explanation", ""),
+                programming.get("hdl_guidance", ""),
+                *programming.get("connection_guidance", []),
+                *programming.get("constraints", []),
+            )
+        ) if isinstance(programming, Mapping) else ""
+        required = (signal, ball, "U23", peer, "TTL", f"LOCATION = {ball}", "IOSTANDARD = LVCMOS33")
+        if not isinstance(programming, Mapping) or programming.get("status") != "verified_fpga" or any(
+            value not in text for value in required
+        ):
+            raise BoardRegressionError(f"CON78.{number} programming guidance drifted")
+
+    con30_pin4 = _pin_index(by_reference["CON30"])["4"]
+    con30_fpga = con30_pin4.get("fpga")
+    con30_programming = con30_pin4.get("programming")
+    con30_text = " ".join(
+        str(value)
+        for value in (
+            con30_programming.get("conclusion", ""),
+            con30_programming.get("network_explanation", ""),
+            con30_programming.get("hdl_guidance", ""),
+            *con30_programming.get("constraints", []),
+        )
+    ) if isinstance(con30_programming, Mapping) else ""
+    if (
+        con30_pin4.get("net") != "FAN_GPIO4"
+        or con30_pin4.get("summary") != "MOTOR_EN_N"
+        or con30_pin4.get("external_level") != "3.3V LVCMOS"
+        or "R937 4.7K to +3V3" not in str(con30_pin4.get("board_pull") or "")
+        or not isinstance(con30_fpga, Mapping)
+        or con30_fpga.get("ball") != "A10"
+        or con30_fpga.get("board_signal") != "MOTOR_EN_N"
+        or not isinstance(con30_programming, Mapping)
+        or con30_programming.get("status") != "verified_fpga"
+        or any(value not in con30_text for value in ("MOTOR_EN_N", "FAN_GPIO4", "A10"))
+    ):
+        raise BoardRegressionError("CON30.4 MOTOR_EN_N programming guidance drifted")
+    if con30_pin4.get("active_level") != "low" or (
+        "低电平" not in con30_text and "low active" not in con30_text
+    ):
+        raise BoardRegressionError("CON30.4 programming must remain low active")
+
+    con31_pin4 = _pin_index(by_reference["CON31"])["4"]
+    con31_fpga = con31_pin4.get("fpga")
+    con31_programming = con31_pin4.get("programming")
+    con31_text = " ".join(
+        str(value)
+        for value in (
+            *con31_pin4.get("path", []),
+            con31_pin4.get("polarity", ""),
+            con31_programming.get("conclusion", ""),
+            con31_programming.get("network_explanation", ""),
+            con31_programming.get("hdl_guidance", ""),
+            *con31_programming.get("constraints", []),
+        )
+    ) if isinstance(con31_programming, Mapping) else ""
+    if (
+        con31_pin4.get("net") != "N9971986"
+        or con31_pin4.get("function_category") != "pwm"
+        or con31_pin4.get("evidence_tier") != "cross_verified"
+        or not isinstance(con31_fpga, Mapping)
+        or con31_fpga.get("ball") != "E10"
+        or con31_fpga.get("board_signal") != "FAN_GPIO6"
+        or con31_fpga.get("evidence_tier") != "cross_verified"
+        or not isinstance(con31_programming, Mapping)
+        or con31_programming.get("status") != "verified_fpga"
+        or con31_programming.get("evidence_tier") != "cross_verified"
+        or any(value not in con31_text for value in ("N9971986", "Q105", "FAN_GPIO6", "E10"))
+        or ("拉低" not in con31_text and "pulls connector low" not in con31_text)
+    ):
+        raise BoardRegressionError("CON31.4 programming verified open-collector path drifted")
+
+    con58_pin4 = _pin_index(by_reference["CON58"])["4"]
+    con58_fpga = con58_pin4.get("fpga")
+    con58_programming = con58_pin4.get("programming")
+    con58_text = " ".join(
+        str(value)
+        for value in (
+            con58_pin4.get("summary", ""),
+            con58_programming.get("conclusion", ""),
+            con58_programming.get("network_explanation", ""),
+            con58_programming.get("hdl_guidance", ""),
+            *con58_programming.get("constraints", []),
+        )
+    ) if isinstance(con58_programming, Mapping) else ""
+    if (
+        con58_pin4.get("net") != "FAN_GPIO38"
+        or con58_pin4.get("function_category") != "motor_step"
+        or con58_pin4.get("active_level") != "rising_edge"
+        or not isinstance(con58_fpga, Mapping)
+        or con58_fpga.get("ball") != "D15"
+        or con58_fpga.get("board_signal") != "MOTOR_STEP"
+        or not isinstance(con58_programming, Mapping)
+        or con58_programming.get("status") != "verified_fpga"
+        or not any(marker in con58_text for marker in ("上升沿", "rising edge", "rising-edge"))
+    ):
+        raise BoardRegressionError("CON58.4 MOTOR_STEP rising-edge semantics drifted")
+
+    con65_pin4 = _pin_index(by_reference["CON65"])["4"]
+    con65_fpga = con65_pin4.get("fpga")
+    con65_programming = con65_pin4.get("programming")
+    con65_text = " ".join(
+        str(value)
+        for value in (
+            con65_pin4.get("summary", ""),
+            con65_programming.get("conclusion", ""),
+            con65_programming.get("network_explanation", ""),
+            con65_programming.get("hdl_guidance", ""),
+            *con65_programming.get("constraints", []),
+        )
+    ) if isinstance(con65_programming, Mapping) else ""
+    if (
+        con65_pin4.get("net") != "FAN_GPIO32"
+        or con65_pin4.get("function_category") != "motor_direction"
+        or con65_pin4.get("active_level") != "state"
+        or not isinstance(con65_fpga, Mapping)
+        or con65_fpga.get("ball") != "H14"
+        or con65_fpga.get("board_signal") != "MOTOR_DIR"
+        or not isinstance(con65_programming, Mapping)
+        or con65_programming.get("status") != "verified_fpga"
+        or not any(marker in con65_text for marker in ("方向状态", "direction state"))
+    ):
+        raise BoardRegressionError("CON65.4 MOTOR_DIR state semantics drifted")
+
+    con53_pin1 = _pin_index(by_reference["CON53"])["1"]
+    con53_programming = con53_pin1.get("programming")
+    con53_text = " ".join(
+        str(value)
+        for value in (
+            con53_programming.get("hdl_guidance", ""),
+            *con53_programming.get("risks", []),
+        )
+    ) if isinstance(con53_programming, Mapping) else ""
+    if (
+        con53_pin1.get("function_category") != "remote_temperature"
+        or not isinstance(con53_programming, Mapping)
+        or con53_programming.get("status") != "board_only"
+        or "open-drain" not in con53_text
+        or not any(marker in con53_text for marker in ("只拉低或释放", "drive low or release"))
+        or "R811/R812" not in con53_text
+    ):
+        raise BoardRegressionError("CON53.1 CT7428 open-drain programming guidance drifted")
+
+
+def validate_product_regression(payload: Mapping[str, object]) -> None:
+    counts = payload.get("counts")
+    if not isinstance(counts, Mapping):
+        raise BoardRegressionError("counts missing")
+    for name, expected in EXPECTED_COUNTS.items():
+        if counts.get(name) != expected:
+            raise BoardRegressionError(f"{name}={counts.get(name)} expected {expected}")
+    categories = counts.get("categories")
+    if not isinstance(categories, Mapping):
+        raise BoardRegressionError("category counts missing")
+    for name, expected in EXPECTED_CATEGORIES.items():
+        if categories.get(name) != expected:
+            raise BoardRegressionError(f"{name}={categories.get(name)} expected {expected}")
+    sides = counts.get("sides")
+    if not isinstance(sides, Mapping) or sides.get("front") != 110 or sides.get("back") != 0:
+        back = sides.get("back") if isinstance(sides, Mapping) else "missing"
+        raise BoardRegressionError(f"all touchpoints must be front-side; back={back}")
+
+    raw_touchpoints = payload.get("touchpoints", [])
+    touchpoints = [item for item in raw_touchpoints if isinstance(item, Mapping)] if isinstance(raw_touchpoints, list) else []
+    references = [str(item.get("reference") or "") for item in touchpoints]
+    if "CON5" in references:
+        raise BoardRegressionError("CON5 must not appear as a footprint hotspot")
+    if len(touchpoints) != 110 or len(set(references)) != 110:
+        raise BoardRegressionError(f"touchpoint list has {len(touchpoints)} rows and {len(set(references))} unique references")
+    actual_categories = Counter(_category(reference) for reference in references)
+    if dict(actual_categories) != EXPECTED_CATEGORIES:
+        raise BoardRegressionError(f"touchpoint reference categories drifted: {dict(actual_categories)}")
+    if any(item.get("side") != "front" for item in touchpoints):
+        raise BoardRegressionError("touchpoint list contains a non-front item")
+
+    by_reference = {str(item.get("reference")): item for item in touchpoints}
+    _validate_connector_contracts(by_reference)
+    _validate_j3_jtag(by_reference)
+    con78 = by_reference.get("CON78")
+    if con78 is None:
+        raise BoardRegressionError("CON78 missing")
+    pins = _pin_index(con78)
+    expected_nets = {
+        "1": "RS232_TX2",
+        "2": "RS232_RX2",
+        "3": "GND",
+        "4": "GND",
+        "5": "GND",
+        "6": "GND",
+    }
+    for number, net in expected_nets.items():
+        if number not in pins or pins[number].get("net") != net:
+            actual = pins.get(number, {}).get("net") if number in pins else "missing"
+            raise BoardRegressionError(f"CON78.{number} net={actual} expected {net}")
+    for number, ball in (("1", "M10"), ("2", "N11")):
+        pin = pins[number]
+        fpga = pin.get("fpga")
+        if not isinstance(fpga, Mapping) or fpga.get("ball") != ball:
+            actual = fpga.get("ball") if isinstance(fpga, Mapping) else "missing"
+            raise BoardRegressionError(f"CON78.{number} FPGA ball={actual} expected {ball}")
+        if "U23" not in " ".join(str(item) for item in pin.get("path", [])):
+            raise BoardRegressionError(f"CON78.{number} path must include U23")
+
+    _validate_recommendable_pins(touchpoints)
+    _validate_programming_guidance(by_reference)

+ 179 - 0
tools/board-viewer/board_viewer/server.py

@@ -0,0 +1,179 @@
+"""Loopback-only read-only HTTP server for the local board viewer."""
+
+from __future__ import annotations
+
+import json
+import mimetypes
+import re
+from http import HTTPStatus
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from urllib.parse import unquote, urlsplit
+
+from .assets import AssetIntegrityError, AssetValidationResult, validate_generated_bundle
+
+
+ROOT = Path(__file__).resolve().parents[3]
+WEB_FILES = {
+    "/": "index.html",
+    "/index.html": "index.html",
+    "/app.css": "app.css",
+    "/app.js": "app.js",
+    "/board-logic.mjs": "board-logic.mjs",
+}
+GENERATED_FILES = {
+    "/generated/board-data.json": "board-data.json",
+    "/generated/board-mask-edge.svg": "board-mask-edge.svg",
+    "/generated/board-silkscreen.svg": "board-silkscreen.svg",
+    "/generated/board-copper.svg": "board-copper.svg",
+}
+PHOTO_ASSET = re.compile(r"^board-photo\.(?:png|jpg|jpeg|webp)$")
+
+
+class BoardViewerServer(ThreadingHTTPServer):
+    daemon_threads = True
+    allow_reuse_address = True
+
+
+def _runtime_payload(result: AssetValidationResult) -> dict[str, object]:
+    return {
+        "status": result.status,
+        "assetErrors": result.asset_errors,
+        "staleSources": result.stale_sources,
+        "recommendationsEnabled": result.recommendations_enabled,
+        "adcCopyEnabled": result.adc_copy_enabled,
+        "generatedAt": result.build_info.get("generated_at"),
+        "counts": result.build_info.get("counts"),
+    }
+
+
+def _request_path(raw_path: str) -> str | None:
+    path = unquote(urlsplit(raw_path).path)
+    if "\x00" in path or "\\" in path:
+        return None
+    parts = path.split("/")
+    if any(part in {".", ".."} for part in parts):
+        return None
+    return path
+
+
+def create_server(
+    web_root: Path | str,
+    generated_dir: Path | str,
+    *,
+    host: str = "127.0.0.1",
+    port: int = 8765,
+    repository_root: Path | str = ROOT,
+) -> BoardViewerServer:
+    if host != "127.0.0.1":
+        raise ValueError("board viewer server must bind exactly to 127.0.0.1")
+    web = Path(web_root).resolve()
+    generated = Path(generated_dir).resolve()
+    repository = Path(repository_root).resolve()
+    for filename in set(WEB_FILES.values()):
+        if not (web / filename).is_file():
+            raise AssetIntegrityError(f"missing web asset: {filename}")
+    validate_generated_bundle(generated, repository_root=repository)
+    generated_files = dict(GENERATED_FILES)
+    board_data = json.loads((generated / "board-data.json").read_text(encoding="utf-8"))
+    photo_overlay = board_data.get("photo_overlay")
+    if isinstance(photo_overlay, dict):
+        photo_asset = str(photo_overlay.get("asset") or "")
+        if not PHOTO_ASSET.fullmatch(photo_asset):
+            raise AssetIntegrityError(f"unsafe photo asset name: {photo_asset}")
+        generated_files[f"/generated/{photo_asset}"] = photo_asset
+
+    class Handler(BaseHTTPRequestHandler):
+        server_version = "BoardViewer/1.0"
+        sys_version = ""
+
+        def log_message(self, format: str, *args: object) -> None:
+            return
+
+        def _security_headers(self) -> None:
+            self.send_header("X-Content-Type-Options", "nosniff")
+            self.send_header("Referrer-Policy", "no-referrer")
+            self.send_header("Cross-Origin-Resource-Policy", "same-origin")
+            self.send_header(
+                "Content-Security-Policy",
+                "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; "
+                "connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'",
+            )
+            self.send_header("Cache-Control", "no-store")
+
+        def _send_bytes(self, payload: bytes, content_type: str, *, status: int = 200, head: bool = False) -> None:
+            self.send_response(status)
+            self._security_headers()
+            self.send_header("Content-Type", content_type)
+            self.send_header("Content-Length", str(len(payload)))
+            self.end_headers()
+            if not head:
+                self.wfile.write(payload)
+
+        def _send_not_found(self, *, head: bool = False) -> None:
+            self._send_bytes(b"Not Found\n", "text/plain; charset=utf-8", status=HTTPStatus.NOT_FOUND, head=head)
+
+        def _serve(self, *, head: bool = False) -> None:
+            path = _request_path(self.path)
+            if path is None:
+                self._send_not_found(head=head)
+                return
+            if path == "/api/status":
+                try:
+                    result = validate_generated_bundle(generated, repository_root=repository)
+                    payload = _runtime_payload(result)
+                    status = HTTPStatus.OK
+                except AssetIntegrityError as exc:
+                    payload = {
+                        "status": "invalid_assets",
+                        "assetErrors": [str(exc)],
+                        "staleSources": [],
+                        "recommendationsEnabled": False,
+                        "adcCopyEnabled": False,
+                        "message": str(exc),
+                    }
+                    status = HTTPStatus.SERVICE_UNAVAILABLE
+                body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
+                self._send_bytes(body, "application/json; charset=utf-8", status=status, head=head)
+                return
+            if path in WEB_FILES:
+                file_path = web / WEB_FILES[path]
+            elif path in generated_files:
+                file_path = generated / generated_files[path]
+            else:
+                self._send_not_found(head=head)
+                return
+            try:
+                body = file_path.read_bytes()
+            except OSError:
+                self._send_not_found(head=head)
+                return
+            content_type = mimetypes.guess_type(file_path.name)[0] or "application/octet-stream"
+            if file_path.suffix in {".js", ".mjs"}:
+                content_type = "text/javascript"
+            if file_path.suffix in {".html", ".css", ".js", ".mjs", ".json", ".svg"}:
+                content_type += "; charset=utf-8"
+            self._send_bytes(body, content_type, head=head)
+
+        def do_GET(self) -> None:  # noqa: N802
+            self._serve(head=False)
+
+        def do_HEAD(self) -> None:  # noqa: N802
+            self._serve(head=True)
+
+        def _reject_mutation(self) -> None:
+            payload = b"Method Not Allowed\n"
+            self.send_response(HTTPStatus.METHOD_NOT_ALLOWED)
+            self._security_headers()
+            self.send_header("Allow", "GET, HEAD")
+            self.send_header("Content-Type", "text/plain; charset=utf-8")
+            self.send_header("Content-Length", str(len(payload)))
+            self.end_headers()
+            self.wfile.write(payload)
+
+        do_POST = _reject_mutation  # noqa: N815
+        do_PUT = _reject_mutation  # noqa: N815
+        do_PATCH = _reject_mutation  # noqa: N815
+        do_DELETE = _reject_mutation  # noqa: N815
+
+    return BoardViewerServer((host, port), Handler)

+ 190 - 0
tools/board-viewer/board_viewer/sexpr.py

@@ -0,0 +1,190 @@
+"""Streaming S-expression reader for KiCad board files."""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from contextlib import contextmanager
+from dataclasses import dataclass
+from pathlib import Path
+from typing import TextIO
+
+
+SExpr = str | list["SExpr"]
+
+
+class SExprError(ValueError):
+    """Raised when an S-expression stream is malformed."""
+
+
+@dataclass(frozen=True)
+class Token:
+    kind: str
+    value: str
+    line: int
+    column: int
+
+
+class _CharacterStream:
+    def __init__(self, stream: TextIO, chunk_size: int = 65536) -> None:
+        self.stream = stream
+        self.chunk_size = chunk_size
+        self.buffer = ""
+        self.index = 0
+        self.eof = False
+        self.line = 1
+        self.column = 0
+
+    def _fill(self) -> bool:
+        if self.index < len(self.buffer):
+            return True
+        if self.eof:
+            return False
+        self.buffer = self.stream.read(self.chunk_size)
+        self.index = 0
+        if not self.buffer:
+            self.eof = True
+            return False
+        return True
+
+    def peek(self) -> str:
+        return self.buffer[self.index] if self._fill() else ""
+
+    def take(self) -> str:
+        if not self._fill():
+            return ""
+        char = self.buffer[self.index]
+        self.index += 1
+        if char == "\n":
+            self.line += 1
+            self.column = 0
+        else:
+            self.column += 1
+        return char
+
+
+def tokenize(stream: TextIO) -> Iterator[Token]:
+    chars = _CharacterStream(stream)
+    while True:
+        char = chars.peek()
+        if not char:
+            return
+        if char.isspace() or char == "\ufeff":
+            chars.take()
+            continue
+        if char == ";":
+            while chars.peek() not in {"", "\n"}:
+                chars.take()
+            continue
+
+        line, column = chars.line, chars.column + 1
+        if char == "(":
+            chars.take()
+            yield Token("lparen", "(", line, column)
+            continue
+        if char == ")":
+            chars.take()
+            yield Token("rparen", ")", line, column)
+            continue
+        if char == '"':
+            chars.take()
+            value: list[str] = []
+            while True:
+                current = chars.take()
+                if not current:
+                    raise SExprError(f"unterminated string at {line}:{column}")
+                if current == '"':
+                    break
+                if current != "\\":
+                    value.append(current)
+                    continue
+                escaped = chars.take()
+                if not escaped:
+                    raise SExprError(f"unterminated escape at {line}:{column}")
+                value.append({"n": "\n", "r": "\r", "t": "\t"}.get(escaped, escaped))
+            yield Token("string", "".join(value), line, column)
+            continue
+
+        value = []
+        while True:
+            current = chars.peek()
+            if not current or current.isspace() or current in "();":
+                break
+            value.append(chars.take())
+        if not value:
+            raise SExprError(f"unexpected character {chars.take()!r} at {line}:{column}")
+        yield Token("atom", "".join(value), line, column)
+
+
+class _TokenReader:
+    def __init__(self, tokens: Iterator[Token]) -> None:
+        self.tokens = tokens
+        self.buffered: Token | None = None
+
+    def peek(self) -> Token | None:
+        if self.buffered is None:
+            self.buffered = next(self.tokens, None)
+        return self.buffered
+
+    def take(self) -> Token | None:
+        token = self.peek()
+        self.buffered = None
+        return token
+
+    def expect(self, kind: str) -> Token:
+        token = self.take()
+        if token is None or token.kind != kind:
+            actual = "end of file" if token is None else f"{token.kind} at {token.line}:{token.column}"
+            raise SExprError(f"expected {kind}, got {actual}")
+        return token
+
+
+def _read_form(reader: _TokenReader) -> list[SExpr]:
+    reader.expect("lparen")
+    values: list[SExpr] = []
+    while True:
+        token = reader.peek()
+        if token is None:
+            raise SExprError("unexpected end of file inside list")
+        if token.kind == "rparen":
+            reader.take()
+            return values
+        if token.kind == "lparen":
+            values.append(_read_form(reader))
+            continue
+        if token.kind in {"atom", "string"}:
+            values.append(reader.take().value)  # type: ignore[union-attr]
+            continue
+        raise SExprError(f"unexpected token {token.kind} at {token.line}:{token.column}")
+
+
+@contextmanager
+def _open_source(source: Path | str | TextIO) -> Iterator[TextIO]:
+    if hasattr(source, "read"):
+        yield source  # type: ignore[misc]
+        return
+    with Path(source).open("r", encoding="utf-8", errors="strict", newline="") as stream:
+        yield stream
+
+
+def iter_root_forms(source: Path | str | TextIO, expected_root: str = "kicad_pcb") -> Iterator[list[SExpr]]:
+    """Yield one materialized top-level form at a time from a KiCad file."""
+
+    with _open_source(source) as stream:
+        reader = _TokenReader(iter(tokenize(stream)))
+        reader.expect("lparen")
+        root = reader.expect("atom")
+        if root.value != expected_root:
+            raise SExprError(f"expected root {expected_root}, got {root.value}")
+        while True:
+            token = reader.peek()
+            if token is None:
+                raise SExprError("unexpected end of file before root close")
+            if token.kind == "rparen":
+                reader.take()
+                if reader.peek() is not None:
+                    trailing = reader.peek()
+                    raise SExprError(f"trailing token at {trailing.line}:{trailing.column}")
+                return
+            if token.kind != "lparen":
+                raise SExprError(f"expected top-level form at {token.line}:{token.column}")
+            yield _read_form(reader)

+ 63 - 0
tools/board-viewer/package-lock.json

@@ -0,0 +1,63 @@
+{
+  "name": "cpld-board-viewer-validation",
+  "version": "1.0.0",
+  "lockfileVersion": 3,
+  "requires": true,
+  "packages": {
+    "": {
+      "name": "cpld-board-viewer-validation",
+      "version": "1.0.0",
+      "license": "UNLICENSED",
+      "devDependencies": {
+        "playwright": "1.61.1"
+      }
+    },
+    "node_modules/fsevents": {
+      "version": "2.3.2",
+      "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
+      "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
+      "dev": true,
+      "hasInstallScript": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+      }
+    },
+    "node_modules/playwright": {
+      "version": "1.61.1",
+      "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz",
+      "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "dependencies": {
+        "playwright-core": "1.61.1"
+      },
+      "bin": {
+        "playwright": "cli.js"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "optionalDependencies": {
+        "fsevents": "2.3.2"
+      }
+    },
+    "node_modules/playwright-core": {
+      "version": "1.61.1",
+      "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz",
+      "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "bin": {
+        "playwright-core": "cli.js"
+      },
+      "engines": {
+        "node": ">=18"
+      }
+    }
+  }
+}

+ 15 - 0
tools/board-viewer/package.json

@@ -0,0 +1,15 @@
+{
+  "name": "cpld-board-viewer-validation",
+  "version": "1.0.0",
+  "private": true,
+  "description": "Offline validation harness for the local FCB board viewer",
+  "license": "UNLICENSED",
+  "scripts": {
+    "test": "npm run test:logic",
+    "test:logic": "node --test ../../tests/board_viewer/board-logic.test.mjs",
+    "test:e2e": "node ../../tests/board_viewer/playwright_e2e.cjs"
+  },
+  "devDependencies": {
+    "playwright": "1.61.1"
+  }
+}

Разница между файлами не показана из-за своего большого размера
+ 1281 - 0
tools/board-viewer/web/app.css


Разница между файлами не показана из-за своего большого размера
+ 1038 - 0
tools/board-viewer/web/app.js


+ 288 - 0
tools/board-viewer/web/board-logic.mjs

@@ -0,0 +1,288 @@
+const VERIFIED = "cross_verified";
+const POWER_NET = /^(?:GND|AGND|DGND|PGND|EARTH|VCC|VDD|VBAT|PWR|\+)/i;
+const RTL_PORT = /^[A-Za-z_][A-Za-z0-9_$]*(?:\[[0-9]+\])?$/;
+const CAPABILITY_ALIASES = {
+  pwm: ["pwm", "pwm_output"],
+  gpio_output: ["gpio_output", "digital_output"],
+  gpio_input: ["gpio_input", "digital_input"],
+  tach: ["tach", "tach_input"],
+  fan_tach: ["fan_tach", "tach_input"],
+  presence: ["presence", "presence_input"],
+};
+
+
+function text(value) {
+  return value == null ? "" : String(value);
+}
+
+
+function normalized(value) {
+  return text(value).trim().toLocaleLowerCase();
+}
+
+
+function naturalCompare(left, right) {
+  return text(left).localeCompare(text(right), undefined, {numeric: true, sensitivity: "base"});
+}
+
+
+function capabilities(pin) {
+  return Array.isArray(pin?.fpga?.capabilities) ? pin.fpga.capabilities.map(text) : [];
+}
+
+
+function baseBlockers(pin) {
+  const blockers = [];
+  if (pin?.evidence_tier !== VERIFIED || pin?.fpga?.evidence_tier !== VERIFIED) {
+    blockers.push("unverified");
+  }
+  if (!pin?.fpga?.ball || !pin?.fpga?.io_standard) blockers.push("missing_fpga_assignment");
+  if (pin?.mechanical === true || pin?.electrical !== true) blockers.push("mechanical_or_non_electrical");
+  if (pin?.pad_role !== "contact") blockers.push("not_connector_contact");
+  if (["power", "ground"].includes(pin?.function_category) || POWER_NET.test(text(pin?.net))) {
+    blockers.push("power_or_ground");
+  }
+  if (pin?.reserved === true) blockers.push("reserved");
+  if (pin?.fixed_load_conflict === true) blockers.push("fixed_load_conflict");
+  if (["", "unknown"].includes(normalized(pin?.external_level))) blockers.push("external_level_unknown");
+  return blockers;
+}
+
+
+export function connectorPinGroups(touchpoint) {
+  const pins = Array.isArray(touchpoint?.pins) ? touchpoint.pins : [];
+  const connector = touchpoint?.connector;
+  const reviewed = connector?.review_status === VERIFIED;
+  const grid = reviewed && Array.isArray(connector?.contact_grid) ? connector.contact_grid : [];
+  const byNumber = new Map(
+    pins
+      .filter((pin) => pin?.pad_role === "contact" && text(pin?.number))
+      .map((pin) => [text(pin.number), pin]),
+  );
+  const contactRows = grid.map((row) =>
+    (Array.isArray(row) ? row : []).map((number) => byNumber.get(text(number))).filter(Boolean),
+  );
+  return {
+    contactRows,
+    contacts: contactRows.flat(),
+    auxiliary: pins.filter((pin) => pin?.pad_role !== "contact"),
+  };
+}
+
+
+function pinSearchFields(touchpoint, pin) {
+  const programming = pin?.programming ?? {};
+  return [
+    ["pin", `${touchpoint.reference}.${pin.number}`],
+    ["reference", touchpoint.reference],
+    ["pin_number", pin.number],
+    ["net", pin.net],
+    ["summary", pin.summary],
+    ["function", pin.function_category],
+    ["direction", pin.direction],
+    ["external_level", pin.external_level],
+    ["fpga_ball", pin.fpga?.ball],
+    ["board_signal", pin.fpga?.board_signal],
+    ["capability", capabilities(pin).join(" ")],
+    ["mcu_device", pin.mcu?.device],
+    ["mcu_family", pin.mcu?.family],
+    ["mcu_pin", pin.mcu?.device && pin.mcu?.pin ? `${pin.mcu.device}.${pin.mcu.pin}` : ""],
+    ["mcu_signal", pin.mcu?.signal],
+    ["mcu_capability", Array.isArray(pin.mcu?.capabilities) ? pin.mcu.capabilities.join(" ") : ""],
+    ["path", Array.isArray(pin.path) ? pin.path.join(" ") : ""],
+    ["programming_conclusion", programming.conclusion],
+    ["network_explanation", programming.network_explanation],
+    ["hdl_guidance", programming.hdl_guidance],
+    ["connection_guidance", Array.isArray(programming.connection_guidance) ? programming.connection_guidance.join(" ") : ""],
+    ["programming_constraints", Array.isArray(programming.constraints) ? programming.constraints.join(" ") : ""],
+    ["programming_risks", Array.isArray(programming.risks) ? programming.risks.join(" ") : ""],
+  ];
+}
+
+
+function fieldScore(field, value, query) {
+  const candidate = normalized(value);
+  if (!candidate) return 0;
+  const weights = {
+    pin: 1200,
+    reference: 1000,
+    fpga_ball: 900,
+    mcu_pin: 900,
+    mcu_signal: 840,
+    mcu_device: 800,
+    mcu_family: 780,
+    mcu_capability: 720,
+    net: 850,
+    board_signal: 820,
+    function: 760,
+    capability: 720,
+    pin_number: 620,
+    summary: 500,
+    path: 460,
+    programming_conclusion: 700,
+    network_explanation: 610,
+    hdl_guidance: 590,
+    connection_guidance: 570,
+    programming_constraints: 540,
+    programming_risks: 480,
+    external_level: 420,
+    direction: 360,
+  };
+  const weight = weights[field] ?? 200;
+  if (candidate === query) return weight;
+  if (candidate.startsWith(query)) return weight - 120;
+  if (candidate.includes(query)) return weight - 240;
+  return 0;
+}
+
+
+export function searchBoard(data, query) {
+  const needle = normalized(query);
+  if (!needle) return [];
+  const results = [];
+  for (const touchpoint of data?.touchpoints ?? []) {
+    const touchpointFields = [
+      ["reference", touchpoint.reference],
+      ["summary", touchpoint.summary],
+      ["function", touchpoint.category],
+    ];
+    let touchpointScore = 0;
+    let touchpointField = "";
+    for (const [field, value] of touchpointFields) {
+      const score = fieldScore(field, value, needle);
+      if (score > touchpointScore) {
+        touchpointScore = score;
+        touchpointField = field;
+      }
+    }
+    if (touchpointScore) {
+      results.push({
+        type: "touchpoint",
+        reference: touchpoint.reference,
+        pinNumber: null,
+        touchpoint,
+        pin: null,
+        matchedField: touchpointField,
+        score: touchpointScore + 20,
+      });
+    }
+    for (const pin of touchpoint.pins ?? []) {
+      let score = 0;
+      let matchedField = "";
+      for (const [field, value] of pinSearchFields(touchpoint, pin)) {
+        const candidateScore = fieldScore(field, value, needle);
+        if (candidateScore > score) {
+          score = candidateScore;
+          matchedField = field;
+        }
+      }
+      if (!score) continue;
+      if (baseBlockers(pin).length === 0) score += 40;
+      results.push({
+        type: "pin",
+        reference: touchpoint.reference,
+        pinNumber: text(pin.number),
+        touchpoint,
+        pin,
+        matchedField,
+        score,
+      });
+    }
+  }
+  return results.sort((left, right) => {
+    if (right.score !== left.score) return right.score - left.score;
+    const referenceOrder = naturalCompare(left.reference, right.reference);
+    if (referenceOrder) return referenceOrder;
+    if (left.type !== right.type) return left.type === "touchpoint" ? -1 : 1;
+    return naturalCompare(left.pinNumber, right.pinNumber);
+  });
+}
+
+
+export function sameNetPins(data, net) {
+  const wanted = text(net);
+  if (!wanted) return [];
+  const matches = [];
+  for (const touchpoint of data?.touchpoints ?? []) {
+    for (const pin of touchpoint.pins ?? []) {
+      if (pin.net === wanted) {
+        matches.push({reference: touchpoint.reference, pinNumber: text(pin.number), touchpoint, pin});
+      }
+    }
+  }
+  return matches.sort((left, right) => {
+    const referenceOrder = naturalCompare(left.reference, right.reference);
+    return referenceOrder || naturalCompare(left.pinNumber, right.pinNumber);
+  });
+}
+
+
+export function findCandidates(data, capability) {
+  const wanted = normalized(capability);
+  if (!wanted) return [];
+  const acceptedCapabilities = new Set(
+    (CAPABILITY_ALIASES[wanted] ?? [wanted]).map(normalized),
+  );
+  const candidates = [];
+  for (const touchpoint of data?.touchpoints ?? []) {
+    for (const pin of touchpoint.pins ?? []) {
+      const pinCapabilities = capabilities(pin).map(normalized);
+      if (!pinCapabilities.some((item) => acceptedCapabilities.has(item))) continue;
+      if (wanted === "gpio" && !["gpio", "direct_gpio"].includes(normalized(pin.function_category))) {
+        continue;
+      }
+      if (baseBlockers(pin).length) continue;
+      const purpose = text(pin.summary).trim();
+      const polarity = normalized(pin.polarity);
+      const details = [];
+      if (purpose) details.push(`用途 ${purpose}`);
+      if (polarity && polarity !== "unknown") details.push(`极性 ${pin.polarity}`);
+      candidates.push({
+        reference: touchpoint.reference,
+        touchpoint,
+        pin,
+        reason: `${details.length ? `${details.join(";")};` : ""}能力 ${capability} 匹配;已验证 FPGA 路径至 ${pin.fpga.ball};外部电平 ${pin.external_level}。`,
+        warning: "只证明物理可用性,仍需检查当前工程约束冲突。",
+      });
+    }
+  }
+  return candidates.sort((left, right) => {
+    const categoryMatchLeft = normalized(left.pin.function_category) === wanted ? 1 : 0;
+    const categoryMatchRight = normalized(right.pin.function_category) === wanted ? 1 : 0;
+    if (categoryMatchRight !== categoryMatchLeft) return categoryMatchRight - categoryMatchLeft;
+    const referenceOrder = naturalCompare(left.reference, right.reference);
+    return referenceOrder || naturalCompare(left.pin.number, right.pin.number);
+  });
+}
+
+
+export function isValidRtlPortName(name) {
+  return RTL_PORT.test(text(name));
+}
+
+
+export function generateAdcSnippet(pin, rtlPortName, runtimeStatus = {}) {
+  if (runtimeStatus.adcCopyEnabled !== true) {
+    throw new Error("源数据已过期,ADC 复制已关闭。");
+  }
+  if (!isValidRtlPortName(rtlPortName)) {
+    throw new Error("生成 ADC 前请输入合法的 RTL 端口名。");
+  }
+  if (baseBlockers(pin).length) {
+    throw new Error("此针脚不具备 ADC 生成资格。");
+  }
+  const ball = text(pin.fpga.ball);
+  const ioStandard = text(pin.fpga.io_standard);
+  if (!/^[A-Z]+[0-9]+$/.test(ball) || !/^[A-Za-z0-9_.+-]+$/.test(ioStandard)) {
+    throw new Error("已验证 FPGA 分配包含不安全的 ADC 值。");
+  }
+  const assignments = [`LOCATION = ${ball}`, `IOSTANDARD = ${ioStandard}`];
+  if (pin.adc_pulltype != null) {
+    const pulltype = text(pin.adc_pulltype);
+    if (!/^[A-Z][A-Z0-9_]*$/.test(pulltype)) {
+      throw new Error("人工注释的 PULLTYPE 包含不安全值。");
+    }
+    assignments.push(`PULLTYPE = ${pulltype}`);
+  }
+  return `set_pin_assignment { ${rtlPortName} } { ${assignments.join("; ")}; }`;
+}

+ 126 - 0
tools/board-viewer/web/index.html

@@ -0,0 +1,126 @@
+<!doctype html>
+<html lang="zh-CN">
+  <head>
+    <meta charset="utf-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1">
+    <meta name="color-scheme" content="light">
+    <title>电路板选脚查看器</title>
+    <link rel="stylesheet" href="app.css">
+  </head>
+  <body>
+    <div class="app-shell" id="app">
+      <header class="topbar">
+        <div class="product-block">
+          <span class="product-mark" aria-hidden="true"></span>
+          <div>
+            <div class="product-title">FCB 电路板选脚查看器</div>
+            <div class="product-meta" id="board-summary">正在载入板数据</div>
+          </div>
+        </div>
+
+        <div class="search-block">
+          <label class="search-field" for="board-search">
+            <span aria-hidden="true">⌕</span>
+            <input
+              id="board-search"
+              type="search"
+              autocomplete="off"
+              spellcheck="false"
+              placeholder="位号、针号、网络、功能、能力或 FPGA 球位"
+              aria-controls="search-results"
+              aria-autocomplete="list"
+            >
+          </label>
+          <div id="search-results" class="search-results" role="listbox" aria-label="搜索结果" hidden></div>
+        </div>
+
+        <div class="status-cluster">
+          <span id="app-status" class="status-badge status-loading" role="status">校验中</span>
+          <button id="drawer-toggle" class="icon-button drawer-toggle" type="button" title="展开详情" aria-label="展开详情" aria-expanded="true">
+            <span aria-hidden="true">⌄</span>
+          </button>
+        </div>
+      </header>
+
+      <main class="workspace">
+        <section class="board-pane" aria-label="电路板工作区">
+          <div id="stale-banner" class="stale-banner" role="alert" hidden></div>
+          <div class="board-toolbar">
+            <fieldset id="category-filters" class="segmented filters" aria-label="座子类别">
+              <legend class="sr-only">座子类别</legend>
+              <label><input type="checkbox" value="CON" checked><span>CON</span></label>
+              <label><input type="checkbox" value="J" checked><span>J</span></label>
+              <label><input type="checkbox" value="PL" checked><span>PL</span></label>
+              <label><input type="checkbox" value="TP" checked><span>TP</span></label>
+            </fieldset>
+
+            <fieldset id="layer-controls" class="layer-controls" aria-label="板图图层">
+              <legend class="sr-only">板图图层</legend>
+              <label><input type="checkbox" value="mask" checked><span class="swatch swatch-mask"></span>阻焊/板框</label>
+              <label><input type="checkbox" value="silk" checked><span class="swatch swatch-silk"></span>丝印</label>
+              <label><input type="checkbox" value="copper" checked><span class="swatch swatch-copper"></span>铜层</label>
+              <label id="photo-control" class="disabled-control" title="当前版本未配置照片叠层"><input id="photo-layer" type="checkbox" value="photo" disabled><span class="swatch swatch-photo"></span><span id="photo-label">照片未配置</span></label>
+            </fieldset>
+
+            <div class="view-tools" aria-label="视图工具">
+              <button id="zoom-out" class="icon-button" type="button" title="缩小" aria-label="缩小"><span aria-hidden="true">−</span></button>
+              <button id="zoom-in" class="icon-button" type="button" title="放大" aria-label="放大"><span aria-hidden="true">+</span></button>
+              <button id="reset-view" class="icon-button" type="button" title="重置视图" aria-label="重置视图"><span aria-hidden="true">↺</span></button>
+            </div>
+          </div>
+
+          <div id="board-viewport" class="board-viewport">
+            <svg id="board-svg" role="img" aria-label="电路板视图" tabindex="0" preserveAspectRatio="xMidYMid meet">
+              <g id="asset-layers" aria-hidden="true">
+                <image id="layer-mask" href="/generated/board-mask-edge.svg" preserveAspectRatio="none"></image>
+                <image id="layer-silk" href="/generated/board-silkscreen.svg" preserveAspectRatio="none"></image>
+                <image id="layer-copper" href="/generated/board-copper.svg" preserveAspectRatio="none"></image>
+                <image id="layer-photo" preserveAspectRatio="none" hidden></image>
+              </g>
+              <g id="net-layer" aria-hidden="true"></g>
+              <g id="hotspot-layer"></g>
+              <g id="pin-layer"></g>
+              <g id="selection-layer" aria-hidden="true"></g>
+            </svg>
+            <div id="board-loading" class="board-loading" role="status">正在载入 110 个接触点</div>
+            <div id="board-tooltip" class="board-tooltip" role="tooltip" hidden></div>
+            <div class="coordinate-rail" aria-hidden="true"><span>0</span><span>215 mm</span><span>430 mm</span></div>
+          </div>
+
+          <footer class="board-footer">
+            <span id="visible-count">0 个座子</span>
+            <span id="zoom-readout">100%</span>
+            <span id="selection-readout">未选择</span>
+          </footer>
+        </section>
+
+        <aside id="detail-panel" class="detail-panel" aria-label="座子与针脚详情">
+          <div class="drawer-handle" aria-hidden="true"></div>
+          <div class="detail-tabs" role="tablist" aria-label="详情视图">
+            <button id="detail-tab" type="button" role="tab" aria-selected="true" aria-controls="detail-content">座子详情</button>
+            <button id="candidate-tab" type="button" role="tab" aria-selected="false" aria-controls="candidate-content">选脚辅助</button>
+          </div>
+          <section id="detail-content" class="panel-content" role="tabpanel" aria-labelledby="detail-tab"></section>
+          <section id="candidate-content" class="panel-content" role="tabpanel" aria-labelledby="candidate-tab" hidden>
+            <div class="candidate-controls">
+              <label for="capability-select">目标能力</label>
+              <select id="capability-select">
+                <option value="uart_tx">UART TX</option>
+                <option value="uart_rx">UART RX</option>
+                <option value="pwm">PWM</option>
+                <option value="gpio_output">GPIO 输出</option>
+                <option value="gpio_input">GPIO 输入</option>
+                <option value="tach">转速输入</option>
+                <option value="fan_tach">风扇转速输入</option>
+                <option value="presence">在位检测</option>
+                <option value="gpio">通用 GPIO</option>
+              </select>
+            </div>
+            <div id="candidate-list" class="candidate-list"></div>
+          </section>
+        </aside>
+      </main>
+    </div>
+    <script type="module" src="app.js"></script>
+  </body>
+</html>

+ 569 - 0
tools/cpld_c_drive_audit.py

@@ -0,0 +1,569 @@
+"""Read-only inventory and archive comparison for CPLD-related C-drive paths."""
+
+from __future__ import annotations
+
+import argparse
+import ctypes
+import hashlib
+import json
+import os
+import re
+import stat
+import subprocess
+import sys
+import zipfile
+from dataclasses import dataclass, field
+from datetime import datetime, timezone
+from functools import lru_cache
+from pathlib import Path, PurePosixPath
+from typing import Any, Iterable, Iterator, Mapping, Sequence
+
+
+SCHEMA = "cpld-c-drive-audit-v1"
+CONFIG_SCHEMA = "cpld-c-drive-audit-config-v1"
+DEFAULT_CONFIG = Path(__file__).resolve().parents[1] / "config" / "cpld_c_drive_audit.json"
+MAX_MEMBER_BYTES = 8 * 1024 * 1024 * 1024
+REPARSE_ATTRIBUTE = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
+DEFAULT_CANDIDATE_PATTERNS = (
+    "cpld",
+    "p4",
+    "prod2u",
+    "temperature",
+    "normal",
+    "handoff",
+    "analysis",
+    "board",
+    "ct7428",
+    "fpga",
+)
+DEFAULT_PROTECTED_PATTERNS = (
+    "release",
+    "source",
+    "firmware",
+    "final-gate",
+    "rc1",
+    "sha256sums",
+    "license",
+    r"\.lic$",
+    "private",
+    "original",
+    r"hardware[-_ ]evidence",
+)
+
+
+@dataclass(frozen=True)
+class AuditConfig:
+    candidate_patterns: tuple[str, ...] = DEFAULT_CANDIDATE_PATTERNS
+    excluded_patterns: tuple[str, ...] = ()
+    protected_patterns: tuple[str, ...] = DEFAULT_PROTECTED_PATTERNS
+    max_files: int = 100_000
+    root_scopes: Mapping[str, str] = field(default_factory=dict)
+
+    @classmethod
+    def from_mapping(cls, payload: Mapping[str, Any]) -> "AuditConfig":
+        if payload.get("schema") not in (None, CONFIG_SCHEMA):
+            raise ValueError(f"unsupported audit config schema: {payload.get('schema')!r}")
+        roots = payload.get("scan_roots", [])
+        scopes = {
+            str(Path(item["path"]).resolve()): str(item.get("scope", "configured_root"))
+            for item in roots
+            if isinstance(item, Mapping) and item.get("path")
+        }
+        return cls(
+            candidate_patterns=tuple(str(item) for item in payload.get("candidate_patterns", DEFAULT_CANDIDATE_PATTERNS)),
+            excluded_patterns=tuple(str(item) for item in payload.get("excluded_patterns", ())),
+            protected_patterns=tuple(str(item) for item in payload.get("protected_patterns", DEFAULT_PROTECTED_PATTERNS)),
+            max_files=max(1, int(payload.get("max_files", 100_000))),
+            root_scopes=scopes,
+        )
+
+
+def _now() -> str:
+    return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def _matches(value: str, patterns: Sequence[str]) -> bool:
+    for pattern in patterns:
+        try:
+            if re.search(pattern, value, flags=re.IGNORECASE):
+                return True
+        except re.error:
+            if pattern.casefold() in value.casefold():
+                return True
+    return False
+
+
+def _is_reparse(path: Path, file_stat: os.stat_result | None = None) -> bool:
+    if path.is_symlink():
+        return True
+    try:
+        value = file_stat if file_stat is not None else path.stat(follow_symlinks=False)
+        return bool(getattr(value, "st_file_attributes", 0) & REPARSE_ATTRIBUTE)
+    except OSError:
+        return False
+
+
+def _safe_resolve(path: Path) -> Path:
+    try:
+        return path.resolve(strict=False)
+    except OSError:
+        return Path(os.path.abspath(os.fspath(path)))
+
+
+def _absolute_path(path: Path) -> Path:
+    raw = os.fspath(path)
+    if not os.path.isabs(raw):
+        raw = os.path.abspath(raw)
+    if os.name != "nt":
+        return Path(raw)
+    buffer = ctypes.create_unicode_buffer(32768)
+    length = ctypes.windll.kernel32.GetFullPathNameW(raw, len(buffer), buffer, None)
+    if not length:
+        return Path(raw)
+    full = buffer.value[:length]
+    long_buffer = ctypes.create_unicode_buffer(32768)
+    long_length = ctypes.windll.kernel32.GetLongPathNameW(full, long_buffer, len(long_buffer))
+    return Path(long_buffer.value[:long_length] if long_length else full)
+
+
+def _sha256(path: Path) -> str:
+    digest = hashlib.sha256()
+    with path.open("rb") as handle:
+        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+            digest.update(chunk)
+    return digest.hexdigest()
+
+
+def _git_anchor(path: Path) -> Path | None:
+    current = path if path.is_dir() else path.parent
+    for candidate in (current, *current.parents):
+        try:
+            if (candidate / ".git").exists() or (candidate / ".git").is_file():
+                return candidate
+        except OSError:
+            continue
+    return None
+
+
+@lru_cache(maxsize=256)
+def _git_context_for_anchor(anchor_value: str) -> tuple[str | None, bool, list[str]]:
+    anchor = Path(anchor_value)
+    if not anchor.exists():
+        return None, False, []
+    try:
+        top = subprocess.run(
+            ["git", "-C", str(anchor), "rev-parse", "--show-toplevel"],
+            check=True,
+            capture_output=True,
+            text=True,
+            timeout=10,
+        ).stdout.strip()
+        common_raw = subprocess.run(
+            ["git", "-C", str(anchor), "rev-parse", "--git-common-dir"],
+            check=True,
+            capture_output=True,
+            text=True,
+            timeout=10,
+        ).stdout.strip()
+        common = _safe_resolve(Path(common_raw) if os.path.isabs(common_raw) else Path(top) / common_raw)
+        status = subprocess.run(
+            ["git", "-C", str(anchor), "status", "--porcelain", "--untracked-files=all"],
+            check=True,
+            capture_output=True,
+            text=True,
+            timeout=20,
+        ).stdout
+    except (OSError, subprocess.SubprocessError):
+        return None, False, ["git_probe_failed"]
+    return str(common), bool(status.strip()), [f"git_worktree:{top}", f"git_common_dir:{common}"]
+
+
+def _git_context(path: Path) -> tuple[str | None, bool, list[str]]:
+    anchor = _git_anchor(path)
+    return _git_context_for_anchor(str(anchor)) if anchor is not None else (None, False, [])
+
+
+def _base_record(path: Path | None, *, size: int | None, sha256: str | None, classification: str,
+                 recommended_action: str, reason: str, reparse_point: bool = False,
+                 comparison_target: str | None = None, comparison_result: str = "not_compared",
+                 ownership_evidence: Iterable[str] = ()) -> dict[str, Any]:
+    resolved_path = _safe_resolve(path) if path is not None else None
+    absolute = str(_absolute_path(path)) if path is not None else None
+    resolved = str(resolved_path) if resolved_path is not None else None
+    git_common_dir, dirty, git_evidence = _git_context(path) if path is not None else (None, False, [])
+    evidence = list(dict.fromkeys([*ownership_evidence, *git_evidence]))
+    return {
+        "absolute_path": absolute,
+        "resolved_path": resolved,
+        "size": size,
+        "git_common_dir": git_common_dir,
+        "worktree_dirty": dirty,
+        "reparse_point": reparse_point,
+        "ownership_evidence": evidence,
+        "sha256": sha256,
+        "comparison_target": comparison_target,
+        "comparison_result": comparison_result,
+        "classification": classification,
+        "recommended_action": recommended_action,
+        "reason": reason,
+    }
+
+
+def _iter_files(root: Path, config: AuditConfig) -> Iterator[tuple[Path, os.stat_result, bool]]:
+    pending = [root]
+    while pending:
+        current = pending.pop()
+        try:
+            entries = list(os.scandir(current))
+        except OSError:
+            continue
+        for entry in sorted(entries, key=lambda item: item.name.casefold()):
+            path = Path(entry.path)
+            try:
+                file_stat = entry.stat(follow_symlinks=False)
+            except OSError:
+                continue
+            if _matches(str(path), config.excluded_patterns):
+                continue
+            reparse = _is_reparse(path, file_stat)
+            if entry.is_dir(follow_symlinks=False):
+                if reparse:
+                    yield path, file_stat, True
+                else:
+                    pending.append(path)
+                continue
+            yield path, file_stat, reparse
+
+
+def _record_file(
+    path: Path,
+    file_stat: os.stat_result,
+    reparse: bool,
+    config: AuditConfig,
+    *,
+    force_include: bool = False,
+) -> dict[str, Any] | None:
+    text = str(path)
+    if not force_include and not _matches(text, config.candidate_patterns):
+        return None
+    evidence = ["configured_root_scope" if force_include else "candidate_name_match"]
+    protected = _matches(text, config.protected_patterns)
+    if reparse:
+        return _base_record(
+            path,
+            size=int(file_stat.st_size),
+            sha256=None,
+            classification="reparse_point",
+            recommended_action="retain_and_review",
+            reason="reparse point was not followed or hashed",
+            reparse_point=True,
+            ownership_evidence=evidence,
+        )
+    try:
+        digest = _sha256(path)
+    except OSError as exc:
+        return _base_record(
+            path,
+            size=int(file_stat.st_size),
+            sha256=None,
+            classification="unreadable_cpld_related_file",
+            recommended_action="retain_and_review",
+            reason=f"sha256 failed: {exc}",
+            ownership_evidence=evidence,
+        )
+    if protected:
+        classification = "protected_asset"
+        action = "retain"
+        reason = "release/source/original/license/private or hardware evidence path"
+    elif path.suffix.casefold() in {".zip", ".7z", ".rar"}:
+        classification = "archive_candidate"
+        action = "review_with_compare_archives"
+        reason = "archive requires independent member/hash comparison before any disposal"
+    else:
+        classification = "cpld_related_file"
+        action = "review"
+        reason = "under a configured CPLD scope" if force_include else "matched configured CPLD/P4 name or path pattern"
+    return _base_record(
+        path,
+        size=int(file_stat.st_size),
+        sha256=digest,
+        classification=classification,
+        recommended_action=action,
+        reason=reason,
+        ownership_evidence=evidence,
+    )
+
+
+def scan_paths(paths: Sequence[Path], *, config: AuditConfig) -> dict[str, Any]:
+    records: list[dict[str, Any]] = []
+    visited = 0
+    root_names = [str(_safe_resolve(Path(path))) for path in paths]
+    for root_value in paths:
+        root = Path(root_value)
+        if not root.exists():
+            continue
+        root_scope = config.root_scopes.get(str(_safe_resolve(root)))
+        force_include = root_scope in {"cpld_workspace", "named_cpld_path"}
+        for path, file_stat, reparse in _iter_files(root, config):
+            visited += 1
+            if visited > config.max_files:
+                records.append(_base_record(
+                    root,
+                    size=None,
+                    sha256=None,
+                    classification="scan_limit",
+                    recommended_action="retain_and_review",
+                    reason=f"scan stopped after max_files={config.max_files}",
+                    ownership_evidence=("scan_limit",),
+                ))
+                break
+            record = _record_file(path, file_stat, reparse, config, force_include=force_include)
+            if record is not None:
+                records.append(record)
+    records.sort(key=lambda item: str(item["absolute_path"]).casefold())
+    return {
+        "schema": SCHEMA,
+        "command": "scan",
+        "generated_at": _now(),
+        "roots": root_names,
+        "records": records,
+    }
+
+
+def _normalize_member(name: str) -> str | None:
+    normalized = name.replace("\\", "/")
+    path = PurePosixPath(normalized)
+    if not normalized or normalized.startswith("/") or re.match(r"^[A-Za-z]:", normalized):
+        return None
+    if any(part in {"", ".", ".."} for part in path.parts):
+        return None
+    return "/".join(path.parts)
+
+
+def _directory_files(root: Path) -> dict[str, Path]:
+    files: dict[str, Path] = {}
+    for path in root.rglob("*"):
+        if not path.is_file() or _is_reparse(path):
+            continue
+        relative = "/".join(path.relative_to(root).parts).casefold()
+        files[relative] = path
+    return files
+
+
+def _archive_member_hash(handle: zipfile.ZipFile, info: zipfile.ZipInfo) -> tuple[int, str]:
+    if info.file_size > MAX_MEMBER_BYTES:
+        raise ValueError("archive member exceeds audit size budget")
+    digest = hashlib.sha256()
+    size = 0
+    with handle.open(info, "r") as stream:
+        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
+            size += len(chunk)
+            digest.update(chunk)
+    return size, digest.hexdigest()
+
+
+def compare_archive(archive: Path, directory: Path, *, config: AuditConfig | None = None) -> dict[str, Any]:
+    config = config or AuditConfig()
+    archive = Path(archive)
+    directory = Path(directory)
+    archive_record = _base_record(
+        archive,
+        size=archive.stat().st_size if archive.is_file() else None,
+        sha256=_sha256(archive) if archive.is_file() else None,
+        classification="protected_archive" if _matches(str(archive), config.protected_patterns) else "archive_candidate",
+        recommended_action="retain",
+        reason="archive under independent comparison",
+        ownership_evidence=("archive_input",),
+    )
+    directory_record = _base_record(
+        directory,
+        size=None,
+        sha256=None,
+        classification="comparison_directory",
+        recommended_action="retain",
+        reason="directory used as independent archive comparison target",
+        ownership_evidence=("comparison_input",),
+    )
+    members: list[dict[str, Any]] = []
+    unsafe = False
+    target_files = _directory_files(directory) if directory.is_dir() else {}
+    seen: set[str] = set()
+    try:
+        with zipfile.ZipFile(archive) as handle:
+            for info in handle.infolist():
+                normalized = _normalize_member(info.filename)
+                if normalized is None or normalized.casefold() in seen:
+                    unsafe = True
+                    members.append({
+                        **_base_record(
+                            None,
+                            size=info.file_size,
+                            sha256=None,
+                            classification="unsafe_archive_member",
+                            recommended_action="retain",
+                            reason="absolute, traversal, empty, or duplicate archive member path",
+                            ownership_evidence=("zip_member_path_rejected",),
+                            comparison_result="unsafe_member",
+                        ),
+                        "member_path": info.filename,
+                        "target_size": None,
+                    })
+                    continue
+                seen.add(normalized.casefold())
+                if info.is_dir() or info.filename.endswith(("/", "\\")):
+                    members.append({
+                        **_base_record(
+                            directory / normalized,
+                            size=0,
+                            sha256=None,
+                            classification="archive_directory_member",
+                            recommended_action="review",
+                            reason="directory entry does not require file hash coverage",
+                            comparison_result="directory_entry",
+                            ownership_evidence=("zip_directory_member",),
+                        ),
+                        "member_path": info.filename,
+                        "target_size": None,
+                    })
+                    continue
+                try:
+                    member_size, member_hash = _archive_member_hash(handle, info)
+                except (OSError, ValueError, zipfile.BadZipFile) as exc:
+                    unsafe = True
+                    members.append({
+                        **_base_record(
+                            None,
+                            size=info.file_size,
+                            sha256=None,
+                            classification="unsafe_archive_member",
+                            recommended_action="retain",
+                            reason=f"archive member could not be independently hashed: {exc}",
+                            ownership_evidence=("zip_member_hash_failed",),
+                            comparison_result="unsafe_member",
+                        ),
+                        "member_path": info.filename,
+                        "target_size": None,
+                    })
+                    continue
+                target = target_files.get(normalized.casefold())
+                if target is None:
+                    result = "missing"
+                    target_size = None
+                    target_path = None
+                else:
+                    target_size = target.stat().st_size
+                    target_path = target
+                    if target_size != member_size:
+                        result = "size_mismatch"
+                    elif _sha256(target) != member_hash:
+                        result = "sha256_mismatch"
+                    else:
+                        result = "covered_match"
+                if result != "covered_match":
+                    unsafe = False if result in {"missing", "size_mismatch", "sha256_mismatch"} else unsafe
+                members.append({
+                    **_base_record(
+                        target_path,
+                        size=member_size,
+                        sha256=member_hash,
+                        classification="archive_member",
+                        recommended_action="review",
+                        reason="member compared by normalized path, size, and SHA-256",
+                        comparison_target=str(target_path.resolve()) if target_path is not None else None,
+                        comparison_result=result,
+                        ownership_evidence=("zip_member_hash",),
+                    ),
+                    "member_path": info.filename,
+                    "target_size": int(target_size) if target_size is not None else None,
+                })
+    except (OSError, zipfile.BadZipFile) as exc:
+        unsafe = True
+        members.append({
+            **_base_record(
+                archive,
+                size=archive_record["size"],
+                sha256=archive_record["sha256"],
+                classification="unreadable_archive",
+                recommended_action="retain",
+                reason=f"archive could not be read: {exc}",
+                comparison_result="unsafe_member",
+                ownership_evidence=("zip_open_failed",),
+            ),
+            "member_path": "",
+            "target_size": None,
+        })
+    all_match = bool(members) and all(item["comparison_result"] in {"covered_match", "directory_entry"} for item in members)
+    protected = _matches(str(archive), config.protected_patterns)
+    if unsafe:
+        status = "unsafe"
+        action = "retain"
+    elif all_match and protected:
+        status = "full_coverage"
+        action = "retain_protected_archive"
+    elif all_match:
+        status = "full_coverage"
+        action = "delete_archive_after_verification"
+    else:
+        status = "mismatch"
+        action = "retain"
+    archive_record["comparison_target"] = str(directory.resolve())
+    archive_record["comparison_result"] = status
+    archive_record["recommended_action"] = action
+    return {
+        "schema": SCHEMA,
+        "command": "compare-archives",
+        "generated_at": _now(),
+        "archive": archive_record,
+        "directory": directory_record,
+        "comparison": {"status": status, "recommended_action": action, "members": members},
+    }
+
+
+def load_config(path: Path) -> tuple[AuditConfig, list[Path]]:
+    payload = json.loads(Path(path).read_text(encoding="utf-8"))
+    config = AuditConfig.from_mapping(payload)
+    roots = [Path(str(item["path"])) for item in payload.get("scan_roots", []) if isinstance(item, Mapping) and item.get("path")]
+    return config, roots
+
+
+def build_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(description="Read-only CPLD C-drive audit")
+    subparsers = parser.add_subparsers(dest="command", required=True)
+    scan = subparsers.add_parser("scan", help="scan configured roots and emit JSON inventory")
+    scan.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
+    scan.add_argument("--root", action="append", type=Path, help="override configured scan roots; repeatable")
+    scan.add_argument("--output", type=Path, help="write JSON report to this path")
+    compare = subparsers.add_parser("compare-archives", help="compare ZIP members with an extracted directory")
+    compare.add_argument("--archive", type=Path, required=True)
+    compare.add_argument("--directory", type=Path, required=True)
+    compare.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
+    compare.add_argument("--output", type=Path, help="write JSON report to this path")
+    return parser
+
+
+def _emit(payload: Mapping[str, Any], output: Path | None) -> None:
+    encoded = json.dumps(payload, ensure_ascii=False, indent=2) + "\n"
+    if output is None:
+        sys.stdout.write(encoded)
+    else:
+        output.parent.mkdir(parents=True, exist_ok=True)
+        output.write_text(encoded, encoding="utf-8", newline="\n")
+
+
+def main(argv: Sequence[str] | None = None) -> int:
+    args = build_parser().parse_args(argv)
+    try:
+        config, configured_roots = load_config(args.config)
+        if args.command == "scan":
+            roots = args.root if args.root else configured_roots
+            _emit(scan_paths(roots, config=config), args.output)
+        else:
+            _emit(compare_archive(args.archive, args.directory, config=config), args.output)
+    except (OSError, ValueError, json.JSONDecodeError) as exc:
+        print(f"cpld-c-drive-audit: fail: {exc}", file=sys.stderr)
+        return 2
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 203 - 0
tools/package_agent_handoff.ps1

@@ -0,0 +1,203 @@
+<#
+.SYNOPSIS
+Creates a sanitized, evidence-aware CPLD workspace archive for another agent.
+
+.EXAMPLE
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File tools\package_agent_handoff.ps1 -AuditOnly
+
+.EXAMPLE
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File tools\package_agent_handoff.ps1 -OutputDir C:\handoff
+#>
+
+param(
+    [string]$SourceRoot = "",
+    [string]$OutputDir = "",
+    [string]$PackageName = "",
+    [switch]$ForceOverwrite,
+    [switch]$AuditOnly
+)
+
+$ErrorActionPreference = "Stop"
+
+if (-not ("AgentHandoff.NativePath" -as [type])) {
+    Add-Type -TypeDefinition @"
+using System;
+using System.ComponentModel;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Text;
+using Microsoft.Win32.SafeHandles;
+
+namespace AgentHandoff
+{
+    public static class NativePath
+    {
+        private const uint FileShareRead = 0x00000001;
+        private const uint FileShareWrite = 0x00000002;
+        private const uint FileShareDelete = 0x00000004;
+        private const uint OpenExisting = 3;
+        private const uint FileFlagBackupSemantics = 0x02000000;
+
+        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+        private static extern SafeFileHandle CreateFile(
+            string fileName,
+            uint desiredAccess,
+            uint shareMode,
+            IntPtr securityAttributes,
+            uint creationDisposition,
+            uint flagsAndAttributes,
+            IntPtr templateFile);
+
+        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+        private static extern uint GetFinalPathNameByHandle(
+            SafeFileHandle file,
+            StringBuilder filePath,
+            uint filePathLength,
+            uint flags);
+
+        public static string Resolve(string path)
+        {
+            string fullPath = Path.GetFullPath(path);
+            using (SafeFileHandle handle = CreateFile(
+                fullPath,
+                0,
+                FileShareRead | FileShareWrite | FileShareDelete,
+                IntPtr.Zero,
+                OpenExisting,
+                FileFlagBackupSemantics,
+                IntPtr.Zero))
+            {
+                if (handle.IsInvalid)
+                {
+                    throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to open path for final-path resolution");
+                }
+
+                StringBuilder buffer = new StringBuilder(512);
+                uint length = GetFinalPathNameByHandle(handle, buffer, (uint)buffer.Capacity, 0);
+                if (length == 0)
+                {
+                    throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to resolve final path");
+                }
+                if (length >= buffer.Capacity)
+                {
+                    buffer.Capacity = checked((int)length + 1);
+                    length = GetFinalPathNameByHandle(handle, buffer, (uint)buffer.Capacity, 0);
+                    if (length == 0 || length >= buffer.Capacity)
+                    {
+                        throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to resolve final path");
+                    }
+                }
+
+                string resolved = buffer.ToString();
+                if (resolved.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase))
+                {
+                    return @"\\" + resolved.Substring(8);
+                }
+                if (resolved.StartsWith(@"\\?\", StringComparison.OrdinalIgnoreCase))
+                {
+                    return resolved.Substring(4);
+                }
+                return resolved;
+            }
+        }
+    }
+}
+"@ -ErrorAction Stop
+}
+
+function Resolve-FinalPath {
+    param([string]$Path)
+    return [AgentHandoff.NativePath]::Resolve($Path)
+}
+
+$repo = Resolve-FinalPath (
+    (Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path))
+)
+$core = Join-Path $repo "tools\package_agent_handoff.py"
+$effectiveSourceRoot = if ($SourceRoot) {
+    Resolve-FinalPath $SourceRoot
+}
+else {
+    $repo
+}
+$pythonIsolationFlags = @("-I", "-S", "-B")
+
+function Test-PathWithinRoot {
+    param(
+        [string]$Path,
+        [string]$Root
+    )
+    $fullPath = [System.IO.Path]::GetFullPath($Path)
+    $fullRoot = [System.IO.Path]::GetFullPath($Root)
+    if ([string]::Equals($fullPath, $fullRoot, [System.StringComparison]::OrdinalIgnoreCase)) {
+        return $true
+    }
+    if (-not $fullRoot.EndsWith([System.IO.Path]::DirectorySeparatorChar)) {
+        $fullRoot += [System.IO.Path]::DirectorySeparatorChar
+    }
+    return $fullPath.StartsWith($fullRoot, [System.StringComparison]::OrdinalIgnoreCase)
+}
+
+function Test-ExternalPythonCandidate {
+    param([string]$Executable)
+    if (-not (Test-Path -LiteralPath $Executable -PathType Leaf)) {
+        return $false
+    }
+    try {
+        $candidatePath = Resolve-FinalPath $Executable
+    }
+    catch {
+        return $false
+    }
+    return -not (
+        (Test-PathWithinRoot -Path $candidatePath -Root $repo) -or
+        (Test-PathWithinRoot -Path $candidatePath -Root $effectiveSourceRoot)
+    )
+}
+
+function Test-Python311 {
+    param(
+        [string]$Executable,
+        [string[]]$Prefix
+    )
+    try {
+        & $Executable @Prefix @pythonIsolationFlags -c "import sys; raise SystemExit(0 if sys.version_info >= (3, 11) else 1)" *> $null
+        return $LASTEXITCODE -eq 0
+    }
+    catch {
+        return $false
+    }
+}
+
+function Resolve-Python311 {
+    $candidates = @()
+    $python = Get-Command python.exe -ErrorAction SilentlyContinue
+    if (-not $python) { $python = Get-Command python -ErrorAction SilentlyContinue }
+    if ($python) { $candidates += ,([ordered]@{ exe = $python.Source; prefix = @() }) }
+    $py = Get-Command py.exe -ErrorAction SilentlyContinue
+    if ($py) { $candidates += ,([ordered]@{ exe = $py.Source; prefix = @("-3") }) }
+    foreach ($candidate in $candidates) {
+        if (-not (Test-ExternalPythonCandidate -Executable $candidate.exe)) {
+            continue
+        }
+        if (Test-Python311 -Executable $candidate.exe -Prefix $candidate.prefix) {
+            return $candidate
+        }
+    }
+    throw "Python 3.11 or newer is required to create the agent handoff package"
+}
+
+if (-not (Test-Path -LiteralPath $core -PathType Leaf)) {
+    throw "Agent handoff packager core is missing: $core"
+}
+
+$python311 = Resolve-Python311
+$arguments = @($python311.prefix) + $pythonIsolationFlags + @($core)
+if ($SourceRoot) { $arguments += @("--source-root", $SourceRoot) }
+if ($OutputDir) { $arguments += @("--output-dir", $OutputDir) }
+if ($PackageName) { $arguments += @("--package-name", $PackageName) }
+if ($ForceOverwrite) { $arguments += "--force-overwrite" }
+if ($AuditOnly) { $arguments += "--audit-only" }
+
+& $python311.exe @arguments
+exit $LASTEXITCODE

Разница между файлами не показана из-за своего большого размера
+ 1639 - 0
tools/package_agent_handoff.py


+ 621 - 0
tools/pin_inventory.py

@@ -0,0 +1,621 @@
+#!/usr/bin/env python3
+"""Pin inventory, IO budget, and ADC guardrails for UART/RS232 migration."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+LOCKED_DEBUG_UART_ASSIGNMENTS = {
+    "bmc_uart_tx": "T4",
+    "bmc_uart_rx": "R5",
+    "host_uart_tx": "P7",
+    "host_uart_rx": "P8",
+    "debug_uart_rx": "P10",
+    "debug_uart_tx": "R10",
+}
+
+TEMP_UART_PTC_REMAP_SUBSTITUTIONS = {
+    "PTC03": {"signal": "ptc_pwm_out[2]", "substitute_ball": "P5", "bank_io_net": "BANK2_GPIO40"},
+    "PTC04": {"signal": "ptc_pwm_out[3]", "substitute_ball": "T8", "bank_io_net": "BANK2_GPIO41"},
+    "PTC17": {"signal": "ptc_pwm_out[16]", "substitute_ball": "M14", "bank_io_net": "BANK2_GPIO42"},
+    "PTC18": {"signal": "ptc_pwm_out[17]", "substitute_ball": "M15", "bank_io_net": "BANK2_GPIO43"},
+    "PTC21": {"signal": "ptc_pwm_out[20]", "substitute_ball": "P15", "bank_io_net": "BANK2_GPIO44"},
+    "PTC22": {"signal": "ptc_pwm_out[21]", "substitute_ball": "N14", "bank_io_net": "BANK2_GPIO45"},
+}
+
+FORMAL_UART_ASSIGNMENTS = {
+    "bmc_uart_tx": "P5",
+    "bmc_uart_rx": "T8",
+    "host_uart_tx": "M14",
+    "host_uart_rx": "M15",
+    "debug_uart_rx": "P15",
+    "debug_uart_tx": "N14",
+}
+
+FORMAL_UART1_BMC_REPLAY_ASSIGNMENTS = {
+    "bmc_uart_tx": "L10",
+    "bmc_uart_rx": "M9",
+    "host_uart_tx": "M10",
+    "host_uart_rx": "N11",
+    "debug_uart_rx": "P15",
+    "debug_uart_tx": "N14",
+}
+
+FORMAL_UART1_BMC_REPLAY_BINARY921_ASSIGNMENTS = {
+    "bmc_uart_tx": "L10",
+    "bmc_uart_rx": "M9",
+    "host_uart_tx": "M10",
+    "host_uart_rx": "N11",
+    "debug_uart_rx": "M14",
+    "debug_uart_tx": "M15",
+}
+
+PRODUCTION_TWO_UART_BMC_REPLAY_BINARY921_ASSIGNMENTS = {
+    "bmc_uart_tx": "L10",
+    "bmc_uart_rx": "M9",
+    "host_uart_tx": "M10",
+    "host_uart_rx": "N11",
+}
+
+RESERVED_FUTURE_UART_SIGNALS = ["UART1_TX", "UART1_RX", "UART2_TX", "UART2_RX"]
+
+REQUIRED_IO_GROUPS = [
+    {"name": "ptc_pwm[23:0]", "count": 24, "reason": "24 HEAT/PTC PWM outputs"},
+    {"name": "fan_pwm[3:0]", "count": 4, "reason": "4 FAN_PWM drive outputs"},
+    {"name": "fan_fg[7:0]", "count": 8, "reason": "8 FAN_FG tachometer inputs"},
+    {"name": "fan_install[3:0]", "count": 4, "reason": "4 FAN_INSTALL presence inputs"},
+    {"name": "bmc_uart(rx,tx)", "count": 2, "reason": "temporary J6 BMC UART debug wiring"},
+    {"name": "debug_uart(rx,tx)", "count": 2, "reason": "temporary COM7 P10/R10 debug UART"},
+    {"name": "host_uart(rx,tx)", "count": 2, "reason": "temporary COM8 P7/P8 host-control UART"},
+]
+
+
+def utc_now() -> str:
+    return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
+
+
+def load_pin_inventory(path: Path | str) -> dict[str, Any]:
+    inventory_path = Path(path)
+    return json.loads(inventory_path.read_text(encoding="utf-8"))
+
+
+def _available_gpio_pins(inventory: dict[str, Any]) -> list[dict[str, Any]]:
+    pins = []
+    for pin in inventory.get("pins", []):
+        capabilities = set(pin.get("capability") or [])
+        role = pin.get("role")
+        if pin.get("reserved"):
+            continue
+        if role not in {"user_io", "HEAT", "FAN_PWM", "FAN_FG", "FAN_INSTALL"}:
+            continue
+        if "gpio" not in capabilities:
+            continue
+        pins.append(pin)
+    return pins
+
+
+def build_io_budget(inventory: dict[str, Any]) -> dict[str, Any]:
+    required_total = sum(int(item["count"]) for item in REQUIRED_IO_GROUPS)
+    available_gpio = _available_gpio_pins(inventory)
+    verified_gpio = [pin for pin in available_gpio if pin.get("manually_verified") is True]
+    required_groups = {item["name"]: {"count": item["count"], "reason": item["reason"]} for item in REQUIRED_IO_GROUPS}
+
+    locked_conflicts = check_locked_uart_conflicts(inventory)
+
+    if inventory.get("status") == "product_pin_map_missing":
+        status = "blocked_product_pin_map_missing"
+    elif locked_conflicts["status"] != "pass":
+        status = locked_conflicts["status"]
+    elif len(verified_gpio) < required_total:
+        status = "blocked_unverified_or_insufficient_io"
+    else:
+        status = "pass"
+
+    return {
+        "schema": "cpld-io-budget-v1",
+        "generated_at": utc_now(),
+        "board_id": inventory.get("board_id"),
+        "status": status,
+        "required_groups": required_groups,
+        "required_signals_total": required_total,
+        "available_gpio_count": len(available_gpio),
+        "verified_gpio_count": len(verified_gpio),
+        "product_thermal_gate_allowed": bool(inventory.get("product_thermal_gate_allowed")),
+        "locked_uart_conflicts": locked_conflicts["conflicts"],
+        "authority_boundary": "Budget proves only signal count feasibility. It does not prove connector orientation, voltage, current drive, or product thermal safety.",
+    }
+
+
+def real_fan_ptc_assignments(inventory: dict[str, Any]) -> dict[str, str]:
+    assignments: dict[str, str] = {}
+    for pin in inventory.get("pins", []):
+        signal = str(pin.get("signal") or "")
+        ball = str(pin.get("fpga_ball") or "")
+        if not signal or not ball:
+            continue
+        role = str(pin.get("role") or "")
+        channel = int(pin.get("channel") or 0)
+        if role == "HEAT" and 1 <= channel <= 24:
+            assignments[f"ptc_pwm_out[{channel - 1}]"] = ball
+        elif role == "FAN_PWM" and 1 <= channel <= 4:
+            assignments[f"fan_pwm_out[{channel - 1}]"] = ball
+        elif role == "FAN_FG" and 1 <= channel <= 8:
+            assignments[f"fan_fg_in[{channel - 1}]"] = ball
+        elif role == "FAN_INSTALL" and 1 <= channel <= 4:
+            assignments[f"fan_install_in[{channel - 1}]"] = ball
+    return dict(sorted(assignments.items()))
+
+
+def check_locked_uart_conflicts(inventory: dict[str, Any]) -> dict[str, Any]:
+    locked_by_ball = {ball: signal for signal, ball in LOCKED_DEBUG_UART_ASSIGNMENTS.items()}
+    conflicts: list[dict[str, Any]] = []
+    for pin in inventory.get("pins", []):
+        ball = str(pin.get("fpga_ball") or "")
+        if ball not in locked_by_ball:
+            continue
+        role = str(pin.get("role") or "")
+        if role not in {"HEAT", "FAN_PWM", "FAN_FG", "FAN_INSTALL"}:
+            continue
+        conflicts.append(
+            {
+                "function_net": pin.get("function_net") or pin.get("signal"),
+                "signal": pin.get("signal"),
+                "role": role,
+                "channel": pin.get("channel"),
+                "fpga_ball": ball,
+                "locked_signal": locked_by_ball[ball],
+                "bank_io_net": pin.get("bank_io_net"),
+                "source_pages": pin.get("source_pages"),
+            }
+        )
+
+    return {
+        "schema": "cpld-locked-uart-conflict-check-v1",
+        "generated_at": utc_now(),
+        "board_id": inventory.get("board_id"),
+        "locked_uart_assignments": LOCKED_DEBUG_UART_ASSIGNMENTS,
+        "status": "blocked_pin_conflict_with_locked_debug_uart" if conflicts else "pass",
+        "conflicts": conflicts,
+        "authority_boundary": "A real FAN/PTC bitstream cannot bind a schematic function and a locked temporary UART to the same FPGA ball.",
+    }
+
+
+def _pin_by_ball(inventory: dict[str, Any]) -> dict[str, dict[str, Any]]:
+    return {str(pin.get("fpga_ball")): pin for pin in inventory.get("pins", []) if pin.get("fpga_ball")}
+
+
+def _pin_by_signal(inventory: dict[str, Any]) -> dict[str, dict[str, Any]]:
+    return {str(pin.get("signal")): pin for pin in inventory.get("pins", []) if pin.get("signal")}
+
+
+def _pin_ref(pin: dict[str, Any] | None, *, role: str | None = None) -> dict[str, Any]:
+    if pin is None:
+        return {"status": "missing"}
+    payload: dict[str, Any] = {
+        "signal": pin.get("signal"),
+        "function_net": pin.get("function_net"),
+        "bank_io_net": pin.get("bank_io_net"),
+        "fpga_ball": pin.get("fpga_ball"),
+        "role": role or pin.get("role"),
+        "direction": pin.get("direction"),
+        "io_standard": pin.get("io_standard"),
+        "source_pages": pin.get("source_pages"),
+        "manually_verified": pin.get("manually_verified") is True,
+        "reserved": pin.get("reserved") is True,
+    }
+    if pin.get("capability") is not None:
+        payload["capability"] = pin.get("capability")
+    return payload
+
+
+def _reserved_future_uart(inventory: dict[str, Any]) -> dict[str, dict[str, Any]]:
+    pins_by_signal = _pin_by_signal(inventory)
+    return {name: _pin_ref(pins_by_signal.get(name), role="reserved_future_uart") for name in RESERVED_FUTURE_UART_SIGNALS}
+
+
+def _uart_assignment_rows(
+    inventory: dict[str, Any],
+    assignments: dict[str, str],
+    *,
+    aliases: dict[str, str] | None = None,
+) -> dict[str, dict[str, Any]]:
+    pins_by_ball = _pin_by_ball(inventory)
+    rows: dict[str, dict[str, Any]] = {}
+    for signal, ball in assignments.items():
+        pin = pins_by_ball.get(ball)
+        rows[signal] = _pin_ref(pin, role="uart")
+        rows[signal]["fpga_ball"] = ball
+    for alias, signal in (aliases or {}).items():
+        if signal not in assignments:
+            continue
+        ball = assignments[signal]
+        pin = pins_by_ball.get(ball)
+        rows[alias] = _pin_ref(pin, role="uart")
+        rows[alias]["fpga_ball"] = ball
+        rows[alias]["hdl_signal"] = signal
+    return rows
+
+
+def _ptc_substitution_rows(
+    inventory: dict[str, Any],
+    assignments: dict[str, str],
+    *,
+    reason: str = "temporary_uart_overlap_remap",
+) -> dict[str, dict[str, Any]]:
+    real_assignments = real_fan_ptc_assignments(inventory)
+    pins_by_ball = _pin_by_ball(inventory)
+    rows: dict[str, dict[str, Any]] = {}
+    for label, subst in TEMP_UART_PTC_REMAP_SUBSTITUTIONS.items():
+        signal = subst["signal"]
+        original_ball = real_assignments.get(signal)
+        substitute_ball = subst["substitute_ball"]
+        rows[label] = {
+            "signal": signal,
+            "function_net": f"HEAT{int(label[3:])}",
+            "original_ball": original_ball,
+            "substitute_ball": substitute_ball,
+            "substitute_bank_io_net": subst["bank_io_net"],
+            "active_ball": assignments.get(signal),
+            "substitute_pin": _pin_ref(pins_by_ball.get(substitute_ball), role="HEAT_substitute"),
+            "reason": reason,
+        }
+    return rows
+
+
+def diagnostic_profile_assignments(inventory: dict[str, Any], profile: str) -> dict[str, Any]:
+    """Return complete board assignments for the active diagnostic profiles."""
+    supported_profiles = {
+        "temp-uart-ptc-remap",
+        "formal-uart",
+        "debug-photo-uart-bmc-replay",
+        "formal-uart1-bmc-replay",
+        "debug-photo-bmc-replay-binary921",
+        "formal-uart1-bmc-replay-binary921",
+        "production-two-uart-bmc-replay-binary921",
+        "prod2u-bmc-replay-binary921",
+        "prod2u-fan-tach-binary921-v2",
+    }
+    if profile not in supported_profiles:
+        return {
+            "schema": "cpld-diagnostic-pin-profile-v1",
+            "generated_at": utc_now(),
+            "board_id": inventory.get("board_id"),
+            "profile": profile,
+            "status": "fail_unknown_profile",
+            "assignments": {},
+            "errors": [f"unknown_profile:{profile}"],
+        }
+
+    assignments = real_fan_ptc_assignments(inventory)
+    bmc_source = "live_bmc_j6_uart"
+    live_bmc_link_status = "used"
+    hardware_access_status = "not_run"
+    reserved_uart_use_policy = "reserved_unused"
+    uart_aliases: dict[str, str] = {}
+    allowed_reserved_balls: set[str] = set()
+    profile4_fan_tach = profile == "prod2u-fan-tach-binary921-v2"
+    production_profile = profile in {
+        "production-two-uart-bmc-replay-binary921",
+        "prod2u-bmc-replay-binary921",
+        "prod2u-fan-tach-binary921-v2",
+    }
+    if profile in {"temp-uart-ptc-remap", "debug-photo-uart-bmc-replay", "debug-photo-bmc-replay-binary921"}:
+        uart_assignments = dict(LOCKED_DEBUG_UART_ASSIGNMENTS)
+        for item in TEMP_UART_PTC_REMAP_SUBSTITUTIONS.values():
+            assignments[item["signal"]] = item["substitute_ball"]
+        substitution_reason = (
+            "photo_visible_uart_overlap_remap"
+            if profile in {"debug-photo-uart-bmc-replay", "debug-photo-bmc-replay-binary921"}
+            else "temporary_uart_overlap_remap"
+        )
+        ptc_substitutions = _ptc_substitution_rows(inventory, assignments, reason=substitution_reason)
+        hardware_status = "not_run"
+        if profile in {"debug-photo-uart-bmc-replay", "debug-photo-bmc-replay-binary921"}:
+            bmc_source = "pc_replay_from_real_bmc_capture"
+            live_bmc_link_status = "not_used"
+            hardware_access_status = "photo_visible_header"
+            uart_aliases = {
+                "bmc_replay_uart_tx": "bmc_uart_tx",
+                "bmc_replay_uart_rx": "bmc_uart_rx",
+            }
+            if profile == "debug-photo-bmc-replay-binary921":
+                boundary = (
+                    "BMC-replay debug-photo binary921 profile: photo-visible/current J6/COM7/COM8 UART wiring is kept, "
+                    "the CPLD BMC UART talks to a PC poll-response replay emulator instead of a live BMC, "
+                    "HostPort and DebugPort use binary921 machine frames, and six overlapping HEAT/PTC channels are moved to verified spare GPIO. "
+                    "It is debug-only and does not claim full real HEAT pinout pass."
+                )
+            else:
+                boundary = (
+                    "BMC-replay debug-photo profile: photo-visible/current J6/COM7/COM8 UART wiring is kept, "
+                    "the CPLD BMC UART talks to a PC poll-response replay emulator instead of a live BMC, "
+                    "and six overlapping HEAT/PTC channels are moved to verified spare GPIO. "
+                    "It is debug-only and does not claim full real HEAT pinout pass."
+                )
+        else:
+            boundary = (
+                "Temporary debug pin profile: current J6/COM7/COM8 UART wiring is kept, "
+                "and six overlapping HEAT/PTC channels are moved to verified spare GPIO for signal-level diagnostic use."
+            )
+    elif profile == "formal-uart":
+        uart_assignments = dict(FORMAL_UART_ASSIGNMENTS)
+        ptc_substitutions = {}
+        hardware_status = "not_run"
+        boundary = (
+            "Formal debug pin profile: all HEAT/PTC/FAN/FG/INSTALL pins use the schematic mapping, "
+            "and all three diagnostic UARTs move to verified spare GPIO; schematic UART1/2 are reserved unused."
+        )
+    else:
+        if production_profile:
+            uart_assignments = dict(PRODUCTION_TWO_UART_BMC_REPLAY_BINARY921_ASSIGNMENTS)
+        elif profile == "formal-uart1-bmc-replay-binary921":
+            uart_assignments = dict(FORMAL_UART1_BMC_REPLAY_BINARY921_ASSIGNMENTS)
+        else:
+            uart_assignments = dict(FORMAL_UART1_BMC_REPLAY_ASSIGNMENTS)
+        ptc_substitutions = {}
+        hardware_status = "not_run"
+        bmc_source = "pc_replay_from_real_bmc_capture"
+        live_bmc_link_status = "not_used"
+        hardware_access_status = (
+            "production_uart1_uart2_access_confirmed_by_user"
+            if production_profile
+            else "blocked_waiting_for_uart1_uart2_access"
+        )
+        reserved_uart_use_policy = "intentional_uart1_uart2_bmc_replay_host"
+        uart_aliases = {
+            "bmc_replay_uart_tx": "bmc_uart_tx",
+            "bmc_replay_uart_rx": "bmc_uart_rx",
+        }
+        if production_profile:
+            uart_aliases.update(
+                {
+                    "combined_debug_host_uart_tx": "host_uart_tx",
+                    "combined_debug_host_uart_rx": "host_uart_rx",
+                }
+            )
+        if profile4_fan_tach:
+            bmc_source = "out_of_scope"
+            live_bmc_link_status = "out_of_scope"
+            reserved_uart_use_policy = "intentional_uart1_idle_uart2_host"
+            uart_aliases = {
+                "idle_uart1_tx": "bmc_uart_tx",
+                "ignored_uart1_rx": "bmc_uart_rx",
+                "combined_debug_host_uart_tx": "host_uart_tx",
+                "combined_debug_host_uart_rx": "host_uart_rx",
+            }
+        allowed_reserved_balls = {"L10", "M9", "M10", "N11"}
+        if profile4_fan_tach:
+            boundary = (
+                "Prod2U Profile 4 production pin profile: HEAT/FAN/FG/INSTALL stay on the PDF/inventory pins, "
+                "UART2 M10/N11 is the combined Host+Debug binary921-v2 port, and UART1 L10/M9 is retained only "
+                "as an idle TX and ignored RX electrical boundary. BMC is out of scope. J3 is PROGRAM_SRAM-only. "
+                "It does not qualify RPM calibration, PWM electrical accuracy, PTC thermal performance, PID, flash, or nonvolatile programming."
+            )
+        elif production_profile:
+            boundary = (
+                "Production two-UART BMC-replay binary921 profile for J3 SRAM-only bring-up: HEAT/FAN/FG/INSTALL stay on PDF/inventory pins, "
+                "BMC replay uses UART1 L10/M9 at 115200, and a combined Host+Debug binary921 port uses UART2 M10/N11 at 921600. "
+                "The board is programmed through J3 with target board power present and PROGRAM_SRAM only; VREF is a reference, not board power. "
+                "It does not claim live BMC, flash, thermal performance, PID closed-loop, or real PTC/FAN load pass."
+            )
+        elif profile == "formal-uart1-bmc-replay-binary921":
+            boundary = (
+                "BMC-replay formal-uart1 binary921 profile: HEAT/FAN/FG/INSTALL stay on the schematic pins, "
+                "BMC replay uses UART1 L10/M9, HostPort uses UART2 M10/N11, DebugPort uses M14/M15 spare GPIO, "
+                "and HostPort/DebugPort use binary921 machine frames. "
+                "Photo evidence did not prove UART1/2 are physically accessible, so hardware access remains blocked until continuity/header access is verified."
+            )
+        else:
+            boundary = (
+                "BMC-replay formal-uart1 profile: HEAT/FAN/FG/INSTALL stay on the schematic pins, "
+                "BMC replay uses UART1 L10/M9, HostPort uses UART2 M10/N11, and DebugPort uses SPARE_GPIO44/45 "
+                "as TX=N14/RX=P15. "
+                "Photo evidence did not prove UART1/2 are physically accessible, so hardware access remains blocked until continuity/header access is verified."
+            )
+    assignments.update(uart_assignments)
+    conflict = check_pin_conflicts(inventory, assignments, allowed_reserved_balls=allowed_reserved_balls)
+    reserved_future_uart = _reserved_future_uart(inventory)
+    used_balls = {str(ball) for ball in assignments.values()}
+    reserved_balls = {
+        str(item.get("fpga_ball"))
+        for item in reserved_future_uart.values()
+        if item.get("fpga_ball")
+    }
+    uses_reserved_future_uart = bool(used_balls & reserved_balls)
+    errors = list(conflict.get("errors") or [])
+    allowed_reserved_policies = {
+        "intentional_uart1_uart2_bmc_replay_host",
+        "intentional_uart1_idle_uart2_host",
+    }
+    if uses_reserved_future_uart and reserved_uart_use_policy not in allowed_reserved_policies:
+        errors.append("uses_reserved_future_uart")
+    status = "pass" if conflict["status"] == "pass" and not errors else "fail"
+    return {
+        "schema": "cpld-diagnostic-pin-profile-v1",
+        "generated_at": utc_now(),
+        "board_id": inventory.get("board_id"),
+        "profile": profile,
+        "status": status,
+        "assignments": dict(sorted(assignments.items())),
+        "uart_assignments": _uart_assignment_rows(inventory, uart_assignments, aliases=uart_aliases),
+        "ptc_substitutions": ptc_substitutions,
+        "reserved_future_uart": reserved_future_uart,
+        "uses_reserved_future_uart": uses_reserved_future_uart,
+        "reserved_uart_use_policy": reserved_uart_use_policy,
+        "bmc_source": bmc_source,
+        "live_bmc_link_status": live_bmc_link_status,
+        "transport": "combined_host_debug_uart" if production_profile else "separate_host_debug_uart",
+        "hardware_access_status": hardware_access_status,
+        "real_fan_ptc_hardware_status": hardware_status,
+        "conflict_check": conflict,
+        "errors": sorted(set(errors)),
+        "authority_boundary": boundary,
+    }
+
+
+def check_pin_conflicts(
+    inventory: dict[str, Any],
+    assignments: dict[str, str],
+    *,
+    allowed_reserved_balls: set[str] | None = None,
+) -> dict[str, Any]:
+    pins = _pin_by_ball(inventory)
+    allowed_reserved_balls = allowed_reserved_balls or set()
+    seen: dict[str, str] = {}
+    errors: list[str] = []
+    warnings: list[str] = []
+    assignment_rows: list[dict[str, Any]] = []
+
+    for signal, ball in assignments.items():
+        ball_text = str(ball)
+        pin = pins.get(ball_text)
+        if ball_text in seen:
+            errors.append(f"duplicate_ball:{ball_text}")
+        seen[ball_text] = signal
+        if pin is None:
+            errors.append(f"unknown_ball:{ball_text}")
+            assignment_rows.append({"signal": signal, "fpga_ball": ball_text, "status": "unknown_ball"})
+            continue
+        capabilities = set(pin.get("capability") or [])
+        if (
+            (pin.get("reserved") and ball_text not in allowed_reserved_balls)
+            or pin.get("role") not in {"user_io", "HEAT", "FAN_PWM", "FAN_FG", "FAN_INSTALL"}
+            or "gpio" not in capabilities
+        ):
+            errors.append(f"reserved_or_not_gpio:{ball_text}")
+        if pin.get("manually_verified") is not True:
+            warnings.append(f"unverified_pin:{ball_text}")
+        assignment_rows.append(
+            {
+                "signal": signal,
+                "fpga_ball": ball_text,
+                "connector": pin.get("connector"),
+                "connector_pin": pin.get("connector_pin"),
+                "io_standard": pin.get("io_standard"),
+                "manually_verified": pin.get("manually_verified") is True,
+            }
+        )
+
+    return {
+        "schema": "cpld-pin-conflict-check-v1",
+        "generated_at": utc_now(),
+        "board_id": inventory.get("board_id"),
+        "status": "fail" if errors else "pass",
+        "assignments": assignment_rows,
+        "errors": sorted(set(errors)),
+        "warnings": sorted(set(warnings)),
+    }
+
+
+def generate_adc(
+    inventory: dict[str, Any],
+    *,
+    assignments: dict[str, str],
+    output: Path | str,
+    allow_unverified: bool = False,
+) -> dict[str, Any]:
+    conflict = check_pin_conflicts(inventory, assignments)
+    if conflict["errors"]:
+        return {"schema": "cpld-adc-generation-v1", "status": "fail_pin_conflict", "conflict": conflict}
+    if conflict["warnings"] and not allow_unverified:
+        return {"schema": "cpld-adc-generation-v1", "status": "blocked_unverified_pin_map", "conflict": conflict}
+
+    pins = _pin_by_ball(inventory)
+    lines = [
+        "# Generated by tools/pin_inventory.py",
+        f"# Board: {inventory.get('board_id')}",
+    ]
+    if conflict["warnings"]:
+        lines.append("# LAB_SMOKE_UNVERIFIED_PIN_MAP: connector orientation and schematic cross-check are still required.")
+    for signal, ball in assignments.items():
+        pin = pins[str(ball)]
+        io_standard = pin.get("io_standard") or "LVCMOS33"
+        lines.append(f"set_pin_assignment {{ {signal} }} {{ LOCATION = {ball}; IOSTANDARD = {io_standard}; PULLTYPE = NONE; }}")
+
+    output_path = Path(output)
+    output_path.parent.mkdir(parents=True, exist_ok=True)
+    output_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+    return {
+        "schema": "cpld-adc-generation-v1",
+        "status": "pass",
+        "path": str(output_path),
+        "conflict": conflict,
+        "allow_unverified": allow_unverified,
+        "authority_boundary": "Generated ADC is a candidate lab-smoke constraint only unless all pins are manually verified and product gate is explicitly enabled.",
+    }
+
+
+def _parse_assignments(items: list[str]) -> dict[str, str]:
+    assignments: dict[str, str] = {}
+    for item in items:
+        if "=" not in item:
+            raise ValueError(f"assignment must be signal=BALL: {item}")
+        signal, ball = item.split("=", 1)
+        assignments[signal.strip()] = ball.strip()
+    return assignments
+
+
+def build_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(description=__doc__)
+    sub = parser.add_subparsers(dest="command", required=True)
+
+    budget = sub.add_parser("budget")
+    budget.add_argument("--inventory", type=Path, default=ROOT / "config" / "pin_inventory.mini.json")
+    budget.add_argument("--json", action="store_true")
+    budget.set_defaults(func=cmd_budget)
+
+    conflict = sub.add_parser("conflict")
+    conflict.add_argument("--inventory", type=Path, default=ROOT / "config" / "pin_inventory.mini.json")
+    conflict.add_argument("--assign", action="append", default=[])
+    conflict.add_argument("--json", action="store_true")
+    conflict.set_defaults(func=cmd_conflict)
+
+    adc = sub.add_parser("generate-adc")
+    adc.add_argument("--inventory", type=Path, default=ROOT / "config" / "pin_inventory.mini.json")
+    adc.add_argument("--assign", action="append", default=[])
+    adc.add_argument("--output", type=Path, required=True)
+    adc.add_argument("--allow-unverified", action="store_true")
+    adc.add_argument("--json", action="store_true")
+    adc.set_defaults(func=cmd_generate_adc)
+    return parser
+
+
+def cmd_budget(args: argparse.Namespace) -> int:
+    payload = build_io_budget(load_pin_inventory(args.inventory))
+    print(json.dumps(payload, indent=2) if args.json else f"pin-budget: {payload['status']}")
+    return 0 if payload["status"] == "pass" else 1
+
+
+def cmd_conflict(args: argparse.Namespace) -> int:
+    payload = check_pin_conflicts(load_pin_inventory(args.inventory), _parse_assignments(args.assign))
+    print(json.dumps(payload, indent=2) if args.json else f"pin-conflict: {payload['status']}")
+    return 0 if payload["status"] == "pass" else 1
+
+
+def cmd_generate_adc(args: argparse.Namespace) -> int:
+    payload = generate_adc(
+        load_pin_inventory(args.inventory),
+        assignments=_parse_assignments(args.assign),
+        output=args.output,
+        allow_unverified=args.allow_unverified,
+    )
+    print(json.dumps(payload, indent=2) if args.json else f"generate-adc: {payload['status']}")
+    return 0 if payload["status"] == "pass" else 1
+
+
+def main(argv: list[str] | None = None) -> int:
+    return build_parser().parse_args(argv).func(build_parser().parse_args(argv))
+
+
+if __name__ == "__main__":
+    parser = build_parser()
+    parsed = parser.parse_args()
+    raise SystemExit(parsed.func(parsed))