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

fix(mse): Round-10 release tooling fail-closed and current evidence selection

Parse MSLICE from explicit packing/top-level fields instead of LUT fallback,
compare source-closure by production hashes, and select current matrix/Formal
by tip+run. Fail-close review/firmware selftest and release-validation; move
stale R8 canonical receipts to historical. Activity docs describe Round-10
truth without a self-referential delivery commit.

Co-authored-by: Cursor <cursoragent@cursor.com>
root 3 месяцев назад
Родитель
Сommit
c9e7e2b90d
30 измененных файлов с 1844 добавлено и 208 удалено
  1. 5 5
      ACCEPTANCE_MATRIX.md
  2. 15 12
      FINAL_DELIVERY_REPORT.md
  3. 6 5
      OPEN_QUESTIONS.md
  4. 9 8
      PLAN.md
  5. 9 9
      README.zh-CN.md
  6. 9 4
      config/review_compact_evidence_allowlist.json
  7. 6 5
      docs/TD_USAGE.zh-CN.md
  8. 99 12
      package_for_agent_analysis.py
  9. 0 0
      receipts/historical/r8-stale-canonical/FORMAL-CANON-PROMOTION.json
  10. 9 0
      receipts/historical/r8-stale-canonical/README.md
  11. 0 0
      receipts/historical/r8-stale-canonical/formal-receipt.json
  12. 0 0
      receipts/historical/r8-stale-canonical/receipts-current-formal-receipt.json
  13. 0 0
      receipts/historical/r8-stale-canonical/verification-matrix-final.json
  14. 53 0
      receipts/mse-r10-preaudit/five-audit.json
  15. 28 0
      tests/unit/test_activity_docs_truth.py
  16. 139 0
      tests/unit/test_build_firmware_package.py
  17. 7 2
      tests/unit/test_compact_package_selftest.py
  18. 243 0
      tests/unit/test_mse_r10_current_evidence.py
  19. 64 0
      tests/unit/test_mse_r10_release_validation.py
  20. 102 0
      tests/unit/test_mse_r10_td_resources.py
  21. 4 0
      tests/unit/test_mse_r9_td_identity.py
  22. 142 10
      tools/build_firmware_package.py
  23. 151 56
      tools/compact_package_selftest.py
  24. 52 0
      tools/cross_package_verify.py
  25. 387 0
      tools/current_evidence.py
  26. 2 0
      tools/package-review-compact.sh
  27. 1 0
      tools/package-review-debug.sh
  28. 3 0
      tools/package_evidence_canon.py
  29. 237 22
      tools/package_provenance.py
  30. 62 58
      tools/release_validation.py

+ 5 - 5
ACCEPTANCE_MATRIX.md

@@ -4,15 +4,15 @@
 
 
 | Lane | 要求 | 活动真相 |
 | Lane | 要求 | 活动真相 |
 |---|---|---|
 |---|---|---|
-| Python unit / exhaustive | pass,含 rate-builder | **pass** @ `21ed755…` / `mse-r7-20260812T132652Z` |
+| Python unit / exhaustive | pass,含 rate-builder 与 Round-10 发布负向测试 | 以当前 matrix tip 为准;R9 历史 pass @ `d126c3df…` / `mse-r9-20260812T163229Z` |
 | board-viewer | detached-derived PASS;`reference_regeneration_replay=not_packaged_by_policy` | 以当前 matrix tip 为准 |
 | board-viewer | detached-derived PASS;`reference_regeneration_replay=not_packaged_by_policy` | 以当前 matrix tip 为准 |
 | Icarus manifest | 全清单 pass;含 production-gate timing + overlap | 以当前 matrix tip 为准 |
 | Icarus manifest | 全清单 pass;含 production-gate timing + overlap | 以当前 matrix tip 为准 |
 | cocotb UART E2E | pass | 以当前 matrix tip 为准 |
 | cocotb UART E2E | pass | 以当前 matrix tip 为准 |
 | Verilator lint + Perl preflight | pass | 以当前 matrix tip 为准 |
 | Verilator lint + Perl preflight | pass | 以当前 matrix tip 为准 |
-| Formal | 23/23 targets + all tasks;dispatcher cover exact set 10/10 | current PASS receipt only |
-| TD binding | `ff44128a` exact 37/37/0/0;bitstream `b4b0eda4…` | reuse exact |
-| Activity docs | MSE A1 唯一权威(非 Round-6) | 本文件 |
-| Package / selftest / replay / crosscheck | final dual `mse-a1` 或诚实 intermediate | Round-8 |
+| Formal | 23/23 targets + all tasks;dispatcher cover exact set 10/10 | current PASS receipt only(由 tip+run 选择) |
+| TD binding | 历史 `ff44128a` 37/37/0/0 且 bitstream 字节已核验,**或** 本轮 fresh TD PASS | Branch B fresh `td2026`(`b4b0eda4…` 字节未恢复) |
+| Activity docs | MSE A1 唯一权威;R7 `21ed755…` / `mse-r7-20260812T132652Z` 与 R8 `3177c2f0…` 均为 historical | 本文件 |
+| Package / selftest / replay / crosscheck | final dual `mse-a1` 或诚实 intermediate | Round-10 |
 | Hardware | NOT RUN | NOT RUN |
 | Hardware | NOT RUN | NOT RUN |
 | `dev` | 不动 | locked `d4f3df25…` |
 | `dev` | 不动 | locked `d4f3df25…` |
 
 

+ 15 - 12
FINAL_DELIVERY_REPORT.md

@@ -1,4 +1,4 @@
-# FINAL_DELIVERY_REPORT — MSE A1(Round-8 release/provenance closure)
+# FINAL_DELIVERY_REPORT — MSE A1(Round-10 release/provenance closure)
 
 
 ## 身份
 ## 身份
 
 
@@ -6,9 +6,10 @@
 |---|---|
 |---|---|
 | base_dev_commit | `d4f3df2549efeb1e9227f62d1d71c6179c9f9160` |
 | base_dev_commit | `d4f3df2549efeb1e9227f62d1d71c6179c9f9160` |
 | branch | `preview/motor-shared-executor` |
 | branch | `preview/motor-shared-executor` |
-| td_bound_commit / artifact_source_commit | `ff44128a540b7ffd9d82314093b242ac3aee92d7` |
-| matrix_verification_tip | `21ed755ad2ddb6689bca88a9a037b391372a060e`(R7);新 tip 以 package identity 为准 |
-| verification_run_id | `mse-r7-20260812T132652Z` |
+| 当前软件 matrix_verification_tip / run | package-time identity(本轮 clean tip + `mse-r10-<UTC>`) |
+| 最近一次已完成软件矩阵(历史,将被本轮新 tip 取代) | R9 `d126c3df…` / `mse-r9-20260812T163229Z` |
+| R7/R8(历史,非 current) | `21ed755ad2ddb6689bca88a9a037b391372a060e` / `mse-r7-20260812T132652Z`;`3177c2f0…` |
+| 历史 td_bound / artifact_source | `ff44128a540b7ffd9d82314093b242ac3aee92d7` |
 | delivery_commit | package-time actual HEAD(`meta/release-set-identity.json` / closure) |
 | delivery_commit | package-time actual HEAD(`meta/release-set-identity.json` / closure) |
 | package stage | final-review(硬门全过)或 intermediate-review(诚实缺口) |
 | package stage | final-review(硬门全过)或 intermediate-review(诚实缺口) |
 | topic | `mse-a1` |
 | topic | `mse-a1` |
@@ -19,22 +20,24 @@
 - A2:**STOPPED**(已测 full-chip 配置 route `PHY-8155`;不换 seed / 不做 placement 黑魔法)。
 - A2:**STOPPED**(已测 full-chip 配置 route `PHY-8155`;不换 seed / 不做 placement 黑魔法)。
 - Scheme B:**STOPPED**(LUT 回归)。
 - Scheme B:**STOPPED**(LUT 回归)。
 
 
-## TD / 资源(复用 exact source-bound TD)
+## TD / 资源
 
 
-- Bitstream SHA-256:`b4b0eda4ee8d774109eff83b519bdaa19d5e73d770562983121a596df00952d0`
-- LUT 4320 / REG 1641 / MSLICE 1089 / DSP 1 / BRAM 0;Fmax ≈ 42.332 MHz;setup slack ≈ +16.377 ns
-- 生产 source closure 相对 `ff44128a`:**37/37/0/0** → 复用该 exact TD。
-- 扩展余量有限(≈96.43% LUT);可接受保留现状,不建议继续扩展。
+- 历史 A1 TD:bitstream `b4b0eda4ee8d774109eff83b519bdaa19d5e73d770562983121a596df00952d0`;LUT 4320 / MSLICE 1089 / DSP 1 / BRAM 0;Fmax ≈ 42.332 MHz。**实际字节未在磁盘恢复**。
+- 生产 source closure 相对 `ff44128a`:**37/37/0/0**。
+- 本轮 Branch B:在新 verification tip 上 fresh `td2026`。成功则新 TD 字段为 current;失败则保持 intermediate,不生成 firmware。
+- Round-12 tip TD(历史,非 current):`8403e020` / bitstream `e0cf1321` / LUT 2893。
 
 
 ## 协议与运动(活动)
 ## 协议与运动(活动)
 
 
 百分比门控、`0x03`/`0x83`、30 s watchdog、`startup_complete`、`latest-wins`、六限位、`truncate_current_high_pulse_immediately_after_synchronized_limit`、`permanent_high`、CON104/105/106/120/12/129、标定 ≤5000。
 百分比门控、`0x03`/`0x83`、30 s watchdog、`startup_complete`、`latest-wins`、六限位、`truncate_current_high_pulse_immediately_after_synchronized_limit`、`permanent_high`、CON104/105/106/120/12/129、标定 ≤5000。
 
 
-## Provenance 规则(Round-8)
+## Provenance 规则(Round-10)
 
 
-- `matrix_verification_tip` / `checked_delivery_commit` / `td_bound_commit` 三角色拆清,禁止把文档提交冒充 matrix tip。
+- current matrix / Formal 由显式 verification tip + run ID 选择;R7/R8 canonical 路径不得再当 current。
+- source-closure relations 按生产输入哈希,不按 commit 相等捷径。
+- MSLICE 不得回退为 LUT。
 - verification→delivery closure 在 **package time** 针对 actual HEAD 计算;不得自引用循环提交。
 - verification→delivery closure 在 **package time** 针对 actual HEAD 计算;不得自引用循环提交。
-- current Formal receipt 必须是当前 matrix PASS;stale FAIL 不得占 canonical 路径。
+- P0/P1 发布工具 fail-open 已修(release-validation sidecar、selftest 入口)。
 
 
 ## 状态
 ## 状态
 
 

+ 6 - 5
OPEN_QUESTIONS.md

@@ -4,15 +4,16 @@
 
 
 - 架构 winner:A1 frozen;A2 停止(PHY-8155 / 边界规则);Scheme B 退出。
 - 架构 winner:A1 frozen;A2 停止(PHY-8155 / 边界规则);Scheme B 退出。
 - 协议:百分比 + `0x03`/`0x83` + 30 s watchdog;破坏性全开语义已文档化。
 - 协议:百分比 + `0x03`/`0x83` + 30 s watchdog;破坏性全开语义已文档化。
-- TD 候选:`ff44128a` / bitstream `b4b0eda4…` / 4320 LUT / DSP 1 / 37/37 binding。
-- Round-7 软件统一矩阵(含 board-viewer detached-derived)在 tip `21ed755…` 上 **pass**;Round-8 在新 verification tip 重跑并收口 provenance。
-- 活动文档已换代为 MSE A1 当前真相(不再以 Round-6 为 current)。
+- Round-9 软件统一矩阵在 tip `d126c3df…` / `mse-r9-20260812T163229Z` 上 **pass**(历史;本轮新 tip 将取代其为 current)。
+- R7 `21ed755…` / `mse-r7-20260812T132652Z` 与 R8 `3177c2f0…` 已降为 historical,不再是 current。
+- 活动文档已换代为 MSE A1 Round-10 当前真相(不再以 Round-6 / Round-8 文档为 current)。
+- 发布工具 P0(MSLICE、source-closure 哈希、release-validation fail-open)已落地。
 
 
 ## 仍开放(不阻塞 A1 冻结)
 ## 仍开放(不阻塞 A1 冻结)
 
 
 1. Hardware bring-up(明确 **NOT RUN**,需另授权)。
 1. Hardware bring-up(明确 **NOT RUN**,需另授权)。
-2. 是否做 bounded LUT 小优化(最多一轮);默认可接受现状 96.43% LUT。
-3. 若本机缺少 `b4b0eda4…` bitstream 字节,则 final firmware 双包需先恢复 bytes(TD replay)或保持 intermediate。
+2. 是否做 bounded LUT 小优化(最多一轮);默认可接受历史 A1 4320 LUT / 1089 MSLICE。
+3. 历史 bitstream `b4b0eda4…` @ `ff44128a` 字节未恢复;final firmware 取决于本轮 fresh `td2026`,否则保持 intermediate。
 
 
 ## 非问题
 ## 非问题
 
 

+ 9 - 8
PLAN.md

@@ -1,16 +1,17 @@
-# PLAN — MSE A1 Round-8 final release / provenance dual-package closure
+# PLAN — MSE A1 Round-10 final release / provenance dual-package closure
 
 
 ## 优先级
 ## 优先级
 
 
 1. 功能可靠:串行标定、三轴 overlap、百分比、限位 one-shot、rate-dispatch 原子 tag(已冻结,本轮不改生产 RTL)。
 1. 功能可靠:串行标定、三轴 overlap、百分比、限位 one-shot、rate-dispatch 原子 tag(已冻结,本轮不改生产 RTL)。
-2. 资源:保持 A1 route(4320 LUT / 1089 MSLICE / DSP 1);不因余量小而重构。
-3. 性能:仅需 25 MHz;42.3 MHz 已足够。
+2. 资源:保持 A1 语义;历史 TD 为 4320 LUT / 1089 MSLICE / DSP 1。fresh TD 以新 receipt 为准,不为余量重构。
+3. 性能:仅需 25 MHz。
 
 
-## Round-8 目标
+## Round-10 目标
 
 
-1. 关闭 Round-7 provenance 缺口:actual-HEAD closure、tip 三角色、current Formal PASS、活动文档换代、final identity、topic 命名。
-2. clean verification tip(当前含 R7 tip `21ed755…` / run `mse-r7-20260812T132652Z`)→ 矩阵/gates → delivery receipts → package-time dual package(或诚实 intermediate)。
-3. reference 原件继续默认排除。
+1. 关闭 Round-9 发布工具缺口:MSLICE 解析、source-closure 哈希关系、current/historical 证据选择、final semantic selftest、firmware SHA256SUMS、release-validation fail-closed、topic=`mse-a1` 命名。
+2. 全部 tracked 工具/文档/测试落地后提交 **clean verification tip**(文档不硬编码该 tip / delivery commit)→ 完整矩阵 `mse-r10-<UTC>` → 无 `b4b0eda4…` 字节则 fresh `td2026` → package-time dual package(或诚实 intermediate)。
+3. R7 `21ed755…` / `mse-r7-20260812T132652Z` 与 R8 `3177c2f0…` 仅为 historical,不是 current。
+4. reference 原件继续默认排除。
 
 
 ## 协议锚点(活动)
 ## 协议锚点(活动)
 
 
@@ -21,4 +22,4 @@
 - 不合入 `dev`;不访问 COM/JTAG;不重开 Scheme B/A2;不 seed sweep。
 - 不合入 `dev`;不访问 COM/JTAG;不重开 Scheme B/A2;不 seed sweep。
 - Round-12(`8403e020` / 2893 LUT / DSP0)与 Round-6 文档权威 **不再是** 当前真相。
 - Round-12(`8403e020` / 2893 LUT / DSP0)与 Round-6 文档权威 **不再是** 当前真相。
 - 不再恢复 legacy 450-step jog。
 - 不再恢复 legacy 450-step jog。
-- TD-bound 仍为 `ff44128a` / bitstream `b4b0eda4…`(生产输入未变则 reuse)。
+- 不得把历史 `ff44128a` / `b4b0eda4…` 当作已核验 bitstream 字节。

+ 9 - 9
README.zh-CN.md

@@ -14,20 +14,22 @@
 - 限位硬截断:`truncate_current_high_pulse_immediately_after_synchronized_limit`。
 - 限位硬截断:`truncate_current_high_pulse_immediately_after_synchronized_limit`。
 - Motor EN:`permanent_high`。Active IO:CON104/105/106/120/12/129。六限位。
 - Motor EN:`permanent_high`。Active IO:CON104/105/106/120/12/129。六限位。
 
 
-## 当前基线与验证真相(MSE A1 / Round-8 release closure)
+## 当前基线与验证真相(MSE A1 / Round-10 release closure)
 
 
 | 项 | 值 |
 | 项 | 值 |
 |---|---|
 |---|---|
 | 预览分支 | `preview/motor-shared-executor` |
 | 预览分支 | `preview/motor-shared-executor` |
 | base `dev`(锁定,未改) | `d4f3df2549efeb1e9227f62d1d71c6179c9f9160` |
 | base `dev`(锁定,未改) | `d4f3df2549efeb1e9227f62d1d71c6179c9f9160` |
-| TD-bound / artifact source | `ff44128a540b7ffd9d82314093b242ac3aee92d7`(生产 source closure 37/37 unchanged → 复用 exact TD) |
-| matrix_verification_tip | `21ed755ad2ddb6689bca88a9a037b391372a060e`(Round-7 matrix;Round-8 tip 若重跑矩阵则以 package identity 为准) |
-| Unified matrix run_id | `mse-r7-20260812T132652Z` |
 | 架构 winner | **A1 sequential shared DDA = PRODUCT WINNER / FROZEN** |
 | 架构 winner | **A1 sequential shared DDA = PRODUCT WINNER / FROZEN** |
 | A2 | **STOPPED**(full-chip route `PHY-8155`;不换 seed) |
 | A2 | **STOPPED**(full-chip route `PHY-8155`;不换 seed) |
 | Scheme B | **STOPPED**(LUT 回归) |
 | Scheme B | **STOPPED**(LUT 回归) |
-| TD candidate(复用) | bitstream `b4b0eda4ee8d774109eff83b519bdaa19d5e73d770562983121a596df00952d0`;LUT **4320**/4480;MSLICE **1089**/1120;DSP **1**;Fmax ≈ **42.332** MHz |
-| 生产 binding | **37 expected / 37 matched / 0 missing / 0 hash mismatch** |
+| 当前软件矩阵 / Formal | package-time `meta/release-set-identity.json` 的 `matrix_verification_tip` + `software_verification_run_id`(本轮 clean tip 上跑 `mse-r10-<UTC>`) |
+| 最近一次已完成软件矩阵(历史,将被本轮新 tip 矩阵取代) | R9 `d126c3df…` / `mse-r9-20260812T163229Z` |
+| R8 canonical(历史,非 current) | `3177c2f0…` / `mse-r8-20260812T153716Z` |
+| R7 matrix(历史,非 current) | `21ed755ad2ddb6689bca88a9a037b391372a060e` / `mse-r7-20260812T132652Z` |
+| 历史 TD-bound / artifact source | `ff44128a540b7ffd9d82314093b242ac3aee92d7`;LUT **4320** / MSLICE **1089** / DSP **1**;bitstream `b4b0eda4…` **字节未在磁盘恢复** |
+| 本轮 TD | Branch B:新 verification tip 上独占 `td2026` fresh;成功则新 TD 为 current;失败则诚实 intermediate,不生成 firmware |
+| 生产 binding | 历史 A1 **37 expected / 37 matched / 0 missing / 0 hash mismatch**;fresh TD 以新 receipt 为准 |
 | Package topic | `mse-a1`(`door-percent` 仅为 deprecated alias) |
 | Package topic | `mse-a1`(`door-percent` 仅为 deprecated alias) |
 | Hardware / JTAG / 烧录 | **`NOT RUN`** |
 | Hardware / JTAG / 烧录 | **`NOT RUN`** |
 | 合入 `dev` | **禁止** |
 | 合入 `dev` | **禁止** |
@@ -36,8 +38,6 @@
 
 
 旧 Round-6 / Round-12 固定速度 / `8403e020` / `e0cf1321…` / 2893 LUT / DSP0 **不再是活动权威**(见 `docs/historical/` 与 `receipts/historical/`)。
 旧 Round-6 / Round-12 固定速度 / `8403e020` / `e0cf1321…` / 2893 LUT / DSP0 **不再是活动权威**(见 `docs/historical/` 与 `receipts/historical/`)。
 
 
-当前资源余量很小(≈96.43% LUT),不建议继续扩展;现有 route/timing/bitgen 已通过。
-
 ## Reference 策略
 ## Reference 策略
 
 
 raw BRD/PDF/DSN 默认不进 review/firmware 包;derived board-viewer + reference/polarity fingerprint 保留。无物理映射变化时不另传原件。
 raw BRD/PDF/DSN 默认不进 review/firmware 包;derived board-viewer + reference/polarity fingerprint 保留。无物理映射变化时不另传原件。
@@ -45,7 +45,7 @@ raw BRD/PDF/DSN 默认不进 review/firmware 包;derived board-viewer + refere
 ## 离线验证入口(Linux)
 ## 离线验证入口(Linux)
 
 
 ```bash
 ```bash
-export PATH=/data/prod2u/oss-cad-suite/latest/bin:$PATH
+export PATH=/data/prod2u/bin:$PATH
 bash tools/verify.sh --lane python
 bash tools/verify.sh --lane python
 bash tools/verify.sh --lane icarus
 bash tools/verify.sh --lane icarus
 bash tools/verify.sh --lane cocotb
 bash tools/verify.sh --lane cocotb

+ 9 - 4
config/review_compact_evidence_allowlist.json

@@ -17,9 +17,9 @@
         "formal-receipt.json"
         "formal-receipt.json"
       ],
       ],
       "match_workspace_paths": [
       "match_workspace_paths": [
-        "receipts/current/formal-receipt.json",
-        "receipts/mse-r7-matrix/mse-r7-20260812T132652Z/lanes/formal-receipt.json"
-      ]
+        "evidence/formal/formal-receipt.json"
+      ],
+      "notes": "Current Formal is selected by PRODU2_VERIFICATION_TIP + PRODU2_VERIFICATION_RUN_ID, never hardcoded R7/R8 paths."
     },
     },
     {
     {
       "key": "td_receipt",
       "key": "td_receipt",
@@ -110,7 +110,12 @@
     "path_prefixes": [
     "path_prefixes": [
       "lane-status/",
       "lane-status/",
       "evidence/lane-status/",
       "evidence/lane-status/",
-      "status/"
+      "status/",
+      "receipts/historical/",
+      "receipts/mse-r6-matrix/",
+      "receipts/mse-r7-matrix/",
+      "receipts/mse-r8-matrix/",
+      "receipts/current/"
     ],
     ],
     "basename_globs": [
     "basename_globs": [
       "verification-matrix-rerun*.json",
       "verification-matrix-rerun*.json",

+ 6 - 5
docs/TD_USAGE.zh-CN.md

@@ -2,15 +2,16 @@
 
 
 **活动权威环境是 Linux 容器**,命令入口为 `td2026`(Anlogic TD 2026.1 SP2)。最终验收收据必须以当前 Linux 运行产生;Windows GUI/批处理路径仅作可选参考,不是活动闭环权威。
 **活动权威环境是 Linux 容器**,命令入口为 `td2026`(Anlogic TD 2026.1 SP2)。最终验收收据必须以当前 Linux 运行产生;Windows GUI/批处理路径仅作可选参考,不是活动闭环权威。
 
 
-## 活动 TD / bitstream 身份(door-percent · Round-12)
+## 活动 TD / bitstream 身份(MSE A1 · Round-10)
 
 
 | 项 | 状态 |
 | 项 | 状态 |
 |---|---|
 |---|---|
 | 活动合同 | 三轴 **百分比定位**;标定 seek-close→measure-open;WD 30s FAN10;`0x03/0x83`;`truncate_current_high_pulse_immediately_after_synchronized_limit`;EN `permanent_high`;六限位;CON104/105/106/120/12/129 |
 | 活动合同 | 三轴 **百分比定位**;标定 seek-close→measure-open;WD 30s FAN10;`0x03/0x83`;`truncate_current_high_pulse_immediately_after_synchronized_limit`;EN `permanent_high`;六限位;CON104/105/106/120/12/129 |
-| Round-12 tip TD / bitstream | **pass**;verif `12d20260810140146000000000000000`;artifact `7a6f306aa33045eea78d8785a1765b12`;SHA `e0cf1321b7a517a48dae57547356c17caace5bc9949f8c6a8f14a558353d4f69`;TD-bound `8403e0204176614bc381a135c4a5bf5ee6691af8`;LUT 2893 / Packed Slice 2893;Hardware NOT RUN;不合入 `dev` |
-| Round-11 tip bit(历史) | SHA `4ce1dd7c…` — **不得**复用为 Round-12 tip pass |
-| Round-10 tip bit(历史) | verif `c919ae3d…`;SHA `299ef1cf…` @ `ff480c0a…` — **不得**复用 |
-| Round-9 tip bit(历史) | run `1e784d30…`;SHA `71a571a3…` @ `52aae277…` — **不得**复用 |
+| 当前 TD | 本轮 Branch B:新 verification tip 上独占 `td2026` fresh。历史 `ff44128a` / bitstream `b4b0eda4…` / LUT 4320 / MSLICE 1089 **字节未恢复,不得冒充已核验 current** |
+| Round-12 tip TD(历史,非 current) | `8403e020` / SHA `e0cf1321…` / LUT 2893 — **不得**复用为 MSE A1 current |
+| Round-11 tip bit(历史) | SHA `4ce1dd7c…` — **不得**复用为 current |
+| Round-10 door-percent tip bit(历史) | verif `c919ae3d…`;SHA `299ef1cf…` @ `ff480c0a…` — **不得**复用 |
+| Round-9 door-percent tip bit(历史) | run `1e784d30…`;SHA `71a571a3…` @ `52aae277…` — **不得**复用 |
 | 修复前 tip bit(历史) | `9cd778…` @ `3ad444fb` — **不得**复用 |
 | 修复前 tip bit(历史) | `9cd778…` @ `3ad444fb` — **不得**复用 |
 | 旧 jog tip / bit(历史) | `f23d6d4c…` / `eb275921…` — **不得**复用 |
 | 旧 jog tip / bit(历史) | `f23d6d4c…` / `eb275921…` — **不得**复用 |
 | td2026 | Release_2026.1_SP2 Build `6.2.2.200067`(工具版本) |
 | td2026 | Release_2026.1_SP2 Build `6.2.2.200067`(工具版本) |

+ 99 - 12
package_for_agent_analysis.py

@@ -1581,6 +1581,16 @@ def collect_analysis_inputs(
                 ).strip()
                 ).strip()
                 # Reused TD-bound production tip when unchanged; never silently equal delivery.
                 # Reused TD-bound production tip when unchanged; never silently equal delivery.
                 artifact = td_bound_candidate or delivery
                 artifact = td_bound_candidate or delivery
+                old_cmp = pkg_prov.compare_production_source_commits(
+                    from_commit=pkg_prov.BASE_DEV_COMMIT_DEFAULT,
+                    to_commit=artifact,
+                    repo_root=root,
+                )
+                art_cmp = pkg_prov.compare_production_source_commits(
+                    from_commit=artifact,
+                    to_commit=delivery,
+                    repo_root=root,
+                )
                 ref_pointer = pkg_prov.build_reference_pointer(
                 ref_pointer = pkg_prov.build_reference_pointer(
                     artifact_commit=artifact,
                     artifact_commit=artifact,
                     delivery_commit=delivery,
                     delivery_commit=delivery,
@@ -1593,10 +1603,14 @@ def collect_analysis_inputs(
                     old_baseline_commit=pkg_prov.BASE_DEV_COMMIT_DEFAULT,
                     old_baseline_commit=pkg_prov.BASE_DEV_COMMIT_DEFAULT,
                     artifact_commit=artifact,
                     artifact_commit=artifact,
                     delivery_commit=delivery,
                     delivery_commit=delivery,
-                    old_to_artifact_unchanged=False,  # A1 TD tip changed vs locked dev
-                    artifact_to_delivery_unchanged=(artifact == delivery),
-                    old_to_artifact_changed_paths=[],
-                    artifact_to_delivery_changed_paths=[],
+                    old_to_artifact_unchanged=bool(old_cmp.get("unchanged")),
+                    artifact_to_delivery_unchanged=bool(art_cmp.get("unchanged")),
+                    old_to_artifact_changed_paths=list(
+                        old_cmp.get("production_changed_paths") or []
+                    ),
+                    artifact_to_delivery_changed_paths=list(
+                        art_cmp.get("production_changed_paths") or []
+                    ),
                     comparison_mode="snapshot_hash",
                     comparison_mode="snapshot_hash",
                 )
                 )
                 # Annotate MSE intermediate identity without inventing a false unchanged edge.
                 # Annotate MSE intermediate identity without inventing a false unchanged edge.
@@ -1935,6 +1949,7 @@ def collect_analysis_inputs(
                 "release_set_id": release_set_id,
                 "release_set_id": release_set_id,
                 "base_dev_commit": pkg_prov.BASE_DEV_COMMIT_DEFAULT,
                 "base_dev_commit": pkg_prov.BASE_DEV_COMMIT_DEFAULT,
                 "matrix_verification_tip": matrix_tip or None,
                 "matrix_verification_tip": matrix_tip or None,
+                "software_verification_run_id": matrix_run or None,
                 "verification_tip": matrix_tip or None,
                 "verification_tip": matrix_tip or None,
                 "verification_run_id": matrix_run or td_verification_run_id or td_run,
                 "verification_run_id": matrix_run or td_verification_run_id or td_run,
                 "td_bound_commit": td_bound,
                 "td_bound_commit": td_bound,
@@ -1959,6 +1974,9 @@ def collect_analysis_inputs(
                 "reference_set_fingerprint": ref_fp["sha256"],
                 "reference_set_fingerprint": ref_fp["sha256"],
                 "polarity_fingerprint": config_fp,
                 "polarity_fingerprint": config_fp,
                 "hardware_validation": "not_run",
                 "hardware_validation": "not_run",
+                "lut": None,
+                "mslice": None,
+                "dsp": None,
                 "note": (
                 "note": (
                     "release_set_id is independently recomputable from these fields; "
                     "release_set_id is independently recomputable from these fields; "
                     "td_artifact_run_id (TD receipt run_id) feeds release_set_id; "
                     "td_artifact_run_id (TD receipt run_id) feeds release_set_id; "
@@ -1966,6 +1984,15 @@ def collect_analysis_inputs(
                     "Sibling ZIP SHAs live only in the external release-set JSON."
                     "Sibling ZIP SHAs live only in the external release-set JSON."
                 ),
                 ),
             }
             }
+            try:
+                td_fields = pkg_prov.load_canonical_td_a1_fields(root)
+                release_identity["lut"] = td_fields.get("lut")
+                release_identity["mslice"] = td_fields.get("mslice")
+                release_identity["dsp"] = td_fields.get("dsp")
+                if not release_identity.get("td_receipt_sha256"):
+                    release_identity["td_receipt_sha256"] = td_fields.get("td_receipt_sha256")
+            except Exception:  # noqa: BLE001
+                pass
             for report_meta in binding.get("td_reports") or []:
             for report_meta in binding.get("td_reports") or []:
                 if isinstance(report_meta, dict) and report_meta.get("sha256"):
                 if isinstance(report_meta, dict) and report_meta.get("sha256"):
                     release_identity["td_receipt_sha256"] = report_meta.get("sha256")
                     release_identity["td_receipt_sha256"] = report_meta.get("sha256")
@@ -1993,20 +2020,32 @@ def collect_analysis_inputs(
             )
             )
         # External selftest sidecar certifies the final ZIP; never embed a recursive
         # External selftest sidecar certifies the final ZIP; never embed a recursive
         # compact-package-selftest.json that claims to authenticate this archive.
         # compact-package-selftest.json that claims to authenticate this archive.
+        import package_provenance as pkg_prov
+
         delivery_full = str(provenance.get("head") or binding_commit or "unknown").strip()
         delivery_full = str(provenance.get("head") or binding_commit or "unknown").strip()
-        delivery_short = delivery_full[:8]
         topic_slug = pkg_prov.release_task_slug()
         topic_slug = pkg_prov.release_task_slug()
-        expected_selftest = pkg_prov.release_sibling_filename(
-            "review-selftest", delivery_full, slug=topic_slug
+        actual_zip = None
+        if package_name and "PENDING" not in str(package_name).upper():
+            actual_zip = (
+                package_name if str(package_name).casefold().endswith(".zip") else f"{package_name}.zip"
+            )
+        names = pkg_prov.canonical_release_names(
+            role="review-compact",
+            stage=stage_n if "stage_n" in locals() else "intermediate-review",
+            delivery_commit=delivery_full if delivery_full != "unknown" else "0" * 40,
+            topic=topic_slug,
+            actual_zip_basename=actual_zip,
         )
         )
         provenance_artifacts[_COMPACT_SELFTEST_POINTER] = handoff.json_bytes(
         provenance_artifacts[_COMPACT_SELFTEST_POINTER] = handoff.json_bytes(
             {
             {
                 "schema": "cpld-review-compact-selftest-pointer-v1",
                 "schema": "cpld-review-compact-selftest-pointer-v1",
                 "role": "external_sidecar_only",
                 "role": "external_sidecar_only",
-                "topic": topic_slug,
-                "package_stage": stage_n if "stage_n" in locals() else None,
+                "topic": names["topic"],
+                "package_stage": names["stage"],
                 "delivery_commit": delivery_full,
                 "delivery_commit": delivery_full,
-                "expected_external_selftest_filename": expected_selftest,
+                "actual_zip_basename": names["zip_basename"],
+                "expected_external_selftest_filename": names["selftest_basename"],
+                "expected_detached_replay_filename": names["detached_replay_basename"],
                 "deprecated_alias_filename": pkg_prov.deprecated_door_percent_alias(
                 "deprecated_alias_filename": pkg_prov.deprecated_door_percent_alias(
                     "review-selftest", delivery_full
                     "review-selftest", delivery_full
                 ),
                 ),
@@ -2021,8 +2060,14 @@ def collect_analysis_inputs(
         # Package-time actual-HEAD closure (never pre-committed self-hash).
         # Package-time actual-HEAD closure (never pre-committed self-hash).
         matrix_tip_env = str(
         matrix_tip_env = str(
             os.environ.get("PRODU2_VERIFICATION_TIP", "").strip()
             os.environ.get("PRODU2_VERIFICATION_TIP", "").strip()
-            or "21ed755ad2ddb6689bca88a9a037b391372a060e"
+            or binding.get("matrix_verification_tip")
+            or binding.get("verification_tip")
+            or ""
         ).strip()
         ).strip()
+        if not matrix_tip_env and stage_n == "final-review":
+            raise PackagingError(
+                "final-review requires PRODU2_VERIFICATION_TIP (no hardcoded R7/R8 fallback)"
+            )
         if matrix_tip_env and delivery_full and delivery_full != "unknown":
         if matrix_tip_env and delivery_full and delivery_full != "unknown":
             try:
             try:
                 import verification_to_delivery_closure as v2d
                 import verification_to_delivery_closure as v2d
@@ -2249,6 +2294,42 @@ def collect_analysis_inputs(
                 include_process_evidence=include_process,
                 include_process_evidence=include_process,
                 profile=profile,
                 profile=profile,
             )
             )
+        tip = os.environ.get("PRODU2_VERIFICATION_TIP", "").strip()
+        run_id = os.environ.get("PRODU2_VERIFICATION_RUN_ID", "").strip()
+        if tip and run_id:
+            try:
+                import current_evidence as cur_ev
+
+                staged_cur = cur_ev.stage_current_evidence(
+                    repo=root,
+                    staging_root=temp_root / "current-evidence",
+                    verification_tip=tip,
+                    run_id=run_id,
+                )
+                for key, dest in staged_cur.items():
+                    rel = (
+                        cur_ev.CANONICAL_MATRIX_REL
+                        if key == "matrix"
+                        else cur_ev.CANONICAL_FORMAL_REL
+                    )
+                    items.append(
+                        PackageItem(
+                            candidate=_candidate_from_path(dest, rel),
+                            category="evidence",
+                            source_id="current-evidence",
+                            original_path=rel,
+                            scan_archive=False,
+                        )
+                    )
+            except Exception as exc:  # noqa: BLE001
+                stage_now = str(package_stage or "").casefold().replace("_", "-")
+                if stage_now in {"final", "final-review"}:
+                    raise PackagingError(
+                        f"current evidence selection failed: {exc}"
+                    ) from exc
+                warnings.append(
+                    {"code": "current_evidence_skipped", "detail": str(exc)}
+                )
         kept_items, filter_excluded, _remaps = evidence_canon.filter_package_items_for_compact(
         kept_items, filter_excluded, _remaps = evidence_canon.filter_package_items_for_compact(
             items,
             items,
             profile=profile,
             profile=profile,
@@ -2265,7 +2346,13 @@ def collect_analysis_inputs(
             if previous is None:
             if previous is None:
                 deduped[key] = item
                 deduped[key] = item
                 continue
                 continue
-            prefer_new = item.source_id == "evidence-root" and previous.source_id != "evidence-root"
+            prefer_new = (
+                item.source_id == "current-evidence"
+                and previous.source_id != "current-evidence"
+            ) or (
+                item.source_id == "evidence-root"
+                and previous.source_id not in {"current-evidence", "evidence-root"}
+            )
             keep, drop = (item, previous) if prefer_new else (previous, item)
             keep, drop = (item, previous) if prefer_new else (previous, item)
             deduped[key] = keep
             deduped[key] = keep
             excluded.append(
             excluded.append(

receipts/current/FORMAL-CANON-PROMOTION.json → receipts/historical/r8-stale-canonical/FORMAL-CANON-PROMOTION.json


+ 9 - 0
receipts/historical/r8-stale-canonical/README.md

@@ -0,0 +1,9 @@
+# R8 stale canonical copies (historical, not current)
+
+These files were previously at `evidence/matrix/verification-matrix-final.json`,
+`evidence/formal/formal-receipt.json`, and `receipts/current/`. They bind Round-8
+tip `3177c2f0…` / run `mse-r8-20260812T153716Z` and must not be selected as
+current matrix/Formal.
+
+Current evidence is selected only by `PRODU2_VERIFICATION_TIP` +
+`PRODU2_VERIFICATION_RUN_ID` (see `tools/current_evidence.py`).

evidence/formal/formal-receipt.json → receipts/historical/r8-stale-canonical/formal-receipt.json


receipts/current/formal-receipt.json → receipts/historical/r8-stale-canonical/receipts-current-formal-receipt.json


evidence/matrix/verification-matrix-final.json → receipts/historical/r8-stale-canonical/verification-matrix-final.json


+ 53 - 0
receipts/mse-r10-preaudit/five-audit.json

@@ -0,0 +1,53 @@
+{
+  "schema": "prod2u-mse-r10-pre-audit-v1",
+  "generated_utc": "2026-08-13T01:10:00Z",
+  "branch": "preview/motor-shared-executor",
+  "worktree": "/data/prod2u/worktrees/motor-shared-executor",
+  "dev": "d4f3df2549efeb1e9227f62d1d71c6179c9f9160",
+  "live_head_at_audit": "d91a7b46a37371d9a03ae47c5245da2eb4561772",
+  "hardware_validation": "NOT RUN",
+  "dev_merge": "FORBIDDEN",
+  "audits": [
+    {
+      "id": 1,
+      "name": "production_logic_source_closure",
+      "status": "pass",
+      "production_rtl_change": "none",
+      "artifact": "ff44128a540b7ffd9d82314093b242ac3aee92d7",
+      "note": "A1 frozen. Production inputs unchanged artifact→R9 delivery. No new RTL P0."
+    },
+    {
+      "id": 2,
+      "name": "round9_matrix_authenticity",
+      "status": "pass",
+      "run_id": "mse-r9-20260812T163229Z",
+      "tip": "d126c3df0ceef3de4d559b60253fb5336da11922",
+      "overall": "pass"
+    },
+    {
+      "id": 3,
+      "name": "release_tooling_fail_closed",
+      "status": "fail_found_then_patched_in_this_tip",
+      "findings": [
+        "MSLICE parsed as LUT 4320; now explicit mslice 1089",
+        "source-closure used commit equality; now snapshot_hash",
+        "release_validation fail-open on skipped selftest / sidecar labels",
+        "stale R8 canonical matrix/Formal at evidence/; moved to historical; selector uses tip+run"
+      ]
+    },
+    {
+      "id": 4,
+      "name": "td_bitstream_bytes",
+      "status": "missing_bytes",
+      "canonical_sha": "b4b0eda4ee8d774109eff83b519bdaa19d5e73d770562983121a596df00952d0",
+      "decision": "branch_B_fresh_td_after_this_verification_tip"
+    },
+    {
+      "id": 5,
+      "name": "reference_physical_boundary",
+      "status": "pass",
+      "raw_reference_in_default_package": false,
+      "pin_connector_polarity_change": false
+    }
+  ]
+}

+ 28 - 0
tests/unit/test_activity_docs_truth.py

@@ -134,6 +134,34 @@ class ActivityDocsTruthTests(unittest.TestCase):
                 bad.append(line)
                 bad.append(line)
         return bad
         return bad
 
 
+    def test_activity_docs_r7_r8_not_current_without_negation(self) -> None:
+        entry = (
+            "README.zh-CN.md",
+            "FINAL_DELIVERY_REPORT.md",
+            "ACCEPTANCE_MATRIX.md",
+            "PLAN.md",
+            "OPEN_QUESTIONS.md",
+        )
+        negate = re.compile(
+            r"(?i)历史|historical|retired|superseded|不再|不是\s*current|非\s*current|"
+            r"将被|取代|not\s+current|stale"
+        )
+        for rel in entry:
+            text = _read(rel)
+            for token in (
+                "mse-r7-20260812T132652Z",
+                "21ed755ad2ddb6689bca88a9a037b391372a060e",
+                "3177c2f0",
+            ):
+                for line in text.splitlines():
+                    if token not in line:
+                        continue
+                    if negate.search(line):
+                        continue
+                    self.fail(
+                        f"{rel}: R7/R8 token presented as current without negation: {line!r}"
+                    )
+
     def test_activity_docs_mse_a1_current_authority(self) -> None:
     def test_activity_docs_mse_a1_current_authority(self) -> None:
         """Activity entry docs must describe MSE A1, not Round-12 tip authority."""
         """Activity entry docs must describe MSE A1, not Round-12 tip authority."""
         entry = (
         entry = (

+ 139 - 0
tests/unit/test_build_firmware_package.py

@@ -308,6 +308,145 @@ class BuildFirmwarePackageTests(unittest.TestCase):
         self.assertTrue(comparison["source_closure_equal"])
         self.assertTrue(comparison["source_closure_equal"])
         self.assertEqual(comparison["inputs"][0]["status"], "same")
         self.assertEqual(comparison["inputs"][0]["status"], "same")
 
 
+    def _build_fake_fw(self, tmp_path: Path) -> Path:
+        td_root, bitstream, report = self._make_td_root(tmp_path)
+        artifact, matrix, final_dev = self._commits()
+        with _patch_canonical_td_for_fake():
+            package, _sidecar = builder.build_firmware_package(
+                output_dir=tmp_path / "dist",
+                package_name="tamper-firmware",
+                td_root=td_root,
+                bitstream_path=bitstream,
+                td_report_path=report,
+                artifact_commit=artifact,
+                matrix_commit=matrix,
+                final_dev_commit=final_dev,
+                source_closure_unchanged=True,
+            )
+        return package
+
+    def test_firmware_selftest_tamper_bitstream_byte(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            package = self._build_fake_fw(Path(tmp))
+            mutated = Path(tmp) / "mut-bit.zip"
+            with zipfile.ZipFile(package, "r") as src, zipfile.ZipFile(mutated, "w") as dst:
+                for info in src.infolist():
+                    data = src.read(info.filename)
+                    if info.filename == "fw.bit":
+                        data = data[:-1] + bytes([data[-1] ^ 0x01])
+                    dst.writestr(info, data)
+            result = builder.run_firmware_zip_selftest(mutated)
+            self.assertEqual(result["status"], "fail")
+            joined = " ".join(result["failures"])
+            self.assertTrue(
+                "bitstream" in joined or "sha256sums_mismatch:fw.bit" in joined,
+                result["failures"],
+            )
+
+    def test_firmware_selftest_tamper_sha256sums_entry(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            package = self._build_fake_fw(Path(tmp))
+            mutated = Path(tmp) / "mut-sum.zip"
+            with zipfile.ZipFile(package, "r") as src, zipfile.ZipFile(mutated, "w") as dst:
+                for info in src.infolist():
+                    data = src.read(info.filename)
+                    if info.filename == "SHA256SUMS.txt":
+                        text = data.decode("ascii")
+                        text = text.replace("fw.bit", "fw.bit", 1)
+                        # Flip first hex nibble of the fw.bit line.
+                        lines = []
+                        for line in text.splitlines():
+                            if line.endswith("  fw.bit"):
+                                line = ("0" if line[0] != "0" else "1") + line[1:]
+                            lines.append(line)
+                        data = ("\n".join(lines) + "\n").encode("ascii")
+                    dst.writestr(info, data)
+            result = builder.run_firmware_zip_selftest(mutated)
+            self.assertEqual(result["status"], "fail")
+            self.assertTrue(
+                any("sha256sums_mismatch:fw.bit" in item for item in result["failures"]),
+                result["failures"],
+            )
+
+    def test_firmware_selftest_duplicate_sha_entry(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            package = self._build_fake_fw(Path(tmp))
+            mutated = Path(tmp) / "mut-dup.zip"
+            with zipfile.ZipFile(package, "r") as src, zipfile.ZipFile(mutated, "w") as dst:
+                for info in src.infolist():
+                    data = src.read(info.filename)
+                    if info.filename == "SHA256SUMS.txt":
+                        text = data.decode("ascii")
+                        fw_line = next(
+                            line for line in text.splitlines() if line.endswith("  fw.bit")
+                        )
+                        data = (text + fw_line + "\n").encode("ascii")
+                    dst.writestr(info, data)
+            result = builder.run_firmware_zip_selftest(mutated)
+            self.assertEqual(result["status"], "fail")
+            self.assertTrue(
+                any("sha256sums_duplicate:fw.bit" in item for item in result["failures"]),
+                result["failures"],
+            )
+
+    def test_firmware_selftest_delete_td_receipt(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            package = self._build_fake_fw(Path(tmp))
+            mutated = Path(tmp) / "mut-del.zip"
+            with zipfile.ZipFile(package, "r") as src, zipfile.ZipFile(mutated, "w") as dst:
+                for info in src.infolist():
+                    if info.filename == "td/original-final_td_report.json":
+                        continue
+                    dst.writestr(info, src.read(info.filename))
+            result = builder.run_firmware_zip_selftest(mutated)
+            self.assertEqual(result["status"], "fail")
+            joined = " ".join(result["failures"])
+            self.assertTrue(
+                "missing_required_files" in joined or "sha256sums_missing_file" in joined,
+                result["failures"],
+            )
+
+    def test_firmware_selftest_wrong_delivery(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            package = self._build_fake_fw(Path(tmp))
+            mutated = Path(tmp) / "mut-deliv.zip"
+            with zipfile.ZipFile(package, "r") as src, zipfile.ZipFile(mutated, "w") as dst:
+                for info in src.infolist():
+                    data = src.read(info.filename)
+                    if info.filename == "meta/release-set-identity.json":
+                        ident = json.loads(data)
+                        ident["delivery_commit"] = "0" * 40
+                        data = (json.dumps(ident) + "\n").encode("utf-8")
+                    dst.writestr(info, data)
+            result = builder.run_firmware_zip_selftest(mutated)
+            self.assertEqual(result["status"], "fail")
+            self.assertTrue(
+                any("identity_delivery_mismatch_txt" in item for item in result["failures"]),
+                result["failures"],
+            )
+
+    def test_firmware_selftest_stale_sibling(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            package = self._build_fake_fw(Path(tmp))
+            mutated = Path(tmp) / "mut-sib.zip"
+            with zipfile.ZipFile(package, "r") as src, zipfile.ZipFile(mutated, "w") as dst:
+                for info in src.infolist():
+                    data = src.read(info.filename)
+                    if info.filename == "meta/release-set-sibling.json":
+                        sib = json.loads(data)
+                        sib["sibling_expected_filename"] = (
+                            "prod2u-review-compact-door-percent-deadbeef.zip"
+                        )
+                        data = (json.dumps(sib) + "\n").encode("utf-8")
+                    dst.writestr(info, data)
+            result = builder.run_firmware_zip_selftest(mutated)
+            self.assertEqual(result["status"], "fail")
+            joined = " ".join(result["failures"])
+            self.assertTrue(
+                "sibling_stale_door_percent" in joined or "sibling_topic_not_mse_a1" in joined,
+                result["failures"],
+            )
+
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     unittest.main()
     unittest.main()

+ 7 - 2
tests/unit/test_compact_package_selftest.py

@@ -333,10 +333,15 @@ class CompactPackageSelftestUnitTests(unittest.TestCase):
                     else:
                     else:
                         archive.writestr(member, b"# note\n")
                         archive.writestr(member, b"# note\n")
             with zipfile.ZipFile(zip_path) as archive:
             with zipfile.ZipFile(zip_path) as archive:
-                failures = selftest.check_final_canonical_evidence(
+                path_failures = selftest.check_final_evidence_paths(
                     archive, list(archive.namelist())
                     archive, list(archive.namelist())
                 )
                 )
-            self.assertEqual(failures, [], failures)
+                semantic = selftest.check_final_canonical_evidence(
+                    archive, list(archive.namelist())
+                )
+            self.assertEqual(path_failures, [], path_failures)
+            # Empty `{}` JSON must fail semantic selftest (Round-10).
+            self.assertTrue(semantic, "empty JSON fixtures must not pass semantic selftest")
 
 
     def test_source_check_rejects_untracked_formal_workdir(self) -> None:
     def test_source_check_rejects_untracked_formal_workdir(self) -> None:
         selftest = load_selftest()
         selftest = load_selftest()

+ 243 - 0
tests/unit/test_mse_r10_current_evidence.py

@@ -0,0 +1,243 @@
+"""Round-10: current evidence selection, semantic selftest, naming, firmware tamper."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import zipfile
+from pathlib import Path
+
+import pytest
+
+from tools import current_evidence as cur_ev
+from tools import package_provenance as pkg_prov
+from tools import compact_package_selftest as selftest
+from tools import package_evidence_canon as evidence_canon
+
+
+TIP = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+RUN = "mse-r10-20260813T000000Z"
+
+
+def _matrix(*, status="pass", lane_fail=None, tip=TIP):
+    lanes = {
+        name: {"status": "pass", "commit_full": tip}
+        for name in cur_ev.REQUIRED_MATRIX_LANES
+    }
+    lanes["board_viewer"]["mode"] = "detached_derived"
+    if lane_fail:
+        lanes[lane_fail]["status"] = "fail"
+    return {
+        "schema": "prod2u-p4-normal-v3-verification-matrix-v2",
+        "status": status,
+        "failures": [] if status == "pass" and not lane_fail else [lane_fail or "x"],
+        "commit_full": tip,
+        "lanes": lanes,
+    }
+
+
+def _formal(*, n_targets=23, cover_hits=10, task_rc=0, tip=TIP):
+    targets = []
+    for i in range(n_targets - 1):
+        targets.append(
+            {
+                "name": f"t{i}",
+                "status": "pass",
+                "returncode": 0,
+                "task_results": [{"name": "bmc", "status": "PASS", "returncode": 0}],
+            }
+        )
+    targets.append(
+        {
+            "name": cur_ev.DISPATCHER_TARGET,
+            "status": "pass",
+            "returncode": 0,
+            "cover_required": True,
+            "cover_count": 10,
+            "cover_hit_count": cover_hits,
+            "cover_hit_ids": [str(i) for i in range(cover_hits)],
+            "task_results": [
+                {"name": "bmc", "status": "PASS", "returncode": task_rc},
+                {"name": "cover", "status": "PASS", "returncode": task_rc},
+            ],
+        }
+    )
+    return {
+        "schema": "prod2u-p4-normal-v3-formal-receipt-v1",
+        "status": "pass",
+        "commit_full": tip,
+        "targets": targets,
+        "target_manifest": {
+            "expected": {t["name"]: ["bmc"] for t in targets},
+            "failures": [],
+        },
+    }
+
+
+def test_select_current_matrix_explicit_path(tmp_path: Path):
+    family = tmp_path / "receipts" / "mse-r10-matrix" / RUN
+    family.mkdir(parents=True)
+    path = family / "unified-matrix-report.json"
+    path.write_text(json.dumps(_matrix()), encoding="utf-8")
+    got = cur_ev.select_current_matrix(tmp_path, verification_tip=TIP, run_id=RUN)
+    assert got == path
+
+
+def test_select_missing_matrix_fails(tmp_path: Path):
+    with pytest.raises(cur_ev.CurrentEvidenceError):
+        cur_ev.select_current_matrix(tmp_path, verification_tip=TIP, run_id=RUN)
+
+
+def test_matrix_lane_fail_detected():
+    failures = cur_ev.validate_matrix_report(
+        _matrix(lane_fail="icarus"), verification_tip=TIP, run_id=RUN
+    )
+    assert any("matrix_lane_not_pass:icarus" in item for item in failures)
+
+
+def test_formal_22_of_23_fails():
+    failures = cur_ev.validate_formal_receipt(_formal(n_targets=22), verification_tip=TIP)
+    assert any("formal_target_count:22" in item for item in failures)
+
+
+def test_dispatcher_cover_9_of_10_fails():
+    failures = cur_ev.validate_formal_receipt(
+        _formal(cover_hits=9), verification_tip=TIP
+    )
+    assert any("dispatcher_cover_hit:9" in item for item in failures)
+
+
+def test_formal_task_rc_nonzero_fails():
+    failures = cur_ev.validate_formal_receipt(_formal(task_rc=1), verification_tip=TIP)
+    assert any("formal_task_rc:" in item for item in failures)
+
+
+def test_empty_json_semantic_selftest_fails(tmp_path: Path):
+    zip_path = tmp_path / "empty.json.zip"
+    bit = b"BIT"
+    bit_sha = hashlib.sha256(bit).hexdigest()
+    with zipfile.ZipFile(zip_path, "w") as archive:
+        for suffix in selftest.FINAL_MANDATORY_EVIDENCE_SUFFIXES:
+            member = f"CPLD/{suffix}"
+            if suffix.endswith(".bit"):
+                archive.writestr(member, bit)
+            elif suffix.endswith("BITSTREAM-SHA256.txt"):
+                archive.writestr(member, bit_sha + "\n")
+            elif suffix.endswith(".json"):
+                archive.writestr(member, "{}\n")
+            else:
+                archive.writestr(member, "#\n")
+        archive.writestr("CPLD/meta/release-set-identity.json", "{}\n")
+    with zipfile.ZipFile(zip_path) as archive:
+        failures = selftest.check_final_canonical_evidence(
+            archive, list(archive.namelist())
+        )
+    assert failures
+    assert any("matrix_not_object_or_empty" in item or "release_identity" in item for item in failures)
+
+
+def test_stale_canonical_fail_matrix():
+    doc = _matrix(status="fail")
+    failures = cur_ev.validate_matrix_report(doc, verification_tip=TIP)
+    assert any("matrix_status_not_pass:fail" in item for item in failures)
+
+
+def test_mslice_equals_lut_identity_fails():
+    ident = {
+        "schema": "prod2u-release-set-identity-v1",
+        "algorithm_version": "prod2u-release-set-id-v1",
+        "package_stage": "final-review",
+        "release_set_id": "x",
+        "base_dev_commit": "d4f3df2549efeb1e9227f62d1d71c6179c9f9160",
+        "delivery_commit": TIP,
+        "td_bound_commit": "ff44128a540b7ffd9d82314093b242ac3aee92d7",
+        "artifact_source_commit": "ff44128a540b7ffd9d82314093b242ac3aee92d7",
+        "bitstream_sha256": "b" * 64,
+        "td_artifact_run_id": "run",
+        "td_receipt_sha256": "c" * 64,
+        "production_binding": "37/37/0/0",
+        "hardware_validation": "not_run",
+        "matrix_verification_tip": TIP,
+        "software_verification_run_id": RUN,
+        "lut": 4320,
+        "mslice": 4320,
+        "dsp": 1,
+    }
+    failures = cur_ev.validate_release_identity(ident, zip_head=TIP, require_final=True)
+    assert "release_identity_mslice_equals_lut" in failures
+
+
+def test_hook_ready_identity_fails():
+    ident = {
+        "schema": "prod2u-release-set-identity-v1",
+        "algorithm_version": "v1",
+        "package_stage": "final-review",
+        "release_set_id": "x",
+        "base_dev_commit": "d",
+        "delivery_commit": TIP,
+        "td_bound_commit": "t",
+        "artifact_source_commit": "t",
+        "bitstream_sha256": "b" * 64,
+        "td_artifact_run_id": "run",
+        "td_receipt_sha256": "c" * 64,
+        "production_binding": "37/37/0/0",
+        "hardware_validation": "not_run",
+        "matrix_verification_tip": TIP,
+        "software_verification_run_id": RUN,
+        "lut": 4320,
+        "mslice": 1089,
+        "note": "hook_ready",
+    }
+    failures = cur_ev.validate_release_identity(ident, require_final=True)
+    assert any("forbidden_token:hook_ready" in item for item in failures)
+
+
+def test_naming_helper_topic_mse_a1_no_pending():
+    names = pkg_prov.canonical_release_names(
+        role="review-compact",
+        stage="final-review",
+        delivery_commit=TIP,
+        topic="mse-a1",
+        actual_zip_basename="prod2u-review-compact-mse-a1-aaaaaaaa.zip",
+    )
+    assert names["topic"] == "mse-a1"
+    assert names["zip_basename"] == "prod2u-review-compact-mse-a1-aaaaaaaa.zip"
+    assert "PENDING" not in names["selftest_basename"]
+    assert names["selftest_basename"].endswith(".selftest.json")
+    with pytest.raises(ValueError):
+        pkg_prov.canonical_release_names(
+            role="review-compact",
+            stage="final-review",
+            delivery_commit=TIP,
+            actual_zip_basename="PENDING.zip",
+        )
+
+
+def test_intermediate_names_do_not_assume_final():
+    names = pkg_prov.canonical_release_names(
+        role="review-compact",
+        stage="intermediate-review",
+        delivery_commit=TIP,
+        topic="mse-a1",
+    )
+    assert "intermediate" in names["zip_basename"]
+    final = pkg_prov.canonical_release_names(
+        role="review-compact",
+        stage="final-review",
+        delivery_commit=TIP,
+        topic="mse-a1",
+    )
+    assert names["zip_basename"] != final["zip_basename"]
+
+
+def test_r7_matrix_path_is_process_not_canonical():
+    path = "receipts/mse-r7-matrix/mse-r7-20260812T132652Z/lanes/formal-receipt.json"
+    assert evidence_canon.is_process_evidence(path)
+    assert evidence_canon.workspace_canonical_path(path) is None
+
+
+def test_stale_doc_line_without_negation():
+    text = "Unified matrix run_id | `mse-r7-20260812T132652Z`"
+    assert cur_ev.stale_current_doc_failures(text)
+    ok = "R7 matrix(历史,非 current) | `mse-r7-20260812T132652Z`"
+    assert cur_ev.stale_current_doc_failures(ok) == []

+ 64 - 0
tests/unit/test_mse_r10_release_validation.py

@@ -0,0 +1,64 @@
+"""Round-10: release-validation must fail-closed on skipped/fail sidecars."""
+
+from __future__ import annotations
+
+import json
+import zipfile
+from pathlib import Path
+from unittest import mock
+
+from tools import release_validation as rv
+
+
+def _touch_zip(path: Path) -> None:
+    with zipfile.ZipFile(path, "w") as zf:
+        zf.writestr("meta/release-set-identity.json", "{}")
+
+
+def test_r9_fail_open_scenario_now_fails(tmp_path: Path):
+    review = tmp_path / "review.zip"
+    firmware = tmp_path / "fw.zip"
+    _touch_zip(review)
+    _touch_zip(firmware)
+    review_st = tmp_path / "review-selftest.json"
+    fw_st = tmp_path / "fw-selftest.json"
+    relset = tmp_path / "release-set.json"
+    review_st.write_text(json.dumps({"status": "fail"}), encoding="utf-8")
+    fw_st.write_text(json.dumps({"status": "fail"}), encoding="utf-8")
+    relset.write_text(json.dumps({"status": "fail"}), encoding="utf-8")
+
+    with mock.patch.object(
+        rv, "verify_cross_package", return_value={"status": "pass", "failures": []}
+    ), mock.patch.object(
+        rv,
+        "run_compact_zip_selftest",
+        return_value={"status": "skipped", "reason": "selftest_entry_not_found"},
+    ):
+        result = rv.validate_release(
+            review_zip=review,
+            firmware_zip=firmware,
+            review_selftest_json=review_st,
+            firmware_selftest_json=fw_st,
+            release_set_json=relset,
+        )
+    assert result["status"] == "fail"
+    joined = " ".join(result["failures"])
+    assert "review_standalone_selftest_fail" in joined
+    assert "review_selftest_sidecar_not_pass" in joined
+    assert "firmware_selftest_sidecar_not_pass" in joined
+    assert "external_release_set_not_pass" in joined
+
+
+def test_missing_sidecars_fail(tmp_path: Path):
+    review = tmp_path / "review.zip"
+    firmware = tmp_path / "fw.zip"
+    _touch_zip(review)
+    _touch_zip(firmware)
+    with mock.patch.object(
+        rv, "verify_cross_package", return_value={"status": "pass", "failures": []}
+    ), mock.patch.object(
+        rv, "run_compact_zip_selftest", return_value={"status": "pass"}
+    ):
+        result = rv.validate_release(review_zip=review, firmware_zip=firmware)
+    assert result["status"] == "fail"
+    assert any("not_provided" in f for f in result["failures"])

+ 102 - 0
tests/unit/test_mse_r10_td_resources.py

@@ -0,0 +1,102 @@
+"""Round-10: TD resource parser and production-source hash compare."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from tools import package_provenance as pkg_prov
+
+ROOT = Path(__file__).resolve().parents[2]
+
+
+def test_parse_td_resources_keeps_explicit_mslice_1089():
+    compact = {
+        "lut": 3901,
+        "mslice": 1089,
+        "dsp": 1,
+        "resources": {
+            "utilization": {
+                "lut": {"used": 4320},
+                "dsp": {"used": 1},
+            },
+            "packing": {"mslice": 1089, "lslice": 1089, "total_slices": 2178},
+        },
+    }
+    parsed = pkg_prov.parse_td_resource_fields(compact)
+    assert parsed["lut"] == 4320
+    assert parsed["mslice"] == 1089
+    assert parsed["dsp"] == 1
+
+
+def test_parse_td_resources_never_falls_back_lut_to_mslice():
+    compact = {
+        "resources": {
+            "utilization": {
+                "lut": {"used": 4320},
+                "le": {"used": 4320},
+                "dsp": {"used": 1},
+            }
+        }
+    }
+    parsed = pkg_prov.parse_td_resource_fields(compact)
+    assert parsed["lut"] == 4320
+    assert parsed["mslice"] is None
+    assert parsed["dsp"] == 1
+
+
+def test_canonical_identity_mslice_is_1089_not_4320():
+    td = pkg_prov.load_canonical_td_a1_fields(ROOT)
+    ident = pkg_prov.build_shared_release_identity(
+        delivery_commit="d91a7b46a37371d9a03ae47c5245da2eb4561772",
+        package_stage="intermediate-review",
+        matrix_verification_tip="d126c3df0ceef3de4d559b60253fb5336da11922",
+        software_verification_run_id="mse-r9-20260812T163229Z",
+        config_fingerprint="x",
+        reference_set_fingerprint="y",
+        repo_root=ROOT,
+        claim_bound_bitstream=True,
+    )
+    assert td["mslice"] == 1089
+    assert ident["mslice"] == 1089
+    assert ident["lut"] == 4320
+
+
+def test_artifact_to_delivery_hash_compare_not_commit_equality():
+    artifact = "ff44128a540b7ffd9d82314093b242ac3aee92d7"
+    delivery = "d91a7b46a37371d9a03ae47c5245da2eb4561772"
+    assert artifact != delivery
+    cmp_ = pkg_prov.compare_production_source_commits(
+        from_commit=artifact,
+        to_commit=delivery,
+        repo_root=ROOT,
+    )
+    assert cmp_["unchanged"] is True
+    assert cmp_["production_changed_paths"] == []
+    rel = pkg_prov.build_source_closure_relations(
+        old_baseline_commit=pkg_prov.BASE_DEV_COMMIT_DEFAULT,
+        artifact_commit=artifact,
+        delivery_commit=delivery,
+        old_to_artifact_unchanged=False,
+        artifact_to_delivery_unchanged=True,
+        old_to_artifact_changed_paths=["projects/prod2u-door-temp/project.json"],
+        artifact_to_delivery_changed_paths=[],
+        comparison_mode="snapshot_hash",
+    )
+    check = pkg_prov.validate_source_closure_relations(rel)
+    assert check["status"] == "pass", check
+
+
+def test_snapshot_hash_false_empty_paths_fails():
+    rel = pkg_prov.build_source_closure_relations(
+        old_baseline_commit=pkg_prov.BASE_DEV_COMMIT_DEFAULT,
+        artifact_commit="aa",
+        delivery_commit="bb",
+        old_to_artifact_unchanged=False,
+        artifact_to_delivery_unchanged=False,
+        old_to_artifact_changed_paths=[],
+        artifact_to_delivery_changed_paths=[],
+        comparison_mode="snapshot_hash",
+    )
+    check = pkg_prov.validate_source_closure_relations(rel)
+    assert check["status"] == "fail"
+    assert any("empty_paths" in f for f in check["failures"])

+ 4 - 0
tests/unit/test_mse_r9_td_identity.py

@@ -19,6 +19,10 @@ def test_load_canonical_td_a1_fields_has_run_id_and_receipt_sha():
     assert td["td_bound_commit"].startswith("ff44128a")
     assert td["td_bound_commit"].startswith("ff44128a")
     assert td["td_verification_run_id"] == "2026081201454269af8dbc0000000000"
     assert td["td_verification_run_id"] == "2026081201454269af8dbc0000000000"
     assert td["td_binding_status"] == "pass"
     assert td["td_binding_status"] == "pass"
+    assert td["lut"] == 4320
+    assert td["mslice"] == 1089
+    assert td["dsp"] == 1
+    assert td["mslice"] != td["lut"]
 
 
 
 
 def test_shared_identity_never_null_when_claiming_bitstream():
 def test_shared_identity_never_null_when_claiming_bitstream():

+ 142 - 10
tools/build_firmware_package.py

@@ -388,11 +388,110 @@ def _selftest_package(
         if bad is not None:
         if bad is not None:
             failures.append(f"crc_failed:{bad}")
             failures.append(f"crc_failed:{bad}")
 
 
-        manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
-        if manifest["bitstream_sha256"] != expected_manifest["bitstream_sha256"]:
-            failures.append("bitstream_sha_manifest_mismatch")
-        if "release_set_id" not in manifest:
-            failures.append("missing_release_set_id_in_manifest")
+        bit_names = [name for name in names if name.casefold().endswith(".bit")]
+        if "fw.bit" in names and len(bit_names) != 1:
+            failures.append(f"multiple_or_unexpected_bitstreams:{bit_names}")
+
+        for name in names:
+            lower = name.casefold()
+            if lower.endswith((".brd", ".pdf", ".dsn")):
+                failures.append(f"raw_reference_in_firmware:{name}")
+            if name.startswith("td/") and "td_20260630" in name:
+                failures.append(f"stale_td_log_in_package:{name}")
+            if "PENDING" in name.upper() or "hook_ready" in lower:
+                failures.append(f"forbidden_firmware_member:{name}")
+
+        sums_text = ""
+        if "SHA256SUMS.txt" in names:
+            sums_text = zipf.read("SHA256SUMS.txt").decode("ascii", errors="replace")
+            seen: dict[str, str] = {}
+            for line in sums_text.splitlines():
+                line = line.strip()
+                if not line or line.startswith("#"):
+                    continue
+                digest, _, member = line.partition("  ")
+                if len(digest) != 64 or not member:
+                    failures.append(f"sha256sums_bad_line:{line}")
+                    continue
+                if member in seen:
+                    failures.append(f"sha256sums_duplicate:{member}")
+                    continue
+                seen[member] = digest.casefold()
+                if member not in names:
+                    failures.append(f"sha256sums_missing_file:{member}")
+                    continue
+                actual = _sha256_bytes(zipf.read(member))
+                if actual != digest.casefold():
+                    failures.append(f"sha256sums_mismatch:{member}")
+            for key in (
+                "fw.bit",
+                "BITSTREAM-SHA256.txt",
+                "PACKAGE-MANIFEST.json",
+                "meta/release-set-identity.json",
+                "td/original-final_td_report.json",
+            ):
+                if key in names and key not in seen:
+                    failures.append(f"sha256sums_omitted_key:{key}")
+
+        bit_digest = _sha256_bytes(zipf.read("fw.bit")) if "fw.bit" in names else ""
+        if "BITSTREAM-SHA256.txt" in names and bit_digest:
+            declared = zipf.read("BITSTREAM-SHA256.txt").decode("ascii", errors="replace").strip().split()[0]
+            if declared.casefold() != bit_digest:
+                failures.append("bitstream_sha_mismatch_txt")
+
+        manifest = {}
+        if "PACKAGE-MANIFEST.json" in names:
+            manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
+            if expected_manifest.get("bitstream_sha256") and manifest.get(
+                "bitstream_sha256"
+            ) != expected_manifest["bitstream_sha256"]:
+                failures.append("bitstream_sha_manifest_mismatch")
+            if bit_digest and str(manifest.get("bitstream_sha256") or "").casefold() != bit_digest:
+                failures.append("bitstream_sha_mismatch_manifest")
+            if "release_set_id" not in manifest:
+                failures.append("missing_release_set_id_in_manifest")
+            hw = str(manifest.get("hardware_validation") or "").casefold().replace(" ", "_")
+            if hw not in {"not_run", "not-run"}:
+                failures.append(f"manifest_hardware_not_not_run:{manifest.get('hardware_validation')}")
+
+        identity: dict[str, Any] = {}
+        if "meta/release-set-identity.json" in names:
+            identity = json.loads(zipf.read("meta/release-set-identity.json"))
+            ident_blob = json.dumps(identity)
+            for token in ("PENDING", "pending_package", "hook_ready"):
+                if token in ident_blob:
+                    failures.append(f"identity_forbidden_token:{token}")
+            if bit_digest and str(identity.get("bitstream_sha256") or "").casefold() != bit_digest:
+                failures.append("bitstream_sha_mismatch_release_identity")
+            delivery_txt = ""
+            if "DELIVERY-COMMIT.txt" in names:
+                delivery_txt = zipf.read("DELIVERY-COMMIT.txt").decode("ascii", errors="replace").strip().split()[0]
+            if delivery_txt and str(identity.get("delivery_commit") or "") != delivery_txt:
+                failures.append("identity_delivery_mismatch_txt")
+            if str(identity.get("base_dev_commit") or "") != BASE_DEV_COMMIT_DEFAULT:
+                failures.append("identity_base_dev_mismatch")
+            if not str(identity.get("td_artifact_run_id") or "").strip():
+                failures.append("identity_missing_td_artifact_run_id")
+            if not str(identity.get("td_receipt_sha256") or "").strip():
+                failures.append("identity_missing_td_receipt_sha256")
+            if not str(
+                identity.get("matrix_verification_tip") or identity.get("verification_tip") or ""
+            ).strip():
+                failures.append("identity_missing_matrix_tip")
+            if str(identity.get("package_stage") or "") == "final-review":
+                if str(identity.get("td_binding_status") or "").casefold() != "pass":
+                    failures.append("identity_td_binding_not_pass")
+            lut = identity.get("lut")
+            mslice = identity.get("mslice")
+            if (
+                lut is not None
+                and mslice is not None
+                and lut == mslice
+                and lut not in (0, 0.0, "0")
+            ):
+                failures.append("identity_mslice_equals_lut")
+            if str(identity.get("release_set_id") or "") != str(manifest.get("release_set_id") or ""):
+                failures.append("identity_release_set_id_mismatch_manifest")
 
 
         if "meta/release-set-sibling.json" in names:
         if "meta/release-set-sibling.json" in names:
             sibling = json.loads(zipf.read("meta/release-set-sibling.json"))
             sibling = json.loads(zipf.read("meta/release-set-sibling.json"))
@@ -400,11 +499,30 @@ def _selftest_package(
                 failures.append("sibling_contains_cyclic_zip_sha")
                 failures.append("sibling_contains_cyclic_zip_sha")
             if sibling.get("release_set_id") != manifest.get("release_set_id"):
             if sibling.get("release_set_id") != manifest.get("release_set_id"):
                 failures.append("sibling_release_set_id_mismatch")
                 failures.append("sibling_release_set_id_mismatch")
-
-        # Detect stale repo TD logs from ROOT/td that should not be present
-        for name in names:
-            if name.startswith("td/") and "td_20260630" in name:
-                failures.append(f"stale_td_log_in_package:{name}")
+            if sibling.get("this_role") not in {None, "firmware"}:
+                failures.append("sibling_role_unexpected")
+            expected = str(sibling.get("sibling_expected_filename") or "")
+            if expected:
+                if "PENDING" in expected.upper():
+                    failures.append("sibling_filename_pending")
+                if "door-percent" in expected.casefold() and "mse-a1" not in expected.casefold():
+                    failures.append("sibling_stale_door_percent")
+                topic = pkg_prov.release_task_slug()
+                if topic == "mse-a1" and "mse-a1" not in expected and expected:
+                    failures.append("sibling_topic_not_mse_a1")
+
+        if "meta/source-closure-relations.json" in names:
+            relations = json.loads(zipf.read("meta/source-closure-relations.json"))
+            rel_check = pkg_prov.validate_source_closure_relations(relations)
+            if rel_check.get("status") != "pass":
+                failures.extend(
+                    f"relations:{item}" for item in (rel_check.get("failures") or ["fail"])
+                )
+
+        if "meta/REFERENCE-POINTER.json" in names:
+            pointer = json.loads(zipf.read("meta/REFERENCE-POINTER.json"))
+            if pointer.get("include_raw_reference") is True:
+                failures.append("reference_pointer_includes_raw")
 
 
     return {
     return {
         "status": "fail" if failures else "pass",
         "status": "fail" if failures else "pass",
@@ -415,6 +533,20 @@ def _selftest_package(
     }
     }
 
 
 
 
+def run_firmware_zip_selftest(zip_path: Path) -> dict[str, Any]:
+    """Public firmware ZIP selftest (tamper / sidecar reuse)."""
+    zip_path = zip_path.expanduser().resolve(strict=True)
+    with zipfile.ZipFile(zip_path, "r", allowZip64=True) as zipf:
+        if "PACKAGE-MANIFEST.json" not in zipf.namelist():
+            return {
+                "status": "fail",
+                "failures": ["missing_package_manifest"],
+                "package_path": str(zip_path),
+            }
+        manifest = json.loads(zipf.read("PACKAGE-MANIFEST.json"))
+    return _selftest_package(zip_path=zip_path, expected_manifest=manifest, td_root=zip_path.parent)
+
+
 def build_firmware_package(
 def build_firmware_package(
     *,
     *,
     output_dir: Path,
     output_dir: Path,

+ 151 - 56
tools/compact_package_selftest.py

@@ -27,6 +27,8 @@ if str(TOOLS) not in sys.path:
     sys.path.insert(0, str(TOOLS))
     sys.path.insert(0, str(TOOLS))
 
 
 import package_agent_handoff as handoff  # noqa: E402
 import package_agent_handoff as handoff  # noqa: E402
+import package_provenance as pkg_prov  # noqa: E402
+import current_evidence as cur_ev  # noqa: E402
 from replay_review_compact import replay_review_compact  # noqa: E402
 from replay_review_compact import replay_review_compact  # noqa: E402
 
 
 SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
 SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
@@ -379,35 +381,119 @@ def check_source_matches_delivery_tree(
     return failures
     return failures
 
 
 
 
-def check_final_canonical_evidence(archive: zipfile.ZipFile, members: list[str]) -> list[str]:
-    """Fail-closed: final-review ZIP must contain mandatory evidence entities."""
+def _find_member(members: list[str], suffix: str) -> str | None:
+    want = suffix.replace("\\", "/").casefold()
+    for name in members:
+        if _member_logical(name).endswith(want):
+            return name
+    return None
+
+
+def check_final_evidence_paths(archive: zipfile.ZipFile, members: list[str]) -> list[str]:
+    """Path-only presence check (no JSON semantics)."""
+    del archive
     failures: list[str] = []
     failures: list[str] = []
     logicals = {_member_logical(name) for name in members}
     logicals = {_member_logical(name) for name in members}
     for suffix in FINAL_MANDATORY_EVIDENCE_SUFFIXES:
     for suffix in FINAL_MANDATORY_EVIDENCE_SUFFIXES:
         suffix_cf = suffix.casefold()
         suffix_cf = suffix.casefold()
         if not any(item.endswith(suffix_cf) for item in logicals):
         if not any(item.endswith(suffix_cf) for item in logicals):
             failures.append(f"missing_final_evidence:{suffix}")
             failures.append(f"missing_final_evidence:{suffix}")
+    return failures
 
 
-    bit_member = next(
-        (
-            name
-            for name in members
-            if _member_logical(name).endswith(
-                "evidence/bitstream/prod2u_p4_normal_v3.bit".casefold()
-            )
-        ),
-        None,
+
+def _non_historical_members(members: list[str], suffix: str) -> list[str]:
+    want = suffix.replace("\\", "/").casefold()
+    hits: list[str] = []
+    for name in members:
+        logical = _member_logical(name)
+        if not logical.endswith(want):
+            continue
+        if "/historical/" in f"/{logical}/":
+            continue
+        hits.append(name)
+    return hits
+
+
+def check_final_canonical_evidence(archive: zipfile.ZipFile, members: list[str]) -> list[str]:
+    """Fail-closed: final-review ZIP must contain and semantically match current evidence."""
+    failures: list[str] = []
+    failures.extend(check_final_evidence_paths(archive, members))
+
+    matrix_hits = _non_historical_members(
+        members, "evidence/matrix/verification-matrix-final.json"
     )
     )
-    sha_member = next(
-        (
-            name
-            for name in members
-            if _member_logical(name).endswith(
-                "evidence/bitstream/BITSTREAM-SHA256.txt".casefold()
+    formal_hits = _non_historical_members(members, "evidence/formal/formal-receipt.json")
+    if len(matrix_hits) > 1:
+        failures.append("multiple_current_matrix")
+    if len(formal_hits) > 1:
+        failures.append("multiple_current_formal")
+
+    identity = _read_zip_json(archive, "meta/release-set-identity.json")
+    head_member = _find_member(members, "meta/git/HEAD.txt")
+    zip_head = None
+    if head_member:
+        try:
+            zip_head = (
+                archive.read(head_member).decode("ascii", errors="replace").strip().split()[0]
             )
             )
-        ),
-        None,
+        except Exception as exc:  # noqa: BLE001
+            failures.append(f"zip_head_read_error:{exc}")
+    failures.extend(
+        cur_ev.validate_release_identity(
+            identity, zip_head=zip_head, require_final=True
+        )
+    )
+    tip = None
+    run_id = None
+    if isinstance(identity, dict):
+        tip = str(
+            identity.get("matrix_verification_tip") or identity.get("verification_tip") or ""
+        ).strip() or None
+        run_id = str(
+            identity.get("software_verification_run_id")
+            or identity.get("verification_run_id")
+            or ""
+        ).strip() or None
+        stage = str(identity.get("package_stage") or "")
+        profile = str(identity.get("package_profile") or identity.get("role") or "")
+        if stage and stage != "final-review":
+            failures.append(f"package_stage_not_final:{stage}")
+        if profile in {"firmware", "intermediate-review"}:
+            failures.append(f"package_role_unexpected:{profile}")
+
+    matrix_doc = _read_zip_json(archive, "evidence/matrix/verification-matrix-final.json")
+    failures.extend(
+        cur_ev.validate_matrix_report(matrix_doc, verification_tip=tip, run_id=run_id)
     )
     )
+    formal_doc = _read_zip_json(archive, "evidence/formal/formal-receipt.json")
+    failures.extend(cur_ev.validate_formal_receipt(formal_doc, verification_tip=tip))
+
+    relations = _read_zip_json(archive, "meta/source-closure-relations.json")
+    rel_check = pkg_prov.validate_source_closure_relations(relations)
+    if rel_check.get("status") != "pass":
+        failures.extend(f"relations:{item}" for item in (rel_check.get("failures") or ["fail"]))
+
+    closure = _read_zip_json(archive, "meta/verification-to-delivery-closure.json")
+    if not isinstance(closure, dict) or not closure:
+        failures.append("missing_verification_to_delivery_closure")
+    else:
+        if closure.get("closure_ok") is not True:
+            failures.append("closure_ok_not_true")
+        if tip and not cur_ev.commits_match(
+            str(closure.get("verification_tip") or ""), tip
+        ):
+            failures.append("closure_tip_mismatch")
+        actual = str(closure.get("delivery_commit") or closure.get("actual_head") or "")
+        if zip_head and actual and actual != zip_head:
+            failures.append("closure_head_mismatch")
+        forbidden = closure.get("forbidden_changed_paths") or []
+        if forbidden:
+            failures.append("closure_forbidden_paths_present")
+
+    bit_member = _find_member(members, "evidence/bitstream/prod2u_p4_normal_v3.bit")
+    sha_member = _find_member(members, "evidence/bitstream/BITSTREAM-SHA256.txt")
+    if bit_member is None:
+        failures.append("missing_actual_bitstream_bytes")
     if bit_member and sha_member:
     if bit_member and sha_member:
         try:
         try:
             bit_digest = hashlib.sha256(archive.read(bit_member)).hexdigest()
             bit_digest = hashlib.sha256(archive.read(bit_member)).hexdigest()
@@ -416,52 +502,61 @@ def check_final_canonical_evidence(archive: zipfile.ZipFile, members: list[str])
             )
             )
             if declared.casefold() != bit_digest.casefold():
             if declared.casefold() != bit_digest.casefold():
                 failures.append("bitstream_sha_mismatch_txt")
                 failures.append("bitstream_sha_mismatch_txt")
-            identity = _read_zip_json(archive, "meta/release-set-identity.json")
             if isinstance(identity, dict):
             if isinstance(identity, dict):
                 ident_bit = str(identity.get("bitstream_sha256") or "").casefold()
                 ident_bit = str(identity.get("bitstream_sha256") or "").casefold()
                 if ident_bit and ident_bit != bit_digest.casefold():
                 if ident_bit and ident_bit != bit_digest.casefold():
                     failures.append("bitstream_sha_mismatch_release_identity")
                     failures.append("bitstream_sha_mismatch_release_identity")
-                # Round-9: claiming a bitstream requires non-null TD identity fields.
                 if ident_bit:
                 if ident_bit:
-                    if not str(identity.get("td_artifact_run_id") or "").strip():
-                        failures.append("release_set_identity_missing_td_artifact_run_id")
-                    if not str(identity.get("td_receipt_sha256") or "").strip():
-                        failures.append("release_set_identity_missing_td_receipt_sha256")
                     if str(identity.get("td_binding_status") or "").casefold() != "pass":
                     if str(identity.get("td_binding_status") or "").casefold() != "pass":
                         failures.append("release_set_identity_td_binding_not_pass")
                         failures.append("release_set_identity_td_binding_not_pass")
-                    stage = str(identity.get("package_stage") or "")
-                    if stage == "final-review":
-                        if not str(
-                            identity.get("matrix_verification_tip")
-                            or identity.get("verification_tip")
-                            or ""
-                        ).strip():
-                            failures.append("release_set_identity_missing_matrix_tip")
-                        head_member = next(
-                            (
-                                name
-                                for name in members
-                                if _member_logical(name).endswith("meta/git/HEAD.txt")
-                            ),
-                            None,
-                        )
-                        if head_member:
-                            try:
-                                head = (
-                                    archive.read(head_member)
-                                    .decode("ascii", errors="replace")
-                                    .strip()
-                                    .split()[0]
-                                )
-                                delivery = str(identity.get("delivery_commit") or "")
-                                if delivery and head and delivery != head:
-                                    failures.append(
-                                        "release_identity_delivery_ne_zip_head"
-                                    )
-                            except Exception as exc:  # noqa: BLE001
-                                failures.append(f"zip_head_read_error:{exc}")
         except Exception as exc:  # noqa: BLE001
         except Exception as exc:  # noqa: BLE001
             failures.append(f"bitstream_sha_check_error:{exc}")
             failures.append(f"bitstream_sha_check_error:{exc}")
+
+    td_bind = _read_zip_json(archive, "evidence/td/td-tip-bind-receipt.json")
+    if isinstance(td_bind, dict):
+        st = str(td_bind.get("status") or "").casefold()
+        if st in {"hook_ready", "hook_partial", "deferred", "pending"}:
+            failures.append(f"td_binding_not_pass:{st}")
+        elif st and st != "pass":
+            failures.append(f"td_binding_not_pass:{st}")
+
+    pointer = _read_zip_json(archive, "evidence/selftest/compact-package-selftest-pointer.json")
+    if isinstance(pointer, dict):
+        expected = str(pointer.get("expected_external_selftest_filename") or "")
+        if not expected or "PENDING" in expected.upper():
+            failures.append("selftest_pointer_pending_or_empty")
+        topic = str(pointer.get("topic") or "")
+        if topic and topic != "mse-a1":
+            failures.append(f"selftest_pointer_topic:{topic}")
+        actual = str(pointer.get("actual_zip_basename") or "")
+        if actual and "PENDING" in actual.upper():
+            failures.append("selftest_pointer_actual_pending")
+        if "door-percent" in expected.casefold() and "mse-a1" not in expected.casefold():
+            failures.append("selftest_pointer_stale_door_percent")
+
+    for rel in (
+        "source/README.zh-CN.md",
+        "source/FINAL_DELIVERY_REPORT.md",
+        "source/ACCEPTANCE_MATRIX.md",
+        "source/PLAN.md",
+        "source/OPEN_QUESTIONS.md",
+        "README.zh-CN.md",
+        "FINAL_DELIVERY_REPORT.md",
+    ):
+        member = _find_member(members, rel)
+        if member is None:
+            continue
+        try:
+            text = archive.read(member).decode("utf-8", errors="replace")
+        except Exception as exc:  # noqa: BLE001
+            failures.append(f"active_doc_read_error:{rel}:{exc}")
+            continue
+        failures.extend(cur_ev.stale_current_doc_failures(text))
+
+    blob_names = " ".join(_member_logical(name) for name in members)
+    for token in ("PENDING", "pending_package", "hook_ready"):
+        if token in blob_names:
+            failures.append(f"forbidden_member_token:{token}")
     return failures
     return failures
 
 
 
 

+ 52 - 0
tools/cross_package_verify.py

@@ -139,6 +139,58 @@ def verify_cross_package(review_zip: Path, firmware_zip: Path) -> dict[str, Any]
             failures.append("review_sibling_role_unexpected")
             failures.append("review_sibling_role_unexpected")
         if f_sib.get("this_role") not in {None, "firmware"}:
         if f_sib.get("this_role") not in {None, "firmware"}:
             failures.append("firmware_sibling_role_unexpected")
             failures.append("firmware_sibling_role_unexpected")
+        review_name = Path(review_zip).name
+        firmware_name = Path(firmware_zip).name
+        if f_sib.get("sibling_expected_filename") and f_sib.get(
+            "sibling_expected_filename"
+        ) != review_name:
+            # Pointer names the sibling ZIP; allow topic-canonical match only.
+            expected = str(f_sib.get("sibling_expected_filename") or "")
+            if expected and expected != review_name:
+                failures.append("firmware_sibling_basename_mismatch")
+        if r_sib.get("sibling_expected_filename") and r_sib.get(
+            "sibling_expected_filename"
+        ) != firmware_name:
+            expected = str(r_sib.get("sibling_expected_filename") or "")
+            if expected and expected != firmware_name:
+                failures.append("review_sibling_basename_mismatch")
+        for label, ident in (("review", r_ident), ("firmware", f_ident)):
+            if not ident:
+                continue
+            for key in (
+                "base_dev_commit",
+                "td_bound_commit",
+                "artifact_source_commit",
+                "delivery_commit",
+                "td_verification_run_id",
+                "td_artifact_run_id",
+                "td_receipt_sha256",
+                "production_binding",
+                "reference_set_fingerprint",
+            ):
+                if ident.get(key) in (None, "", "null"):
+                    failures.append(f"{label}_identity_incomplete:{key}")
+            hw = str(ident.get("hardware_validation") or "").casefold().replace(" ", "_")
+            if hw not in {"not_run", "not-run"}:
+                failures.append(f"{label}_hardware_not_not_run")
+            if ident.get("release_set_id") and r_ident.get("release_set_id") != f_ident.get(
+                "release_set_id"
+            ):
+                pass  # already reported
+        if r_ident and f_ident:
+            r_set = r_ident.get("release_set_id")
+            f_set = f_ident.get("release_set_id")
+            if r_set == f_set:
+                for key in SHARED_IDENTITY_KEYS:
+                    if key == "release_set_id":
+                        continue
+                    rv = r_ident.get(key)
+                    fv = f_ident.get(key)
+                    if key == "matrix_verification_tip":
+                        rv = rv or r_ident.get("verification_tip")
+                        fv = fv or f_ident.get("verification_tip")
+                    if rv != fv:
+                        failures.append(f"same_release_set_divergent_identity:{key}")
 
 
     return {
     return {
         "status": "fail" if failures else "pass",
         "status": "fail" if failures else "pass",

+ 387 - 0
tools/current_evidence.py

@@ -0,0 +1,387 @@
+#!/usr/bin/env python3
+"""Select current matrix / Formal evidence by explicit tip + run ID.
+
+Never use "last same basename", hardcoded R7/R8 paths, or directory-scan order.
+Historical receipts stay under receipts/historical/ or receipts/mse-rN-matrix/
+and are not current authority unless that run_id is the explicit selector.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import re
+from pathlib import Path
+from typing import Any
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+REQUIRED_MATRIX_LANES = (
+    "python",
+    "board_viewer",
+    "icarus",
+    "verilator",
+    "cocotb",
+    "formal",
+)
+REQUIRED_FORMAL_TARGET_COUNT = 23
+DISPATCHER_TARGET = "door_rate_quantum_dispatcher"
+DISPATCHER_COVER_EXACT = 10
+CANONICAL_MATRIX_REL = "evidence/matrix/verification-matrix-final.json"
+CANONICAL_FORMAL_REL = "evidence/formal/formal-receipt.json"
+STALE_CURRENT_TOKENS = (
+    "mse-r7-20260812T132652Z",
+    "21ed755ad2ddb6689bca88a9a037b391372a060e",
+    "3177c2f01070b32460dee826e41b685f482fea26",
+)
+FORBIDDEN_IDENTITY_TOKENS = ("PENDING", "pending_package", "hook_ready")
+
+
+class CurrentEvidenceError(RuntimeError):
+    """Fail-closed current-evidence selection or validation error."""
+
+
+def _sha256_file(path: Path) -> str:
+    digest = hashlib.sha256()
+    with path.open("rb") as handle:
+        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+            digest.update(chunk)
+    return digest.hexdigest()
+
+
+def commits_match(left: str | None, right: str | None) -> bool:
+    a = str(left or "").strip().casefold()
+    b = str(right or "").strip().casefold()
+    if not a or not b:
+        return False
+    n = min(len(a), len(b))
+    if n < 7:
+        return False
+    return a[:n] == b[:n]
+
+
+def matrix_family_dir(run_id: str) -> str:
+    """mse-r10-20260813T010203Z → mse-r10-matrix (explicit, not a glob)."""
+    text = str(run_id or "").strip()
+    parts = text.split("-")
+    if len(parts) < 3 or parts[0] != "mse" or not parts[1].startswith("r"):
+        raise CurrentEvidenceError(f"bad_matrix_run_id:{run_id}")
+    return f"{parts[0]}-{parts[1]}-matrix"
+
+
+def current_matrix_path(
+    repo: Path,
+    *,
+    run_id: str,
+    override: str | None = None,
+) -> Path:
+    explicit = (override or os.environ.get("PRODU2_CURRENT_MATRIX_PATH", "")).strip()
+    if explicit:
+        path = Path(explicit)
+        if not path.is_absolute():
+            path = repo / path
+        return path
+    family = matrix_family_dir(run_id)
+    return repo / "receipts" / family / run_id / "unified-matrix-report.json"
+
+
+def current_formal_path(
+    repo: Path,
+    *,
+    run_id: str,
+    override: str | None = None,
+) -> Path:
+    explicit = (override or os.environ.get("PRODU2_CURRENT_FORMAL_PATH", "")).strip()
+    if explicit:
+        path = Path(explicit)
+        if not path.is_absolute():
+            path = repo / path
+        return path
+    family = matrix_family_dir(run_id)
+    return repo / "receipts" / family / run_id / "lanes" / "formal-receipt.json"
+
+
+def select_current_matrix(
+    repo: Path,
+    *,
+    verification_tip: str,
+    run_id: str,
+) -> Path:
+    path = current_matrix_path(repo, run_id=run_id)
+    if not path.is_file():
+        raise CurrentEvidenceError(f"missing_current_matrix:{path}")
+    doc = json.loads(path.read_text(encoding="utf-8"))
+    failures = validate_matrix_report(
+        doc, verification_tip=verification_tip, run_id=run_id
+    )
+    if failures:
+        raise CurrentEvidenceError("current_matrix_invalid:" + ",".join(failures[:12]))
+    return path
+
+
+def select_current_formal(
+    repo: Path,
+    *,
+    verification_tip: str,
+    run_id: str,
+) -> Path:
+    path = current_formal_path(repo, run_id=run_id)
+    if not path.is_file():
+        raise CurrentEvidenceError(f"missing_current_formal:{path}")
+    doc = json.loads(path.read_text(encoding="utf-8"))
+    failures = validate_formal_receipt(doc, verification_tip=verification_tip)
+    if failures:
+        raise CurrentEvidenceError("current_formal_invalid:" + ",".join(failures[:12]))
+    return path
+
+
+def stage_current_evidence(
+    *,
+    repo: Path,
+    staging_root: Path,
+    verification_tip: str,
+    run_id: str,
+) -> dict[str, Path]:
+    """Copy the explicitly selected current receipts onto canonical evidence/ paths."""
+    matrix_src = select_current_matrix(
+        repo, verification_tip=verification_tip, run_id=run_id
+    )
+    formal_src = select_current_formal(
+        repo, verification_tip=verification_tip, run_id=run_id
+    )
+    matrix_dest = staging_root / Path(*CANONICAL_MATRIX_REL.split("/"))
+    formal_dest = staging_root / Path(*CANONICAL_FORMAL_REL.split("/"))
+    matrix_dest.parent.mkdir(parents=True, exist_ok=True)
+    formal_dest.parent.mkdir(parents=True, exist_ok=True)
+    matrix_dest.write_bytes(matrix_src.read_bytes())
+    formal_dest.write_bytes(formal_src.read_bytes())
+    return {"matrix": matrix_dest, "formal": formal_dest}
+
+
+def validate_matrix_report(
+    doc: Any,
+    *,
+    verification_tip: str | None = None,
+    run_id: str | None = None,
+) -> list[str]:
+    failures: list[str] = []
+    if not isinstance(doc, dict) or not doc:
+        return ["matrix_not_object_or_empty"]
+    schema = str(doc.get("schema") or "")
+    if "verification-matrix" not in schema.casefold():
+        failures.append(f"matrix_schema_unexpected:{schema or 'empty'}")
+    status = str(doc.get("status") or "").casefold()
+    if status != "pass":
+        failures.append(f"matrix_status_not_pass:{status or 'empty'}")
+    failures_field = doc.get("failures")
+    if failures_field is None:
+        failures.append("matrix_failures_missing")
+    elif failures_field not in ([], ()):
+        failures.append("matrix_failures_not_empty")
+    if verification_tip:
+        commit = str(doc.get("commit_full") or doc.get("commit") or "")
+        if not commits_match(commit, verification_tip):
+            failures.append("matrix_tip_mismatch")
+    lanes = doc.get("lanes")
+    if not isinstance(lanes, dict):
+        failures.append("matrix_lanes_missing")
+        lanes = {}
+    for name in REQUIRED_MATRIX_LANES:
+        lane = lanes.get(name)
+        if not isinstance(lane, dict):
+            failures.append(f"matrix_lane_missing:{name}")
+            continue
+        lane_status = str(lane.get("status") or "").casefold()
+        if lane_status != "pass":
+            failures.append(f"matrix_lane_not_pass:{name}:{lane_status or 'empty'}")
+        if verification_tip:
+            lane_commit = str(lane.get("commit_full") or lane.get("commit") or "")
+            if lane_commit and not commits_match(lane_commit, verification_tip):
+                failures.append(f"matrix_lane_tip_mismatch:{name}")
+        if name == "board_viewer":
+            mode = str(lane.get("mode") or lane.get("selection", {}).get("mode") or "")
+            if mode and mode != "detached_derived":
+                failures.append(f"board_viewer_mode_not_detached_derived:{mode}")
+    if run_id:
+        # User-level run id lives in the receipts path; JSON may use a hex verification_run_id.
+        json_run = str(doc.get("software_verification_run_id") or doc.get("run_id") or "")
+        if json_run and json_run != run_id and run_id not in json_run:
+            # Hex lane ids are expected; only fail when a conflicting mse-r* id is present.
+            if re.match(r"^mse-r\d+-", json_run) and json_run != run_id:
+                failures.append(f"matrix_run_id_mismatch:{json_run}")
+    return failures
+
+
+def validate_formal_receipt(
+    doc: Any,
+    *,
+    verification_tip: str | None = None,
+) -> list[str]:
+    failures: list[str] = []
+    if not isinstance(doc, dict) or not doc:
+        return ["formal_not_object_or_empty"]
+    schema = str(doc.get("schema") or "")
+    if schema != "prod2u-p4-normal-v3-formal-receipt-v1":
+        failures.append(f"formal_schema_unexpected:{schema or 'empty'}")
+    status = str(doc.get("status") or "").casefold()
+    if status != "pass":
+        failures.append(f"formal_status_not_pass:{status or 'empty'}")
+    if verification_tip:
+        commit = str(doc.get("commit_full") or doc.get("commit") or "")
+        if commit and not commits_match(commit, verification_tip):
+            failures.append("formal_tip_mismatch")
+    targets = doc.get("targets")
+    if not isinstance(targets, list):
+        failures.append("formal_targets_missing")
+        return failures
+    if len(targets) != REQUIRED_FORMAL_TARGET_COUNT:
+        failures.append(f"formal_target_count:{len(targets)}")
+    names: list[str] = []
+    dispatcher = None
+    for target in targets:
+        if not isinstance(target, dict):
+            failures.append("formal_target_not_object")
+            continue
+        name = str(target.get("name") or "")
+        names.append(name)
+        t_status = str(target.get("status") or "").casefold()
+        if t_status != "pass":
+            failures.append(f"formal_target_not_pass:{name or '?'}:{t_status or 'empty'}")
+        rc = target.get("returncode")
+        if rc not in (0, "0"):
+            failures.append(f"formal_target_rc:{name}:{rc}")
+        tasks = target.get("task_results")
+        if isinstance(tasks, list):
+            if not tasks:
+                failures.append(f"formal_target_tasks_empty:{name}")
+            for task in tasks:
+                if not isinstance(task, dict):
+                    failures.append(f"formal_task_not_object:{name}")
+                    continue
+                raw = str(task.get("status") or "").casefold()
+                if raw not in {"pass", "passed"}:
+                    failures.append(
+                        f"formal_task_not_pass:{name}:{task.get('name')}:{raw or 'empty'}"
+                    )
+                task_rc = task.get("returncode")
+                if task_rc not in (0, "0"):
+                    failures.append(
+                        f"formal_task_rc:{name}:{task.get('name')}:{task_rc}"
+                    )
+        if name == DISPATCHER_TARGET:
+            dispatcher = target
+    if len(set(names)) != len(names):
+        failures.append("formal_duplicate_target_names")
+    if dispatcher is None:
+        failures.append("formal_dispatcher_missing")
+    else:
+        hit = dispatcher.get("cover_hit_count")
+        count = dispatcher.get("cover_count")
+        ids = dispatcher.get("cover_hit_ids") or []
+        if count != DISPATCHER_COVER_EXACT:
+            failures.append(f"dispatcher_cover_count:{count}")
+        if hit != DISPATCHER_COVER_EXACT:
+            failures.append(f"dispatcher_cover_hit:{hit}")
+        if isinstance(ids, list) and len(ids) not in (0, DISPATCHER_COVER_EXACT):
+            # Some receipts list all 10 ids; empty list with hit_count=10 is still checked above.
+            if len(ids) != DISPATCHER_COVER_EXACT:
+                failures.append(f"dispatcher_cover_ids:{len(ids)}")
+        if dispatcher.get("cover_required") is not True:
+            failures.append("dispatcher_cover_not_required")
+    manifest = doc.get("target_manifest")
+    if isinstance(manifest, dict):
+        expected = manifest.get("expected")
+        if isinstance(expected, dict) and len(expected) != REQUIRED_FORMAL_TARGET_COUNT:
+            failures.append(f"formal_manifest_expected_count:{len(expected)}")
+        m_fail = manifest.get("failures")
+        if m_fail not in (None, [], ()):
+            failures.append("formal_manifest_failures_not_empty")
+    return failures
+
+
+def validate_release_identity(
+    identity: Any,
+    *,
+    zip_head: str | None = None,
+    require_final: bool = True,
+) -> list[str]:
+    failures: list[str] = []
+    if not isinstance(identity, dict) or not identity:
+        return ["release_identity_not_object_or_empty"]
+    schema = str(identity.get("schema") or "")
+    if schema != "prod2u-release-set-identity-v1":
+        failures.append(f"release_identity_schema:{schema or 'empty'}")
+    if not str(identity.get("algorithm_version") or "").strip():
+        failures.append("release_identity_missing_algorithm_version")
+    stage = str(identity.get("package_stage") or "")
+    if require_final and stage != "final-review":
+        failures.append(f"release_identity_stage_not_final:{stage or 'empty'}")
+    required = (
+        "release_set_id",
+        "base_dev_commit",
+        "delivery_commit",
+        "td_bound_commit",
+        "artifact_source_commit",
+        "bitstream_sha256",
+        "td_artifact_run_id",
+        "td_receipt_sha256",
+        "production_binding",
+        "hardware_validation",
+    )
+    for key in required:
+        value = identity.get(key)
+        if value is None or str(value).strip() in {"", "null", "None"}:
+            failures.append(f"release_identity_missing:{key}")
+    tip = str(
+        identity.get("matrix_verification_tip") or identity.get("verification_tip") or ""
+    ).strip()
+    if require_final and not tip:
+        failures.append("release_identity_missing_matrix_tip")
+    run = str(
+        identity.get("software_verification_run_id")
+        or identity.get("verification_run_id")
+        or ""
+    ).strip()
+    if require_final and not run:
+        failures.append("release_identity_missing_matrix_run")
+    if zip_head:
+        delivery = str(identity.get("delivery_commit") or "")
+        if delivery and zip_head and delivery != zip_head:
+            failures.append("release_identity_delivery_ne_zip_head")
+    lut = identity.get("lut")
+    mslice = identity.get("mslice")
+    if require_final:
+        if mslice is None:
+            failures.append("release_identity_mslice_missing")
+        if lut is None:
+            failures.append("release_identity_lut_missing")
+        if lut is not None and mslice is not None and lut == mslice and lut not in (0, 0.0, "0"):
+            failures.append("release_identity_mslice_equals_lut")
+    blob = json.dumps(identity, sort_keys=True)
+    for token in FORBIDDEN_IDENTITY_TOKENS:
+        if token in blob:
+            failures.append(f"release_identity_forbidden_token:{token}")
+    hw = str(identity.get("hardware_validation") or "").casefold().replace(" ", "_")
+    if hw not in {"not_run", "not-run"}:
+        failures.append(f"hardware_validation_not_not_run:{identity.get('hardware_validation')}")
+    return failures
+
+
+def stale_current_doc_failures(text: str) -> list[str]:
+    """Fail when R7/R8 ids are presented as current without historical negation."""
+    failures: list[str] = []
+    negate = re.compile(
+        r"(?i)历史|historical|retired|superseded|不再|不是\s*current|非\s*current|"
+        r"将被|取代|not\s+current|stale"
+    )
+    for token in STALE_CURRENT_TOKENS:
+        for line in text.splitlines():
+            if token not in line:
+                continue
+            if negate.search(line):
+                continue
+            failures.append(f"stale_current_doc:{token}")
+            break
+    return failures

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

@@ -35,6 +35,8 @@ else
   TOPIC="${PRODU2_PACKAGE_TOPIC:-${PRODU2_RELEASE_TASK_SLUG:-mse-a1}}"
   TOPIC="${PRODU2_PACKAGE_TOPIC:-${PRODU2_RELEASE_TASK_SLUG:-mse-a1}}"
   NAME="${PRODU2_PACKAGE_NAME:-prod2u-review-compact-${TOPIC}-${SHORT}}"
   NAME="${PRODU2_PACKAGE_NAME:-prod2u-review-compact-${TOPIC}-${SHORT}}"
 fi
 fi
+# Current matrix/Formal: set PRODU2_VERIFICATION_TIP + PRODU2_VERIFICATION_RUN_ID
+# (explicit tip+run; never hardcoded R7/R8 paths).
 export PRODU2_PACKAGE_TOPIC="${TOPIC}"
 export PRODU2_PACKAGE_TOPIC="${TOPIC}"
 export PRODU2_RELEASE_TASK_SLUG="${TOPIC}"
 export PRODU2_RELEASE_TASK_SLUG="${TOPIC}"
 mkdir -p "$OUT"
 mkdir -p "$OUT"

+ 1 - 0
tools/package-review-debug.sh

@@ -39,6 +39,7 @@ if [[ -n "$(git -C "$ROOT" status --porcelain --untracked-files=all 2>/dev/null
 fi
 fi
 
 
 # Allow PRODU2_PACKAGE_NAME / PRODU2_PACKAGE_TOPIC to name the current MSE round.
 # Allow PRODU2_PACKAGE_NAME / PRODU2_PACKAGE_TOPIC to name the current MSE round.
+# Current matrix/Formal: PRODU2_VERIFICATION_TIP + PRODU2_VERIFICATION_RUN_ID.
 TOPIC="${PRODU2_PACKAGE_TOPIC:-${PRODU2_RELEASE_TASK_SLUG:-mse-a1}}"
 TOPIC="${PRODU2_PACKAGE_TOPIC:-${PRODU2_RELEASE_TASK_SLUG:-mse-a1}}"
 export PRODU2_PACKAGE_TOPIC="${TOPIC}"
 export PRODU2_PACKAGE_TOPIC="${TOPIC}"
 export PRODU2_RELEASE_TASK_SLUG="${TOPIC}"
 export PRODU2_RELEASE_TASK_SLUG="${TOPIC}"

+ 3 - 0
tools/package_evidence_canon.py

@@ -127,6 +127,9 @@ def match_canonical_entry(
     original = (workspace_original or _strip_layout_prefix(relative)).casefold()
     original = (workspace_original or _strip_layout_prefix(relative)).casefold()
     name = _basename(original)
     name = _basename(original)
     package_lower = relative.casefold()
     package_lower = relative.casefold()
+    # Historical / process trees must not become current via basename coincidence.
+    if is_process_evidence(relative, allowlist) or is_process_evidence(original, allowlist):
+        return None
     for entry in allowlist.canonical_entries:
     for entry in allowlist.canonical_entries:
         if original in entry.match_workspace_paths:
         if original in entry.match_workspace_paths:
             return entry
             return entry

+ 237 - 22
tools/package_provenance.py

@@ -12,6 +12,7 @@ from __future__ import annotations
 import hashlib
 import hashlib
 import json
 import json
 import re
 import re
+import subprocess
 from datetime import datetime, timezone
 from datetime import datetime, timezone
 from pathlib import Path
 from pathlib import Path
 from typing import Any
 from typing import Any
@@ -43,27 +44,133 @@ def release_task_slug() -> str:
 RELEASE_TASK_SLUG = _DEFAULT_RELEASE_TASK_SLUG
 RELEASE_TASK_SLUG = _DEFAULT_RELEASE_TASK_SLUG
 
 
 
 
-def release_sibling_filename(kind: str, delivery_commit: str, *, slug: str | None = None) -> str:
+def canonical_release_names(
+    *,
+    role: str,
+    stage: str,
+    delivery_commit: str,
+    topic: str | None = None,
+    actual_zip_basename: str | None = None,
+) -> dict[str, str]:
+    """Single naming helper for ZIP / sidecar / pointer basenames.
+
+    Inputs: topic (default mse-a1), role, stage, delivery short hash, optional
+    actual ZIP basename. Intermediate names never assume final; final names
+    never use door-percent / PENDING.
+    """
+    topic_n = (topic or release_task_slug()).strip()
+    if not topic_n:
+        topic_n = _DEFAULT_RELEASE_TASK_SLUG
+    stage_n = str(stage or "").strip().casefold().replace("_", "-")
+    if stage_n in {"intermediate", "intermediate-review", "non-final"}:
+        stage_n = "intermediate-review"
+    elif stage_n in {"final", "final-review"}:
+        stage_n = "final-review"
+    else:
+        raise ValueError(f"unsupported package stage for naming: {stage}")
+    role_n = str(role or "").strip().casefold()
+    short = _short(delivery_commit, 8)
+    actual = (actual_zip_basename or "").strip()
+    blob = f"{topic_n}|{role_n}|{stage_n}|{short}|{actual}"
+    if "PENDING" in blob.upper():
+        raise ValueError("PENDING is not allowed in canonical release names")
+    if role_n in {"review-compact", "review", "compact"}:
+        if stage_n == "intermediate-review":
+            zip_name = f"prod2u-review-compact-{topic_n}-intermediate-{short}.zip"
+        else:
+            zip_name = f"prod2u-review-compact-{topic_n}-{short}.zip"
+    elif role_n in {"firmware", "fw"}:
+        if stage_n == "intermediate-review":
+            zip_name = f"prod2u-firmware-{topic_n}-intermediate-{short}.zip"
+        else:
+            zip_name = f"prod2u-firmware-{topic_n}-{short}.zip"
+    else:
+        raise ValueError(f"unsupported naming role: {role}")
+    if actual:
+        zip_name = actual if actual.casefold().endswith(".zip") else f"{actual}.zip"
+    stem = zip_name[:-4] if zip_name.casefold().endswith(".zip") else zip_name
+    return {
+        "topic": topic_n,
+        "role": "firmware" if role_n in {"firmware", "fw"} else "review-compact",
+        "stage": stage_n,
+        "delivery_short": short,
+        "zip_basename": zip_name,
+        "selftest_basename": f"{stem}.selftest.json",
+        "detached_replay_basename": f"{stem}.detached-replay.json",
+        "sha256_basename": f"{zip_name}.sha256",
+        "cross_package_basename": f"prod2u-cross-package-{topic_n}-{short}.json",
+        "release_validation_basename": f"prod2u-release-validation-{topic_n}-{short}.json",
+        "release_set_basename": f"prod2u-release-set-{topic_n}-{short}.json",
+    }
+
+
+def release_sibling_filename(
+    kind: str,
+    delivery_commit: str,
+    *,
+    slug: str | None = None,
+    stage: str = "final-review",
+    actual_zip_basename: str | None = None,
+) -> str:
     """Canonical sibling names for this task (topic/stage-aware; never altconfig)."""
     """Canonical sibling names for this task (topic/stage-aware; never altconfig)."""
     topic = (slug or release_task_slug()).strip()
     topic = (slug or release_task_slug()).strip()
-    short = _short(delivery_commit, 8)
     kind_n = kind.strip().casefold()
     kind_n = kind.strip().casefold()
     if kind_n in {"review-compact", "review", "compact"}:
     if kind_n in {"review-compact", "review", "compact"}:
-        return f"prod2u-review-compact-{topic}-{short}.zip"
+        return canonical_release_names(
+            role="review-compact",
+            stage=stage,
+            delivery_commit=delivery_commit,
+            topic=topic,
+            actual_zip_basename=actual_zip_basename,
+        )["zip_basename"]
     if kind_n in {"firmware", "fw"}:
     if kind_n in {"firmware", "fw"}:
-        return f"prod2u-firmware-{topic}-{short}.zip"
+        return canonical_release_names(
+            role="firmware",
+            stage=stage,
+            delivery_commit=delivery_commit,
+            topic=topic,
+            actual_zip_basename=actual_zip_basename,
+        )["zip_basename"]
+    names = canonical_release_names(
+        role="review-compact" if "firmware" not in kind_n else "firmware",
+        stage=stage,
+        delivery_commit=delivery_commit,
+        topic=topic,
+        actual_zip_basename=actual_zip_basename,
+    )
     if kind_n in {"review-selftest", "compact-selftest"}:
     if kind_n in {"review-selftest", "compact-selftest"}:
-        return f"prod2u-review-compact-{topic}-{short}.selftest.json"
+        review = canonical_release_names(
+            role="review-compact",
+            stage=stage,
+            delivery_commit=delivery_commit,
+            topic=topic,
+            actual_zip_basename=actual_zip_basename,
+        )
+        return review["selftest_basename"]
     if kind_n in {"firmware-selftest", "fw-selftest"}:
     if kind_n in {"firmware-selftest", "fw-selftest"}:
-        return f"prod2u-firmware-{topic}-{short}.selftest.json"
+        fw = canonical_release_names(
+            role="firmware",
+            stage=stage,
+            delivery_commit=delivery_commit,
+            topic=topic,
+            actual_zip_basename=actual_zip_basename,
+        )
+        return fw["selftest_basename"]
     if kind_n in {"release-set", "release_set"}:
     if kind_n in {"release-set", "release_set"}:
-        return f"prod2u-release-set-{topic}-{short}.json"
+        return names["release_set_basename"]
     if kind_n in {"review-replay", "detached-replay"}:
     if kind_n in {"review-replay", "detached-replay"}:
-        return f"prod2u-review-compact-{topic}-{short}.detached-replay.json"
+        review = canonical_release_names(
+            role="review-compact",
+            stage=stage,
+            delivery_commit=delivery_commit,
+            topic=topic,
+            actual_zip_basename=actual_zip_basename,
+        )
+        return review["detached_replay_basename"]
     if kind_n in {"cross-package", "crosscheck"}:
     if kind_n in {"cross-package", "crosscheck"}:
-        return f"prod2u-cross-package-{topic}-{short}.json"
+        return names["cross_package_basename"]
     if kind_n in {"release-validation", "release_validation"}:
     if kind_n in {"release-validation", "release_validation"}:
-        return f"prod2u-release-validation-{topic}-{short}.json"
+        return names["release_validation_basename"]
     raise ValueError(f"unknown sibling kind: {kind}")
     raise ValueError(f"unknown sibling kind: {kind}")
 
 
 
 
@@ -184,13 +291,13 @@ def validate_source_closure_relations(relations: dict[str, Any] | Any) -> dict[s
         if not isinstance(paths, list):
         if not isinstance(paths, list):
             failures.append(f"{edge_key}_paths_not_list")
             failures.append(f"{edge_key}_paths_not_list")
             paths = []
             paths = []
-        if mode == "commit_compare":
+        if mode in {"commit_compare", "snapshot_hash"}:
             if unchanged is True and paths:
             if unchanged is True and paths:
                 failures.append(f"{edge_key}_unchanged_true_with_changed_paths")
                 failures.append(f"{edge_key}_unchanged_true_with_changed_paths")
             if unchanged is False and not paths:
             if unchanged is False and not paths:
                 failures.append(f"{edge_key}_unchanged_false_empty_paths")
                 failures.append(f"{edge_key}_unchanged_false_empty_paths")
             if unchanged not in (True, False):
             if unchanged not in (True, False):
-                failures.append(f"{edge_key}_unchanged_not_bool_under_commit_compare")
+                failures.append(f"{edge_key}_unchanged_not_bool")
         if mode == "comparison_unavailable":
         if mode == "comparison_unavailable":
             if unchanged is not None:
             if unchanged is not None:
                 failures.append(f"{edge_key}_guessed_bool_when_unavailable")
                 failures.append(f"{edge_key}_guessed_bool_when_unavailable")
@@ -440,6 +547,120 @@ def compute_release_set_id(
     )
     )
 
 
 
 
+# Extra TD/project files beyond config/source_closure.json (37 production inputs).
+_TD_EXTRA_PRODUCTION_PATHS = (
+    "constraints/prod2u_p4_normal_v3.adc",
+    "constraints/prod2u_p4_normal_v3.sdc",
+    "td/prod2u_p4_normal_v3.prj",
+    "td/syn/prod2u_p4_normal_v3.tcl",
+    "td/phy/prod2u_p4_normal_v3.tcl",
+    "td/bitgen/prod2u_p4_normal_v3.tcl",
+    "projects/prod2u-door-temp/project.json",
+    "src/generated/td-source-manifest.json",
+)
+
+
+def production_input_paths(repo_root: Path | None = None) -> list[str]:
+    """Canonical 37 TD synthesis / production-input paths."""
+    root = Path(repo_root or ROOT)
+    closure = root / "config" / "source_closure.json"
+    paths: list[str] = []
+    if closure.is_file():
+        doc = json.loads(closure.read_text(encoding="utf-8"))
+        for item in doc.get("sources") or []:
+            text = str(item).replace("\\", "/").strip()
+            if text and text not in paths:
+                paths.append(text)
+    for extra in _TD_EXTRA_PRODUCTION_PATHS:
+        if extra not in paths:
+            paths.append(extra)
+    return paths
+
+
+def _git_bin() -> str:
+    candidate = Path("/data/prod2u/bin/git")
+    return str(candidate) if candidate.is_file() else "git"
+
+
+def _git_show_sha(repo: Path, commit: str, rel: str) -> str | None:
+    try:
+        raw = subprocess.check_output(
+            [_git_bin(), "-C", str(repo), "show", f"{commit}:{rel}"],
+            stderr=subprocess.DEVNULL,
+        )
+    except (OSError, subprocess.CalledProcessError):
+        return None
+    return hashlib.sha256(raw).hexdigest()
+
+
+def compare_production_source_commits(
+    *,
+    from_commit: str,
+    to_commit: str,
+    repo_root: Path | None = None,
+) -> dict[str, Any]:
+    """Hash-compare production inputs. Commit equality is not a shortcut."""
+    root = Path(repo_root or ROOT)
+    changed: list[str] = []
+    missing: list[str] = []
+    for rel in production_input_paths(root):
+        a = _git_show_sha(root, from_commit, rel)
+        b = _git_show_sha(root, to_commit, rel)
+        if a is None or b is None:
+            missing.append(rel)
+            continue
+        if a != b:
+            changed.append(rel)
+    unchanged = not changed and not missing
+    return {
+        "from_commit": from_commit,
+        "to_commit": to_commit,
+        "unchanged": unchanged,
+        "production_changed_paths": changed,
+        "missing_paths": missing,
+        "comparison_mode": "snapshot_hash",
+    }
+
+
+def parse_td_resource_fields(
+    compact_doc: dict[str, Any],
+    full_doc: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+    """Parse LUT / MSLICE / DSP. Never silently substitute LUT for MSLICE.
+
+    Preference:
+    - LUT: ``resources.utilization.lut.used`` (not hierarchy LUT-only counts)
+    - MSLICE: top-level ``mslice``, then ``resources.packing.mslice``
+    - DSP: utilization.dsp.used, else top-level dsp
+    Missing MSLICE stays None — callers must not treat that as LUT.
+    """
+    full_doc = full_doc or {}
+    resources = compact_doc.get("resources") or full_doc.get("resources") or {}
+    if not isinstance(resources, dict):
+        resources = {}
+    util = resources.get("utilization") if isinstance(resources.get("utilization"), dict) else {}
+    packing = resources.get("packing") if isinstance(resources.get("packing"), dict) else {}
+    lut = None
+    if isinstance(util.get("lut"), dict) and util["lut"].get("used") is not None:
+        lut = util["lut"].get("used")
+    elif compact_doc.get("lut") is not None and "utilization" not in resources:
+        lut = compact_doc.get("lut")
+    mslice = compact_doc.get("mslice")
+    if mslice is None:
+        mslice = full_doc.get("mslice")
+    if mslice is None:
+        mslice = packing.get("mslice")
+    # Do not use packing.total_slices (MSLICE+LSLICE) or LE/LUT as MSLICE.
+    dsp = None
+    if isinstance(util.get("dsp"), dict) and util["dsp"].get("used") is not None:
+        dsp = util["dsp"].get("used")
+    elif compact_doc.get("dsp") is not None:
+        dsp = compact_doc.get("dsp")
+    elif full_doc.get("dsp") is not None:
+        dsp = full_doc.get("dsp")
+    return {"lut": lut, "mslice": mslice, "dsp": dsp}
+
+
 # Canonical A1 full-chip TD on ff44128a (Round-9 identity source — not hardcoded nulls).
 # Canonical A1 full-chip TD on ff44128a (Round-9 identity source — not hardcoded nulls).
 CANONICAL_TD_A1_RECEIPT = "receipts/mse-r4-td-a1-ff44128.json"
 CANONICAL_TD_A1_RECEIPT = "receipts/mse-r4-td-a1-ff44128.json"
 CANONICAL_TD_A1_RECEIPT_FULL = "receipts/mse-r4-td-a1-ff44128-full.json"
 CANONICAL_TD_A1_RECEIPT_FULL = "receipts/mse-r4-td-a1-ff44128-full.json"
@@ -485,16 +706,10 @@ def load_canonical_td_a1_fields(repo_root: Path | None = None) -> dict[str, Any]
         or compact_doc.get("verification_run_id")
         or compact_doc.get("verification_run_id")
         or ""
         or ""
     ).strip()
     ).strip()
-    resources = compact_doc.get("resources") or full_doc.get("resources") or {}
-    util = resources.get("utilization") if isinstance(resources, dict) else {}
-    lut = None
-    mslice = None
-    dsp = None
-    if isinstance(util, dict):
-        lut = (util.get("lut") or {}).get("used")
-        # Anlogic area: LE≈MSLICE packing proxy used historically as mslice
-        mslice = (util.get("le") or {}).get("used") or lut
-        dsp = (util.get("dsp") or {}).get("used")
+    parsed = parse_td_resource_fields(compact_doc, full_doc)
+    lut = parsed["lut"]
+    mslice = parsed["mslice"]
+    dsp = parsed["dsp"]
     return {
     return {
         "td_bound_commit": bound or CANONICAL_TD_A1_BOUND_COMMIT,
         "td_bound_commit": bound or CANONICAL_TD_A1_BOUND_COMMIT,
         "artifact_source_commit": bound or CANONICAL_TD_A1_BOUND_COMMIT,
         "artifact_source_commit": bound or CANONICAL_TD_A1_BOUND_COMMIT,

+ 62 - 58
tools/release_validation.py

@@ -1,7 +1,8 @@
 #!/usr/bin/env python3
 #!/usr/bin/env python3
-"""Release-validation aggregator for MSE dual packages (Round-9).
+"""Release-validation aggregator for MSE dual packages.
 
 
-Runs fail-closed checks and writes a single JSON receipt. Does not upload.
+Fail-closed: missing/skipped/not_provided/unknown/fail all make the top-level fail.
+Does not upload.
 """
 """
 
 
 from __future__ import annotations
 from __future__ import annotations
@@ -14,7 +15,27 @@ from datetime import datetime, timezone
 from pathlib import Path
 from pathlib import Path
 from typing import Any
 from typing import Any
 
 
-from cross_package_verify import verify_cross_package
+try:
+    from compact_package_selftest import run_compact_zip_selftest
+    from cross_package_verify import verify_cross_package
+except ImportError:  # pytest imports tools.release_validation
+    from tools.compact_package_selftest import run_compact_zip_selftest
+    from tools.cross_package_verify import verify_cross_package
+
+SELFTEST_SIDECAR_LABELS = frozenset(
+    {
+        "review_selftest_sidecar",
+        "firmware_selftest_sidecar",
+        "review_detached_replay_sidecar",
+    }
+)
+REQUIRED_PARTS = (
+    "cross_package",
+    "review_standalone_selftest",
+    "review_selftest_sidecar",
+    "firmware_selftest_sidecar",
+    "external_release_set",
+)
 
 
 
 
 def _sha256_file(path: Path) -> str:
 def _sha256_file(path: Path) -> str:
@@ -25,25 +46,8 @@ def _sha256_file(path: Path) -> str:
     return h.hexdigest()
     return h.hexdigest()
 
 
 
 
-def _try_import_selftest():
-    try:
-        from compact_package_selftest import selftest_review_zip  # type: ignore
-
-        return selftest_review_zip
-    except Exception:
-        pass
-    try:
-        from compact_package_selftest import run_selftest  # type: ignore
-
-        return run_selftest
-    except Exception:
-        return None
-
-
-def _sidecar_sha(path: Path) -> str | None:
-    if not path.is_file():
-        return None
-    return _sha256_file(path)
+def _status_ok(value: Any) -> bool:
+    return str(value or "").casefold() in {"pass", "true"}
 
 
 
 
 def validate_release(
 def validate_release(
@@ -53,49 +57,38 @@ def validate_release(
     review_selftest_json: Path | None = None,
     review_selftest_json: Path | None = None,
     firmware_selftest_json: Path | None = None,
     firmware_selftest_json: Path | None = None,
     release_set_json: Path | None = None,
     release_set_json: Path | None = None,
+    review_detached_replay_json: Path | None = None,
 ) -> dict[str, Any]:
 ) -> dict[str, Any]:
     failures: list[str] = []
     failures: list[str] = []
     parts: dict[str, Any] = {}
     parts: dict[str, Any] = {}
 
 
-    cross = verify_cross_package(review_zip, firmware_zip)
+    try:
+        cross = verify_cross_package(review_zip, firmware_zip)
+    except Exception as exc:  # noqa: BLE001
+        cross = {"status": "fail", "failures": [f"exception:{exc}"]}
     parts["cross_package"] = cross
     parts["cross_package"] = cross
-    if cross.get("status") != "pass":
+    if not _status_ok(cross.get("status")):
         failures.append("cross_package_fail")
         failures.append("cross_package_fail")
         failures.extend(f"cross:{x}" for x in (cross.get("failures") or [])[:20])
         failures.extend(f"cross:{x}" for x in (cross.get("failures") or [])[:20])
 
 
-    selftest_fn = _try_import_selftest()
-    if selftest_fn is not None:
-        try:
-            review_st = selftest_fn(review_zip)
-            parts["review_standalone_selftest"] = review_st
-            if isinstance(review_st, dict) and review_st.get("status") not in {
-                "pass",
-                "PASS",
-                True,
-            }:
-                failures.append("review_standalone_selftest_fail")
-        except TypeError:
-            # Different signatures across packager versions — record and continue.
-            parts["review_standalone_selftest"] = {
-                "status": "skipped",
-                "reason": "incompatible_selftest_signature",
-            }
-        except Exception as exc:  # noqa: BLE001
-            failures.append(f"review_selftest_error:{exc}")
-            parts["review_standalone_selftest"] = {"status": "fail", "error": str(exc)}
-    else:
-        parts["review_standalone_selftest"] = {
-            "status": "skipped",
-            "reason": "selftest_entry_not_found",
-        }
-
-    # Prefer caller-provided sidecar receipts when present.
-    for label, path in (
+    try:
+        review_st = run_compact_zip_selftest(review_zip)
+        parts["review_standalone_selftest"] = review_st
+        if not isinstance(review_st, dict) or not _status_ok(review_st.get("status")):
+            failures.append("review_standalone_selftest_fail")
+    except Exception as exc:  # noqa: BLE001
+        failures.append(f"review_selftest_error:{exc}")
+        parts["review_standalone_selftest"] = {"status": "fail", "error": str(exc)}
+
+    sidecar_specs = (
         ("review_selftest_sidecar", review_selftest_json),
         ("review_selftest_sidecar", review_selftest_json),
         ("firmware_selftest_sidecar", firmware_selftest_json),
         ("firmware_selftest_sidecar", firmware_selftest_json),
         ("external_release_set", release_set_json),
         ("external_release_set", release_set_json),
-    ):
+        ("review_detached_replay_sidecar", review_detached_replay_json),
+    )
+    for label, path in sidecar_specs:
         if path is None:
         if path is None:
+            failures.append(f"{label}_not_provided")
             parts[label] = {"status": "not_provided"}
             parts[label] = {"status": "not_provided"}
             continue
             continue
         if not path.is_file():
         if not path.is_file():
@@ -112,16 +105,17 @@ def validate_release(
         parts[label] = {
         parts[label] = {
             "status": st or "present",
             "status": st or "present",
             "path": str(path),
             "path": str(path),
-            "sha256": _sidecar_sha(path),
+            "sha256": _sha256_file(path),
         }
         }
-        if label.endswith("selftest") and st not in {"pass", ""}:
-            # empty status on release-set is ok; selftests must pass
-            if "selftest" in label and st != "pass":
+        if label in SELFTEST_SIDECAR_LABELS or label == "external_release_set":
+            if st in {"", "skipped", "not_provided", "missing", "unknown", "incompatible"}:
+                failures.append(f"{label}_not_pass:{st or 'empty'}")
+            elif st != "pass":
                 failures.append(f"{label}_not_pass")
                 failures.append(f"{label}_not_pass")
 
 
-    # ZIP member safety: reject absolute / path-escape names
     for label, zpath in (("review", review_zip), ("firmware", firmware_zip)):
     for label, zpath in (("review", review_zip), ("firmware", firmware_zip)):
         if not zpath.is_file():
         if not zpath.is_file():
+            failures.append(f"missing_{label}_zip")
             continue
             continue
         with zipfile.ZipFile(zpath) as zf:
         with zipfile.ZipFile(zpath) as zf:
             for name in zf.namelist():
             for name in zf.namelist():
@@ -129,6 +123,14 @@ def validate_release(
                 if n.startswith("/") or n.startswith("../") or "/../" in n:
                 if n.startswith("/") or n.startswith("../") or "/../" in n:
                     failures.append(f"{label}_unsafe_zip_path:{n}")
                     failures.append(f"{label}_unsafe_zip_path:{n}")
 
 
+    for name in REQUIRED_PARTS:
+        part = parts.get(name) or {}
+        st = str(part.get("status") or "").casefold()
+        if st in {"skipped", "not_provided", "missing", "unknown"}:
+            failures.append(f"{name}_{st}")
+
+    # unique
+    failures = list(dict.fromkeys(failures))
     status = "fail" if failures else "pass"
     status = "fail" if failures else "pass"
     return {
     return {
         "schema": "prod2u-mse-release-validation-v1",
         "schema": "prod2u-mse-release-validation-v1",
@@ -152,6 +154,7 @@ def main(argv: list[str] | None = None) -> int:
     parser.add_argument("--review-selftest-json", type=Path, default=None)
     parser.add_argument("--review-selftest-json", type=Path, default=None)
     parser.add_argument("--firmware-selftest-json", type=Path, default=None)
     parser.add_argument("--firmware-selftest-json", type=Path, default=None)
     parser.add_argument("--release-set-json", type=Path, default=None)
     parser.add_argument("--release-set-json", type=Path, default=None)
+    parser.add_argument("--review-detached-replay-json", type=Path, default=None)
     parser.add_argument("--output", type=Path, required=True)
     parser.add_argument("--output", type=Path, required=True)
     args = parser.parse_args(argv)
     args = parser.parse_args(argv)
     result = validate_release(
     result = validate_release(
@@ -160,6 +163,7 @@ def main(argv: list[str] | None = None) -> int:
         review_selftest_json=args.review_selftest_json,
         review_selftest_json=args.review_selftest_json,
         firmware_selftest_json=args.firmware_selftest_json,
         firmware_selftest_json=args.firmware_selftest_json,
         release_set_json=args.release_set_json,
         release_set_json=args.release_set_json,
+        review_detached_replay_json=args.review_detached_replay_json,
     )
     )
     args.output.parent.mkdir(parents=True, exist_ok=True)
     args.output.parent.mkdir(parents=True, exist_ok=True)
     text = json.dumps(result, indent=2) + "\n"
     text = json.dumps(result, indent=2) + "\n"