فهرست منبع

Fix Prod2U SRAM startup and binary921 evidence flow

Codex 4 ماه پیش
والد
کامیت
aeb23afeaa
60فایلهای تغییر یافته به همراه12448 افزوده شده و 873 حذف شده
  1. 11 0
      .gitattributes
  2. 6 5
      config/pin_inventory.fcb_fpga_mcu0611.json
  3. 1 2
      constraints/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.adc
  4. BIN
      docs/images/prod2u-con77-con78-rs232-schematic.png
  5. 15 0
      docs/j6-bmc-replay-binary921-protocol-v1.zh-CN.md
  6. 162 0
      docs/prod2u-program-sram-runbook.zh-CN.md
  7. 41 0
      docs/prod2u-start-here.zh-CN.md
  8. 411 0
      receipts/prod2u_bmc_replay_payload_real_capture_20260711.json
  9. 86 0
      receipts/prod2u_formal_20260711T044529Z.json
  10. 622 0
      receipts/prod2u_rtl_sim_20260711T044348Z.json
  11. 81 0
      receipts/prod2u_verilator_lint_20260711T044509Z.json
  12. 688 0
      receipts/td_prod2u_bmc_replay_binary921_20260711T044118Z.json
  13. 130 0
      schemas/prod2u_evidence_manifest.schema.json
  14. 51 0
      schemas/prod2u_final_gate.schema.json
  15. 241 0
      schemas/prod2u_program_sram_receipt.schema.json
  16. 65 0
      schemas/prod2u_td_build_receipt.schema.json
  17. 41 11
      src/rtl/binary921_diag_core.v
  18. 47 29
      src/rtl/binary921_frame_tx.v
  19. 32 0
      src/rtl/prod2u_por.v
  20. 19 7
      src/rtl/uart_rx_8n1.v
  21. 21 3
      src/top/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top.v
  22. 16 0
      td/phy/prod2u_bmc_replay_binary921.tcl
  23. 0 15
      td/phy/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.tcl
  24. 6 5
      td/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.prj
  25. 21 0
      td/syn/prod2u_bmc_replay_binary921.tcl
  26. 0 20
      td/syn/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.tcl
  27. 9 0
      tests/fixtures/prod2u_programmer/cli_success_excerpt.log
  28. 7 0
      tests/fixtures/prod2u_programmer/gui_success_excerpt.log
  29. 5 0
      tests/fixtures/prod2u_programmer/missing_bit_to_vec.log
  30. 99 33
      tests/sim/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top_tb.v
  31. 61 0
      tests/sim/prod2u_por_tb.v
  32. 89 0
      tests/test_project_structure.py
  33. 56 2
      tests/unit/test_binary921_protocol.py
  34. 70 0
      tests/unit/test_collect_j6_binary921.py
  35. 183 3
      tests/unit/test_pid_harness.py
  36. 17 0
      tests/unit/test_pin_inventory.py
  37. 133 0
      tests/unit/test_prod2u_bmc_replay.py
  38. 158 0
      tests/unit/test_prod2u_build_identity.py
  39. 628 0
      tests/unit/test_prod2u_contract.py
  40. 538 0
      tests/unit/test_prod2u_entrypoint.py
  41. 461 0
      tests/unit/test_prod2u_package.py
  42. 267 0
      tests/unit/test_prod2u_programmer.py
  43. 476 0
      tests/unit/test_prod2u_programmer_runtime.py
  44. 147 0
      tests/unit/test_prod2u_rtl_slice.py
  45. 210 0
      tests/unit/test_prod2u_td_build_identity.py
  46. 772 0
      tests/unit/test_prod2u_validator.py
  47. 4 0
      tests/verilator_prod2u_build_id_guard_stub.v
  48. 42 3
      tools/binary921.py
  49. 273 0
      tools/package_prod2u.ps1
  50. 323 19
      tools/pid_harness.py
  51. 10 5
      tools/pin_inventory.py
  52. 53 0
      tools/prod2u.ps1
  53. 474 0
      tools/prod2u_bmc_replay.py
  54. 277 0
      tools/prod2u_build_identity.py
  55. 745 0
      tools/prod2u_cli.py
  56. 1172 0
      tools/prod2u_collector.py
  57. 948 0
      tools/prod2u_programmer.py
  58. 423 0
      tools/prod2u_receipts.py
  59. 421 0
      tools/prod2u_validate.py
  60. 83 711
      tools/remote/collect_j6_binary921.py

+ 11 - 0
.gitattributes

@@ -0,0 +1,11 @@
+/.gitattributes text eol=lf
+*.adc text eol=lf
+*.json text eol=lf
+*.log text eol=lf
+*.md text eol=lf
+*.prj text eol=lf
+*.py text eol=lf
+*.sdc text eol=lf
+*.tcl text eol=lf
+*.v text eol=lf
+*.vh text eol=lf

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 6 - 5
config/pin_inventory.fcb_fpga_mcu0611.json


+ 1 - 2
constraints/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.adc

@@ -1,10 +1,9 @@
-# uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921 constraints.
+# prod2u_bmc_replay_binary921 constraints.
 # Pin profile: production-two-uart-bmc-replay-binary921.
 # BMC replay UART1: L10/M9 @115200. Combined Host+Debug UART2: M10/N11 @921600.
 # SRAM-only diagnostic constraints; no flash or cable programming command is present.
 # Board: fcb_fpga_mcu0611
 set_pin_assignment { sys_clk } { LOCATION = J1; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
-set_pin_assignment { sys_rst_n } { LOCATION = N6; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
 set_pin_assignment { led[0] } { LOCATION = H16; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
 set_pin_assignment { led[1] } { LOCATION = H15; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }
 set_pin_assignment { led[2] } { LOCATION = J16; IOSTANDARD = LVCMOS33; PULLTYPE = NONE; }

BIN
docs/images/prod2u-con77-con78-rs232-schematic.png


+ 15 - 0
docs/j6-bmc-replay-binary921-protocol-v1.zh-CN.md

@@ -37,6 +37,21 @@ decoder 必须支持流式重同步:遇到错误 magic、长度越界、CRC 
 | `0x0b` | `MODULE_SNAPSHOT` | CPLD -> Debug | 内部模块快照 |
 | `0x0c` | `ERROR_COUNTERS` | CPLD -> Debug | drop/error/bad-frame counters |
 
+### 2.1 READY startup identity
+
+The production two-UART wrapper uses an internal configuration POR: reset stays active for 1024 `sys_clk` cycles at 25 MHz, and the production ADC does not expose an external `sys_rst_n` pin. The production runtime profile is `profile_id=3`.
+
+`READY` payload is seven bytes and is emitted at the startup tick after `STARTUP_DELAY_TICKS` (production default `250000`):
+
+| offset | field | meaning |
+| ---: | --- | --- |
+| 0 | `profile_id_payload` | Runtime profile ID, `0x03` for production Prod2U |
+| 1..4 | `BUILD_ID` | 32-bit build identity, little-endian, from the top/core `BUILD_ID` parameter |
+| 5 | `por_reason` | `0x01` = configuration POR |
+| 6 | `announcement_seq` | 0-based startup announcement number |
+
+The startup epoch is frame `seq=1`; the frame timestamp is the startup tick. To tolerate a receiver that begins reading shortly after SRAM configuration, the READY announcement is emitted at most three times with `announcement_seq=0,1,2`. Repeats retain `seq=1`, the same timestamp, profile, build identity, and POR reason; only `announcement_seq` changes, so the host can distinguish announcements without creating new fresh epochs.
+
 ## 3. Host Command
 
 `HOST_CMD` payload 固定 4 字节:

+ 162 - 0
docs/prod2u-program-sram-runbook.zh-CN.md

@@ -0,0 +1,162 @@
+# Prod2U 自动 PROGRAM_SRAM 与 binary921 现场 Runbook
+
+## 1. 适用范围
+
+本流程适用于生产温控板 profile `prod2u-bmc-replay-binary921`:
+
+- JTAG:Anlogic AL-Link Mini,J3,speed code `2`,对应 `200kHz`。
+- Combined Host+Debug:UART2,FPGA `TX=M10`、`RX=N11`,板外 RS232 电平,`921600 8N1`。
+- BMC replay:UART1,FPGA `TX=L10`、`RX=M9`,板外 RS232 电平,`115200 8N1`。
+- UART2 从生产板 `CON78` 引出:pin1=`RS232_TX2`(板输出)、pin2=`RS232_RX2`(板输入)、pin3/pin4=GND;pin5/pin6 是接地固定焊盘。
+- UART1 从生产板 `CON77` 引出:pin1=`RS232_TX1`(板输出)、pin2=`RS232_RX1`(板输入)、pin3/pin4=GND;pin5/pin6 是接地固定焊盘。
+- CON77/CON78 经过 U22/U23 `TRSF3232EIPWR`,必须接真正的 USB-RS232 适配器,不能接 USB-TTL。板 TX 接适配器 RXD,板 RX 接适配器 TXD,并共地;接口不提供 VCC。
+- 原理图没有给出实物连接器的观察方向。未通过 pin1 标记、连接器资料或万用表确认前,不得按“从左到右”猜测针序。
+
+包内 [CON77/CON78 RS-232 原理图截图](images/prod2u-con77-con78-rs232-schematic.png) 来自 `FCB_FPGA+MCU0611.pdf` 第 5 页。它证明电气链路,不证明实物连接器朝向。
+- 只允许 SRAM 配置,不写入非易失存储。
+- 板子保持正常供电,不要求重新上电,不把 DTR/RTS 当复位使用。
+
+本流程的 pass 只证明指定 bitstream 的 SRAM 下载、build identity、binary921 控制通信和 BMC replay 证据。真实 PTC/FAN 负载、热性能和真实 PID 闭环需要独立 gate。
+
+## 2. 已确认的历史事实
+
+旧 `j6bin.bit` 的 SHA256 为:
+
+```text
+D6648FA4E51384AC1DA92AD03A1A3FFEFDD04FECC4EDA07DFDDAC335A7881347
+```
+
+BitWriter 历史日志记录了该文件 4 次 `200kHz` 和 1 次 `500kHz` 完整下载。`-spd 2` 会生成 `bit_to_vec -freq 0.200000`,因此数值映射已有运行日志证据。
+
+此前 CLI 负向探针使用不存在的 `tmp/does-not-exist.bit`。出现 `PRG-8002 Cannot open file` 和后续通用错误是预期结果,不代表上述生产 bitstream 或 JTAG 链路失败。
+
+`bw_commands_prompt.exe` 即使内部命令失败也可能返回进程退出码 `0`。工具必须解析完整事务日志,不能只读取 `$LASTEXITCODE`。
+
+## 3. 固件启动修复
+
+旧生产约束错误地把 `N6` 当作低有效复位。权威原理图第 3 页显示 `N6=KEY_1`,并非系统复位。Prod2U 固件不再使用 N6,改用配置初始化的内部 POR:
+
+1. SRAM 配置完成后,POR 保持核心复位 1024 个 25MHz 时钟周期,约 `40.96us`。
+2. POR 同步释放。
+3. 核心再等待约 `10ms` startup delay。
+4. READY payload 固定为 7 字节:runtime profile ID `3` 1 字节、32-bit build ID 4 字节、POR reason 1 字节和 announcement sequence 1 字节。
+
+每次 SRAM 配置都会重新初始化 POR,不需要对板子断电。
+
+## 4. 包内容
+
+发布包名称固定为 `prod2u-<BUILD_ID>`,根目录包含:
+
+- `fw.bit`
+- `prod2u.ps1`
+- `prod2u_cli.py`
+- `prod2u_programmer.py`
+- `prod2u_validate.py`
+- `source-manifest.json`
+- `td.json`
+- `bmc-replay-payload.json`
+- `manifest.json`
+- `sha256-inventory.json`
+- `START-HERE.zh-CN.md`
+- `prod2u-program-sram-runbook.zh-CN.md`
+- `schemas/prod2u_program_sram_receipt.schema.json`
+- `schemas/prod2u_evidence_manifest.schema.json`
+- `schemas/prod2u_final_gate.schema.json`
+- `schemas/prod2u_td_build_receipt.schema.json`
+
+`BUILD_ID` 是 source manifest SHA256 的前 8 个十六进制字符。完整 source hash 同时保存在 source manifest、TD receipt 和 package manifest 中。
+
+## 5. 命令模式
+
+在包根目录执行。
+
+### 5.1 无硬件自测
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\prod2u.ps1 selftest
+```
+
+该命令不得打开 COM、AL-Link 或执行 SRAM 下载。
+
+### 5.2 预检
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\prod2u.ps1 preflight -CombinedPort COM5 -Bitstream .\fw.bit -TdReceipt .\td.json -SourceManifest .\source-manifest.json
+```
+
+预检校验文件 hash、build ID、TD receipt、显式 COM 名称与 TD 工具路径。preflight 不打开 AL-Link,不打开 COM,不检查或操作 AL-Link 状态,也不执行 SRAM 下载。
+
+### 5.3 仅验证 programmer
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\prod2u.ps1 program-only -Bitstream .\fw.bit -TdReceipt .\td.json -SourceManifest .\source-manifest.json -OutputDir ..\prod2u-<BUILD_ID>-evidence
+```
+
+该模式不证明 READY、UART、BMC replay 或 PWM 功能。
+
+### 5.4 完整自动流程
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\prod2u.ps1 all -CombinedPort COM5 -Bitstream .\fw.bit -TdReceipt .\td.json -SourceManifest .\source-manifest.json -BmcReplayReceipt ..\prod2u-<BUILD_ID>-runtime\bmc-replay-session.json -OutputDir ..\prod2u-<BUILD_ID>-evidence
+```
+
+固定顺序:
+
+1. 校验 package、source manifest、TD receipt 和 bitstream hash。
+2. 正常关闭 TD/BitWriter;等待 5 秒后只结束仍占用当前 TD 安装的进程。
+3. 打开 COM5。先保存 raw pre-program 字节和帧记录,再执行解析。
+4. 执行一次 `PROGRAM_SRAM @200kHz`。
+5. 同时保存 CLI stdout、stderr 和本次新增的 BitWriter 日志区间。
+6. 校验 7 字节 READY 的 profile、build ID、POR reason、序列和 post-program epoch;受损、部分或超时时同样先保存已读 raw,再分类失败。
+7. 发送 12 条 Host binary command,保存实际 wire bytes 和接收 raw。
+8. 生成 programmer receipt、evidence manifest 和 final gate 输入。
+
+失败后立即停止,不自动重试,不重新上电。
+
+## 6. Programmer 严格判定
+
+同一事务必须按顺序出现:
+
+1. 目标 `download` start,参数包含目标 bit 路径、JTAG、`-spd 2`、cable 0。
+2. `PRG-2014 : Chip validation success: EF2L45`。
+3. 同一 bit 路径的 `bit_to_vec` start,频率为 `0.200000`。
+4. `bit_to_vec` finish。
+5. `program -cable 0 -mode svf -spd 2 -p` start。
+6. `program` finish。
+7. 外层 `download` finish。
+
+任何错误代码、错误文本、路径/hash/chip/speed 不一致、marker 缺失或乱序、多事务、超时或禁止动作都使该层失败。退出码 `0` 只是辅助字段。
+
+## 7. READY 和串口失败分类
+
+collector 必须保存所有已读取字节,即使 READY 超时。失败分类包括:
+
+- `blocked_waiting_for_ready_empty`:当前进程确实没有收到字节。
+- `blocked_waiting_for_ready_noise`:收到字节,但不存在 binary921 magic。
+- `blocked_waiting_for_ready_partial`:存在未完成帧。
+- `blocked_waiting_for_ready_corrupt`:帧长度、版本或 CRC 错误。
+- `blocked_ready_profile_mismatch`:profile 不是 ID 3。
+- `blocked_ready_build_identity_mismatch`:READY build ID 与包不一致。
+- `blocked_ready_epoch_not_post_program`:帧不能关联到本次 SRAM 下载。
+
+空 raw 只能说明采集进程没有保存到字节,不能单独证明板子无输出、串口接线正确或 SRAM 下载失败。
+
+## 8. 验收边界
+
+- `program receipt pass`:只证明 BitWriter 日志报告指定 bitstream 的 SRAM 下载事务完整。
+- `fresh epoch pass`:证明本次下载后出现正确 profile/build ID READY。
+- `host_uart pass`:证明 12 条 Host 命令和 ACK 全部匹配。
+- `bmc_replay pass`:证明 CPLD poll 后 PC 回复历史真实 BMC payload,且 hash 匹配。
+- `real_fan_ptc_hardware_status=not_run`:不等于失败,也不能写成真实负载 pass。
+
+`prod2u-final-gate-v1` 是 Prod2U 子 gate。它的 required layers 全部为 `pass` 时,只表示 Prod2U 控制通信证据可作为仓库 `final-gate-v2` 的输入;它不替代 `final-gate-v2`,也不能把 `blocked_*`、`fail_*`、dry-run、fixture 或缺失证据提升为 pass。
+
+## 9. Harness 演进触发条件
+
+以下任一变化必须升级 schema/gate 并重新资格验证:
+
+- TD 或 BitWriter 版本变化。
+- CLI marker、日志目录或 speed 映射变化。
+- 原理图/PDF hash、板卡版本或 UART 电平路径变化。
+- READY payload 或 Host binary protocol 变化。
+- 引入真实 PTC/FAN 负载、真实热测试或 PID 闭环。

+ 41 - 0
docs/prod2u-start-here.zh-CN.md

@@ -0,0 +1,41 @@
+# Prod2U 生产温控板 SRAM 调试包
+
+本包 build ID:`{{BUILD_ID}}`。板子保持正常供电,不要求重新上电。
+
+## 接线与前置条件
+
+1. 生产板正常供电;AL-Link 排线接 J3,JTAG speed 固定 200kHz。
+2. combined Host+Debug 使用生产板 `CON78/UART2`,默认 COM5、921600 8N1。CON78 电气针序为:pin1=`RS232_TX2`(板输出)、pin2=`RS232_RX2`(板输入)、pin3/pin4=GND;pin5/pin6 是接地的固定焊盘。
+3. BMC replay 使用生产板 `CON77/UART1`,115200 8N1。CON77 电气针序为:pin1=`RS232_TX1`(板输出)、pin2=`RS232_RX1`(板输入)、pin3/pin4=GND;pin5/pin6 是接地的固定焊盘。
+4. CON77/CON78 已经过板载 `TRSF3232EIPWR`,板外是标准 RS-232 电平,不是 3.3V TTL。必须使用 USB-RS232 适配器:板 pin1 TX 接适配器 RXD,板 pin2 RX 接适配器 TXD,板 pin3 或 pin4 接适配器 GND。接口不提供 VCC,禁止把 USB-TTL 适配器直接接到 CON77/CON78。
+5. 原理图只证明电气 pin 编号,当前仓库没有 PCB/装配图证明实物连接器从哪个观察方向数 pin1。接线前必须依据板上 pin1 标记、连接器数据手册或万用表确认方向,不能凭左右位置猜测。
+
+电气连接截图见 [CON77/CON78 RS-232 原理图](images/prod2u-con77-con78-rs232-schematic.png)。截图来自 `FCB_FPGA+MCU0611.pdf` 第 5 页,只用于确认 U22/U23、信号名和 pin 编号,不代表实物观察方向。
+
+运行现场流程前,调试机需已具备 Python 3、`pyserial` 和 `jsonschema`。本包不会安装 Python、驱动或依赖。
+
+## 自动流程
+
+先做不打开硬件的检查:`preflight` 不打开 COM、AL-Link,不执行 `PROGRAM_SRAM`。它只校验包内文件、build identity、TD receipt 与 TD 工具路径。
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\prod2u.ps1 preflight -CombinedPort COM5 -Bitstream .\fw.bit -TdReceipt .\td.json -SourceManifest .\source-manifest.json -BmcReplayReceipt ..\prod2u-{{BUILD_ID}}-runtime\bmc-replay-session.json -OutputDir ..\prod2u-{{BUILD_ID}}-evidence
+```
+
+需要完整 BMC gate 时,先在第二个显式串口启动 poll-response replay。运行时文件必须写在包目录外;`--receipt ..\prod2u-{{BUILD_ID}}-runtime\bmc-replay-session.json` 必须写出此次 replay session receipt:
+
+```powershell
+python -B .\prod2u_bmc_replay.py replay --port COM6 --payload .\bmc-replay-payload.json --iterations 0 --timeout-sec 0 --receipt ..\prod2u-{{BUILD_ID}}-runtime\bmc-replay-session.json --json
+```
+
+然后在包根目录运行:
+
+```powershell
+powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\prod2u.ps1 all -CombinedPort COM5 -Bitstream .\fw.bit -TdReceipt .\td.json -SourceManifest .\source-manifest.json -BmcReplayReceipt ..\prod2u-{{BUILD_ID}}-runtime\bmc-replay-session.json -OutputDir ..\prod2u-{{BUILD_ID}}-evidence
+```
+
+工具只允许 `PROGRAM_SRAM`,固定 AL-Link cable 0、speed code 2(200kHz)、单次尝试、零自动重试。`all` 会自动执行这一次 SRAM 下载,随后检查启动 READY 和收集证据;不要断电。失败后保留 raw 和日志并停止。
+
+只验证 programmer 时使用 `program-only`;只采集串口时使用 `collect-only`,但后者不能形成 fresh epoch strict pass。
+
+未接第二路 BMC replay 时,BMC layer 必须保持 `not_run/blocked`。真实 PTC/FAN 负载、热性能和真实 PID 闭环不在本包 pass 范围内。Prod2U 子 gate 证据是仓库 `final-gate-v2` 的输入,不代替仓库 final gate。

+ 411 - 0
receipts/prod2u_bmc_replay_payload_real_capture_20260711.json

@@ -0,0 +1,411 @@
+{
+  "schema": "prod2u-bmc-replay-payload-v1",
+  "status": "pass",
+  "generated_at": "2026-07-11T03:21:23Z",
+  "source": "real_bmc_capture",
+  "bmc_source": "pc_replay_from_real_bmc_capture",
+  "live_bmc_link_status": "not_used",
+  "replay_mode": "poll_response",
+  "seq": 1,
+  "poll_text": "ipmitool raw 0x36 0x6c 0xdf 0xdd 0x00 0x03",
+  "poll_command_text": "ipmitool raw 0x36 0x6c 0xdf 0xdd 0x00 0x03\n",
+  "reply_text": "1e 4b ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff 20 19 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff\r\n",
+  "reply_sha256": "06c173f91f8b6b0e56f9c381b49d5b127d2dbf3a09402843838a0ff2b812f1af",
+  "capture_text_sha256": "1426e31084d5fa6108476b32b45428a4ab5cf49a96a4c8801805faf37f4620ad",
+  "byte_count": 48,
+  "valid_count": 2,
+  "missing_count": 22,
+  "rejected_echo_windows": 0,
+  "payload_hex": [
+    "1e",
+    "4b",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "20",
+    "19",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff",
+    "ff"
+  ],
+  "temperatures": [
+    {
+      "id": 0,
+      "dimm": 1,
+      "temperature_c": 30,
+      "integer_c": 30,
+      "fraction": 75,
+      "valid": true,
+      "status": "valid",
+      "raw_pair": [
+        30,
+        75
+      ]
+    },
+    {
+      "id": 1,
+      "dimm": 2,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 2,
+      "dimm": 3,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 3,
+      "dimm": 4,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 4,
+      "dimm": 5,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 5,
+      "dimm": 6,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 6,
+      "dimm": 7,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 7,
+      "dimm": 8,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 8,
+      "dimm": 9,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 9,
+      "dimm": 10,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 10,
+      "dimm": 11,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 11,
+      "dimm": 12,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 12,
+      "dimm": 13,
+      "temperature_c": 32,
+      "integer_c": 32,
+      "fraction": 25,
+      "valid": true,
+      "status": "valid",
+      "raw_pair": [
+        32,
+        25
+      ]
+    },
+    {
+      "id": 13,
+      "dimm": 14,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 14,
+      "dimm": 15,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 15,
+      "dimm": 16,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 16,
+      "dimm": 17,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 17,
+      "dimm": 18,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 18,
+      "dimm": 19,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 19,
+      "dimm": 20,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 20,
+      "dimm": 21,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 21,
+      "dimm": 22,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 22,
+      "dimm": 23,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    },
+    {
+      "id": 23,
+      "dimm": 24,
+      "temperature_c": null,
+      "integer_c": null,
+      "fraction": null,
+      "valid": false,
+      "status": "missing",
+      "raw_pair": [
+        255,
+        255
+      ],
+      "reason": "missing"
+    }
+  ],
+  "safety": {
+    "unsolicited_reply_attempted": false,
+    "driver_install_attempted": false,
+    "programs_nonvolatile": false
+  },
+  "authority_boundary": "PC replay replies only after observing the CPLD BMC poll text. The payload comes from a prior real BMC capture and is not live BMC evidence."
+}

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 86 - 0
receipts/prod2u_formal_20260711T044529Z.json


+ 622 - 0
receipts/prod2u_rtl_sim_20260711T044348Z.json

@@ -0,0 +1,622 @@
+{
+  "status": "pass",
+  "verification_layer": "hdl_sim",
+  "origin": "project_defined_optional_verification_layer",
+  "backend": "icarus",
+  "fact_class": "project_defined_strategy",
+  "authority_boundary": "This is a project harness strategy, not an Anlogic TD or chip-vendor requirement.",
+  "scenario": null,
+  "required_tools": [
+    "iverilog",
+    "vvp"
+  ],
+  "tool": "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+  "tests": [
+    {
+      "name": "debug_trigger_unit_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\debug_trigger_unit_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_trigger_unit.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\debug_trigger_unit_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: debug_trigger_unit_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\debug_trigger_unit_tb.v:90: $finish called at 6000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "debug_trace_recorder_bram_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\debug_trace_recorder_bram_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_trace_recorder_bram.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\debug_trace_recorder_bram_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: debug_trace_recorder_bram_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\debug_trace_recorder_bram_tb.v:102: $finish called at 170000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "debug_register_window_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\debug_register_window_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_register_window.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\debug_register_window_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: debug_register_window_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\debug_register_window_tb.v:64: $finish called at 5000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "debug_uart_stream_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\debug_uart_stream_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_uart_stream.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\debug_uart_stream_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: debug_uart_stream_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\debug_uart_stream_tb.v:143: $finish called at 3675000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "uart_8n1_phy_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\uart_8n1_phy_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\uart_tx_8n1.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\uart_rx_8n1.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\uart_8n1_phy_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: uart_8n1_phy_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\uart_8n1_phy_tb.v:77: $finish called at 480000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "uart_rx_error_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\uart_rx_error_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\uart_rx_8n1.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\uart_rx_error_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: uart_rx_error_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\uart_rx_error_tb.v:77: $finish called at 1000000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "uart_rx_back_to_back_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\uart_rx_back_to_back_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\uart_rx_8n1.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\uart_rx_back_to_back_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: uart_rx_back_to_back_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\uart_rx_back_to_back_tb.v:92: $finish called at 3400000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\uart_tx_8n1.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\uart_rx_8n1.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\bmc_uart_raw48_poll_lite.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\top\\uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top_tb.v:585: $finish called at 26447740000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "uart_rs232_j6_host_sensor_real_fan_ptc_binary921_top_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\uart_rs232_j6_host_sensor_real_fan_ptc_binary921_top_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\uart_tx_8n1.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\uart_rx_8n1.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\bmc_uart_raw48_poll_lite.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\binary921_crc16.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\binary921_frame_tx.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\binary921_host_rx.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\binary921_diag_core.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\top\\uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921_top.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\uart_rs232_j6_host_sensor_real_fan_ptc_binary921_top_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: uart_rs232_j6_host_sensor_real_fan_ptc_binary921_top_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\uart_rs232_j6_host_sensor_real_fan_ptc_binary921_top_tb.v:488: $finish called at 517945000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "prod2u_bmc_replay_binary921_top_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\prod2u_bmc_replay_binary921_top_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\uart_tx_8n1.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\uart_rx_8n1.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\bmc_uart_raw48_poll_lite.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\binary921_crc16.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\binary921_frame_tx.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\binary921_host_rx.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\prod2u_por.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\binary921_diag_core.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\top\\prod2u_bmc_replay_binary921_top.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\prod2u_bmc_replay_binary921_top_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: prod2u_bmc_replay_binary921_top_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\prod2u_bmc_replay_binary921_top_tb.v:294: $finish called at 323705000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "prod2u_por_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\prod2u_por_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\prod2u_por.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\prod2u_por_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: prod2u_por_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\prod2u_por_tb.v:59: $finish called at 40960000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "bmc_uart_phy_bridge_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\bmc_uart_phy_bridge_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\bmc_uart_phy_bridge.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\bmc_uart_phy_bridge_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: bmc_uart_phy_bridge_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\bmc_uart_phy_bridge_tb.v:100: $finish called at 100000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "bmc_uart_ascii_poll_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\bmc_uart_ascii_poll_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\bmc_uart_ascii_poll.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\bmc_uart_ascii_poll_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: bmc_uart_ascii_poll_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\bmc_uart_ascii_poll_tb.v:222: $finish called at 8240000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "bmc_dimm_frame_parser_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\bmc_dimm_frame_parser_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\bmc_dimm_frame_parser.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\bmc_dimm_frame_parser_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: bmc_dimm_frame_parser_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\bmc_dimm_frame_parser_tb.v:142: $finish called at 86000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "source_arbitrator_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\source_arbitrator_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\source_arbitrator.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\source_arbitrator_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: source_arbitrator_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\source_arbitrator_tb.v:105: $finish called at 26000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "hysteresis_pi_controller_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\hysteresis_pi_controller_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\hysteresis_pi_controller.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\hysteresis_pi_controller_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: hysteresis_pi_controller_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\hysteresis_pi_controller_tb.v:82: $finish called at 86000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "control_service_24ch_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\control_service_24ch_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\pid_24ch_scheduler.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\control_service_24ch.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\control_service_24ch_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: control_service_24ch_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\control_service_24ch_tb.v:143: $finish called at 210000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "pid_core_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\pid_core_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\pid_core.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\pid_core_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: pid_core_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\pid_core_tb.v:90: $finish called at 1080000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "pid_contract_integration_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\pid_contract_integration_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\pid_24ch_scheduler.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\actuator_sink.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\pid_contract_integration_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: pid_contract_integration_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\pid_contract_integration_tb.v:276: $finish called at 770000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "pid_source_mux_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\pid_source_mux_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\sensor_source_mux.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\pid_source_mux_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: pid_source_mux_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\pid_source_mux_tb.v:159: $finish called at 26000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "pid_control_regfile_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\pid_control_regfile_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\pid_control_regfile.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\pid_control_regfile_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: pid_control_regfile_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\pid_control_regfile_tb.v:214: $finish called at 555000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "sensor_domain_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\sensor_domain_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\sensor_source_mux.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\sensor_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\sensor_domain_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: sensor_domain_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\sensor_domain_tb.v:171: $finish called at 4000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "host_command_plane_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\host_command_plane_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\pid_control_regfile.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\host_command_plane.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\host_command_plane_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: host_command_plane_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\host_command_plane_tb.v:173: $finish called at 522000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "safety_supervisor_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\safety_supervisor_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\safety_supervisor.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\safety_supervisor_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: safety_supervisor_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\safety_supervisor_tb.v:142: $finish called at 180000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "ptc_output_bank_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\ptc_output_bank_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\ptc_output_bank.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\ptc_output_bank_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: ptc_output_bank_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\ptc_output_bank_tb.v:144: $finish called at 2610000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "fan_tach_domain_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\fan_tach_domain_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\fan_tach_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\fan_tach_domain_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: fan_tach_domain_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\fan_tach_domain_tb.v:143: $finish called at 32100000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "board_io_adapter_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\board_io_adapter_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\board_io_adapter.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\board_io_adapter_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: board_io_adapter_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\board_io_adapter_tb.v:46: $finish called at 2000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "motor_limit_domain_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\motor_limit_domain_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\motor_limit_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\motor_limit_domain_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: motor_limit_domain_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\motor_limit_domain_tb.v:88: $finish called at 70000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "actuator_domain_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\actuator_domain_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\ptc_output_bank.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\fan_tach_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\board_io_adapter.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\motor_limit_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\actuator_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\actuator_domain_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: actuator_domain_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\actuator_domain_tb.v:196: $finish called at 130000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "debug_snapshot_v2_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\debug_snapshot_v2_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_snapshot_v2.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\debug_snapshot_v2_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: debug_snapshot_v2_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\debug_snapshot_v2_tb.v:130: $finish called at 50000 (1ps)\n",
+      "run_stderr": ""
+    },
+    {
+      "name": "system_contract_top_tb",
+      "status": "pass",
+      "compile_command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\iverilog.exe",
+        "-g2005-sv",
+        "-o",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tmp\\rtl_sim\\system_contract_top_tb.vvp",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\bmc_uart_ascii_poll.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\bmc_dimm_frame_parser.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\fake_sensor_source.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\i2c_master_sensor_adapter.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\pid_control_regfile.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\sensor_source_mux.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\sensor_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\host_command_plane.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\safety_supervisor.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\ptc_output_bank.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\fan_tach_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\board_io_adapter.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\motor_limit_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\pid_24ch_scheduler.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\actuator_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_snapshot_v2.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_trigger_unit.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_trace_recorder_bram.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_register_window.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_uart_stream.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_probe_bus.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\top\\system_contract_top.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\system_contract_top_tb.v"
+      ],
+      "compile_returncode": 0,
+      "compile_stdout": "",
+      "compile_stderr": "",
+      "run_returncode": 0,
+      "run_stdout": "PASS: system_contract_top_tb\nC:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\sim\\system_contract_top_tb.v:275: $finish called at 10080000 (1ps)\n",
+      "run_stderr": ""
+    }
+  ]
+}

+ 81 - 0
receipts/prod2u_verilator_lint_20260711T044509Z.json

@@ -0,0 +1,81 @@
+{
+  "status": "pass",
+  "verification_layer": "hdl_sim",
+  "origin": "project_defined_optional_verification_layer",
+  "backend": "verilator",
+  "fact_class": "project_defined_strategy",
+  "authority_boundary": "This is a project harness strategy, not an Anlogic TD or chip-vendor requirement.",
+  "scenario": null,
+  "mode": "lint_first",
+  "command_mode": "verilator --lint-only",
+  "required_tools": [
+    "verilator"
+  ],
+  "tests": [
+    {
+      "name": "pid_contract_rtl_and_tops",
+      "status": "pass",
+      "returncode": 0,
+      "command": [
+        "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\verilator_bin.exe",
+        "--lint-only",
+        "-Wall",
+        "--timing",
+        "-Wno-MULTITOP",
+        "-Wno-WIDTHTRUNC",
+        "-Wno-WIDTHEXPAND",
+        "-Wno-BLKSEQ",
+        "-Wno-UNUSEDPARAM",
+        "-Wno-UNUSEDSIGNAL",
+        "-Wno-VARHIDDEN",
+        "-Wno-CASEINCOMPLETE",
+        "-Wno-SYNCASYNCNET",
+        "-Wno-PINCONNECTEMPTY",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\verilator_waivers.vlt",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_trigger_unit.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_trace_recorder_bram.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_register_window.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_uart_stream.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\uart_tx_8n1.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\uart_rx_8n1.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\bmc_uart_raw48_poll_lite.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\top\\uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\binary921_crc16.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\binary921_frame_tx.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\binary921_host_rx.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\binary921_diag_core.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\top\\uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921_top.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\prod2u_por.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\top\\prod2u_bmc_replay_binary921_top.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\bmc_uart_phy_bridge.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\bmc_uart_ascii_poll.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\bmc_dimm_frame_parser.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\source_arbitrator.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\hysteresis_pi_controller.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\pid_24ch_scheduler.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\control_service_24ch.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\pid_core.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\actuator_sink.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\sensor_source_mux.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\pid_control_regfile.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\sensor_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\host_command_plane.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\safety_supervisor.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\ptc_output_bank.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\fan_tach_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\board_io_adapter.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\motor_limit_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\actuator_domain.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_snapshot_v2.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\fake_sensor_source.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\i2c_master_sensor_adapter.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\rtl\\debug_probe_bus.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\src\\top\\system_contract_top.v",
+        "C:\\Users\\Administrator\\Agentworkspace\\CPLD\\tests\\verilator_prod2u_build_id_guard_stub.v"
+      ],
+      "stdout": "- V e r i l a t i o n   R e p o r t: Verilator 5.049 devel rev v5.048-347-g6b3e2ce97 (mod)\n- Verilator: Built from 8.879 MB sources in 41 modules, into 2.689 MB in 5 C++ files needing 0.000 MB\n- Verilator: Walltime 0.530 s (elab=0.043, cvt=0.393, bld=0.000); cpu 0.000 s on 1 threads; allocated 60.852 MB\n",
+      "stderr": ""
+    }
+  ],
+  "tool": "C:\\Users\\Administrator\\CodexToolchains\\CPLD\\oss-cad-suite\\latest\\bin\\verilator_bin.exe"
+}

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 688 - 0
receipts/td_prod2u_bmc_replay_binary921_20260711T044118Z.json


+ 130 - 0
schemas/prod2u_evidence_manifest.schema.json

@@ -0,0 +1,130 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "prod2u-evidence-manifest-v1",
+  "title": "Prod2U binary921 evidence manifest",
+  "type": "object",
+  "required": [
+    "schema",
+    "status",
+    "protocol",
+    "profile",
+    "profile_id",
+    "build_identity",
+    "programmer_receipt",
+    "startup_ready",
+    "host_command_count",
+    "host_ack_count",
+    "host_ack_matched_count",
+    "bmc_replay",
+    "artifact_hashes",
+    "real_fan_ptc_hardware_status",
+    "safety"
+  ],
+  "properties": {
+    "schema": {"const": "prod2u-evidence-manifest-v1"},
+    "status": {"enum": ["pass", "blocked_bmc_replay_not_run", "blocked", "fail"]},
+    "protocol": {"const": "binary921"},
+    "profile": {"const": "prod2u-bmc-replay-binary921"},
+    "profile_id": {"const": 3},
+    "build_identity": {
+      "type": "object",
+      "required": ["build_id", "source_manifest_sha256"],
+      "properties": {
+        "build_id": {"type": "string", "pattern": "^[0-9A-Fa-f]{8}$"},
+        "source_manifest_sha256": {"type": "string", "pattern": "^[0-9A-Fa-f]{64}$"}
+      },
+      "additionalProperties": true
+    },
+    "startup_ready": {
+      "type": "object",
+      "required": ["frame_type", "seq", "profile_id", "build_id", "post_program_epoch", "por_reason", "announcement_seq", "matching_ready_count", "selection_policy"],
+      "properties": {
+        "frame_type": {"const": 1},
+        "seq": {"const": 1},
+        "profile_id": {"const": 3},
+        "build_id": {"type": "string", "pattern": "^[0-9A-Fa-f]{8}$"},
+        "post_program_epoch": {"const": true},
+        "por_reason": {"const": 1},
+        "announcement_seq": {"type": "integer", "minimum": 0, "maximum": 2},
+        "matching_ready_count": {"type": "integer", "minimum": 1},
+        "selection_policy": {"const": "last_matching_ready"}
+      },
+      "additionalProperties": true
+    },
+    "host_command_count": {"const": 12},
+    "host_ack_count": {"const": 12},
+    "host_ack_matched_count": {"const": 12},
+    "programmer_receipt": {
+      "type": "object",
+      "required": ["path", "sha256", "status"],
+      "properties": {
+        "path": {"type": "string", "minLength": 1},
+        "sha256": {"$ref": "#/$defs/nonEmptySha256"},
+        "status": {"type": "string", "minLength": 1}
+      },
+      "additionalProperties": true
+    },
+    "bmc_replay": {
+      "type": "object",
+      "required": ["status", "bmc_source", "payload_sha256"],
+      "properties": {
+        "status": {"type": "string", "minLength": 1},
+        "bmc_source": {"type": ["string", "null"]},
+        "payload_sha256": {
+          "anyOf": [
+            {"$ref": "#/$defs/nonEmptySha256"},
+            {"type": "null"}
+          ]
+        }
+      },
+      "additionalProperties": true
+    },
+    "artifact_hashes": {
+      "type": "object",
+      "required": ["combined-rx.raw", "host-command-wire.bin"],
+      "properties": {
+        "combined-rx.raw": {"$ref": "#/$defs/nonEmptySha256"},
+        "host-command-wire.bin": {"$ref": "#/$defs/nonEmptySha256"}
+      },
+      "additionalProperties": true
+    },
+    "real_fan_ptc_hardware_status": {"const": "not_run"},
+    "safety": {
+      "type": "object",
+      "required": ["flash_attempted", "programs_nonvolatile", "driver_install_attempted", "power_cycle_attempted", "toggles_dtr_rts"],
+      "properties": {
+        "flash_attempted": {"const": false},
+        "programs_nonvolatile": {"const": false},
+        "driver_install_attempted": {"const": false},
+        "power_cycle_attempted": {"const": false},
+        "toggles_dtr_rts": {"const": false}
+      },
+      "additionalProperties": true
+    }
+  },
+  "allOf": [
+    {
+      "if": {"properties": {"status": {"const": "pass"}}, "required": ["status"]},
+      "then": {
+        "properties": {
+          "programmer_receipt": {"properties": {"status": {"const": "pass"}}},
+          "bmc_replay": {
+            "properties": {
+              "status": {"const": "pass"},
+              "bmc_source": {"const": "pc_replay_from_real_bmc_capture"},
+              "payload_sha256": {"$ref": "#/$defs/nonEmptySha256"}
+            }
+          }
+        }
+      }
+    }
+  ],
+  "additionalProperties": true,
+  "$defs": {
+    "nonEmptySha256": {
+      "type": "string",
+      "pattern": "^[0-9a-f]{64}$",
+      "not": {"const": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}
+    }
+  }
+}

+ 51 - 0
schemas/prod2u_final_gate.schema.json

@@ -0,0 +1,51 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "prod2u-final-gate-v1",
+  "title": "Prod2U final gate receipt",
+  "type": "object",
+  "required": ["schema", "status", "failures", "layers", "authority_boundary"],
+  "properties": {
+    "schema": {"const": "prod2u-final-gate-v1"},
+    "status": {"enum": ["pass", "blocked", "fail"]},
+    "failures": {"type": "array", "items": {"type": "string"}},
+    "layers": {
+      "type": "object",
+      "required": ["static", "rtl_sim", "formal", "td_build", "program_sram", "fresh_epoch", "host_uart", "bmc_replay"],
+      "properties": {
+        "static": {"enum": ["pass", "blocked", "not_run", "fail"]},
+        "rtl_sim": {"enum": ["pass", "blocked", "not_run", "fail"]},
+        "formal": {"enum": ["pass", "blocked", "not_run", "fail"]},
+        "td_build": {"enum": ["pass", "blocked", "not_run", "fail"]},
+        "program_sram": {"enum": ["pass", "blocked", "not_run", "fail"]},
+        "fresh_epoch": {"enum": ["pass", "blocked", "not_run", "fail"]},
+        "host_uart": {"enum": ["pass", "blocked", "not_run", "fail"]},
+        "bmc_replay": {"enum": ["pass", "blocked", "not_run", "fail"]}
+      },
+      "additionalProperties": true
+    },
+    "authority_boundary": {"type": "string", "minLength": 1}
+  },
+  "allOf": [
+    {
+      "if": {"properties": {"status": {"const": "pass"}}, "required": ["status"]},
+      "then": {
+        "properties": {
+          "failures": {"maxItems": 0},
+          "layers": {
+            "properties": {
+              "static": {"const": "pass"},
+              "rtl_sim": {"const": "pass"},
+              "formal": {"const": "pass"},
+              "td_build": {"const": "pass"},
+              "program_sram": {"const": "pass"},
+              "fresh_epoch": {"const": "pass"},
+              "host_uart": {"const": "pass"},
+              "bmc_replay": {"const": "pass"}
+            }
+          }
+        }
+      }
+    }
+  ],
+  "additionalProperties": true
+}

+ 241 - 0
schemas/prod2u_program_sram_receipt.schema.json

@@ -0,0 +1,241 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "prod2u-program-sram-receipt-v1",
+  "title": "Prod2U PROGRAM_SRAM receipt",
+  "type": "object",
+  "required": [
+    "schema",
+    "status",
+    "run_id",
+    "request",
+    "bitstream",
+    "staging",
+    "execution",
+    "parser",
+    "safety",
+    "tool",
+    "mutex",
+    "process_cleanup",
+    "artifacts",
+    "authority_boundary"
+  ],
+  "properties": {
+    "schema": {"const": "prod2u-program-sram-receipt-v1"},
+    "status": {"enum": ["pass", "fail", "fail_forbidden_action"]},
+    "run_id": {"type": "string", "minLength": 1},
+    "request": {
+      "type": "object",
+      "required": ["operation", "target_chip", "cable_index", "speed_code", "speed_hz", "attempt_limit", "power_cycle_allowed"],
+      "properties": {
+        "operation": {"const": "PROGRAM_SRAM"},
+        "target_chip": {"const": "EF2L45"},
+        "cable_index": {"const": 0},
+        "speed_code": {"const": 2},
+        "speed_hz": {"const": 200000},
+        "attempt_limit": {"const": 1},
+        "power_cycle_allowed": {"const": false}
+      },
+      "additionalProperties": true
+    },
+    "bitstream": {
+      "type": "object",
+      "required": ["path", "sha256", "build_id"],
+      "properties": {
+        "path": {"type": "string", "minLength": 1},
+        "sha256": {"type": "string", "pattern": "^[0-9a-fA-F]{64}$"},
+        "build_id": {"type": "string", "pattern": "^[0-9A-F]{8}$"}
+      },
+      "additionalProperties": true
+    },
+    "staging": {
+      "type": "object",
+      "required": ["expected_path", "observed_path", "matches_expected_path"],
+      "properties": {
+        "expected_path": {"type": "string"},
+        "observed_path": {"type": "string"},
+        "matches_expected_path": {"type": "boolean"}
+      },
+      "additionalProperties": true
+    },
+    "execution": {
+      "type": "object",
+      "required": ["exit_code", "timed_out", "attempt_count", "retry_count", "power_cycle_count", "command_execution_attempted", "timeout_seconds", "started_at", "finished_at", "duration_seconds"],
+      "properties": {
+        "exit_code": {"type": "integer"},
+        "timed_out": {"type": "boolean"},
+        "attempt_count": {"const": 1},
+        "retry_count": {"const": 0},
+        "power_cycle_count": {"const": 0},
+        "command_execution_attempted": {"type": "boolean"},
+        "timeout_seconds": {"const": 60},
+        "started_at": {"type": "string", "minLength": 1},
+        "finished_at": {"type": "string", "minLength": 1},
+        "duration_seconds": {"type": "number", "minimum": 0}
+      },
+      "additionalProperties": true
+    },
+    "parser": {
+      "type": "object",
+      "required": ["status", "exit_code_trusted", "ordered_markers", "ordered_markers_complete", "observed_markers", "observed_marker_lines", "error_markers", "failures", "transcript_sha256"],
+      "properties": {
+        "status": {"enum": ["pass", "fail"]},
+        "exit_code_trusted": {"const": false},
+        "ordered_markers": {"const": ["download_start", "chip_validation", "bit_to_vec_start", "bit_to_vec_finish", "program_start", "program_finish", "download_finish"]},
+        "ordered_markers_complete": {"type": "boolean"},
+        "observed_markers": {"type": "array", "items": {"type": "string"}},
+        "observed_marker_lines": {"type": "array", "items": {"type": "integer", "minimum": 1}},
+        "error_markers": {"type": "array", "items": {"type": "string"}},
+        "failures": {"type": "array", "items": {"type": "string"}},
+        "transcript_sha256": {"$ref": "#/$defs/nonEmptySha256"}
+      },
+      "additionalProperties": true
+    },
+    "safety": {
+      "type": "object",
+      "required": ["flash_attempted", "programs_nonvolatile", "power_cycle_attempted", "driver_install_attempted", "toggles_dtr_rts", "real_ptc_fan_action_attempted", "external_programming_command_executed"],
+      "properties": {
+        "flash_attempted": {"type": "boolean"},
+        "programs_nonvolatile": {"type": "boolean"},
+        "power_cycle_attempted": {"const": false},
+        "driver_install_attempted": {"const": false},
+        "toggles_dtr_rts": {"const": false},
+        "real_ptc_fan_action_attempted": {"const": false},
+        "external_programming_command_executed": {"type": "boolean"}
+      },
+      "additionalProperties": true
+    },
+    "tool": {
+      "type": "object",
+      "required": ["path", "td_root", "td_bin"],
+      "properties": {
+        "path": {"type": "string", "minLength": 1},
+        "td_root": {"type": "string", "minLength": 1},
+        "td_bin": {"type": "string", "minLength": 1}
+      },
+      "additionalProperties": true
+    },
+    "mutex": {
+      "type": "object",
+      "required": ["name", "acquired"],
+      "properties": {
+        "name": {"const": "Global\\Prod2UProgramSram"},
+        "acquired": {"const": true}
+      },
+      "additionalProperties": true
+    },
+    "process_cleanup": {
+      "type": "object",
+      "required": ["status", "td_root", "graceful_close_requested", "forced_terminated", "wait_seconds", "remaining"],
+      "properties": {
+        "status": {"const": "pass"},
+        "td_root": {"type": "string", "minLength": 1},
+        "graceful_close_requested": {"type": "array", "items": {"type": "string"}},
+        "forced_terminated": {"type": "array", "items": {"type": "string"}},
+        "wait_seconds": {"const": 5.0},
+        "remaining": {"type": "array", "maxItems": 0}
+      },
+      "additionalProperties": true
+    },
+    "artifacts": {
+      "type": "object",
+      "required": ["tcl", "stdout", "stderr", "log_delta", "log_delta_sources"],
+      "properties": {
+        "tcl": {"$ref": "#/$defs/artifact"},
+        "stdout": {"$ref": "#/$defs/artifact"},
+        "stderr": {"$ref": "#/$defs/artifact"},
+        "log_delta": {"$ref": "#/$defs/artifact"},
+        "log_delta_sources": {
+          "type": "array",
+          "items": {
+            "type": "object",
+            "required": ["path", "start_offset", "byte_count", "sha256"],
+            "properties": {
+              "path": {"type": "string", "minLength": 1, "pattern": "(^|[\\\\/])bw_[^\\\\/]+\\.log$"},
+              "start_offset": {"type": "integer", "minimum": 0},
+              "byte_count": {"type": "integer", "minimum": 1},
+              "sha256": {"$ref": "#/$defs/nonEmptySha256"}
+            },
+            "additionalProperties": true
+          }
+        }
+      },
+      "additionalProperties": true
+    },
+    "authority_boundary": {"type": "string", "minLength": 1}
+  },
+  "additionalProperties": true,
+  "allOf": [
+    {
+      "if": {
+        "properties": {"status": {"const": "pass"}},
+        "required": ["status"]
+      },
+      "then": {
+        "properties": {
+          "staging": {
+            "properties": {"matches_expected_path": {"const": true}}
+          },
+          "execution": {
+            "properties": {
+              "exit_code": {"const": 0},
+              "timed_out": {"const": false},
+              "attempt_count": {"const": 1},
+              "retry_count": {"const": 0},
+              "power_cycle_count": {"const": 0},
+              "command_execution_attempted": {"const": true},
+              "timeout_seconds": {"const": 60}
+            }
+          },
+          "parser": {
+            "properties": {
+              "status": {"const": "pass"},
+              "ordered_markers_complete": {"const": true},
+              "observed_markers": {"const": ["download_start", "chip_validation", "bit_to_vec_start", "bit_to_vec_finish", "program_start", "program_finish", "download_finish"]},
+              "error_markers": {"maxItems": 0},
+              "failures": {"maxItems": 0}
+            }
+          },
+          "artifacts": {
+            "properties": {
+              "log_delta": {
+                "properties": {
+                  "size": {"type": "integer", "minimum": 1},
+                  "sha256": {"$ref": "#/$defs/nonEmptySha256"}
+                }
+              },
+              "log_delta_sources": {"minItems": 1, "maxItems": 1}
+            }
+          },
+          "safety": {
+            "properties": {
+              "flash_attempted": {"const": false},
+              "programs_nonvolatile": {"const": false},
+              "power_cycle_attempted": {"const": false},
+              "driver_install_attempted": {"const": false},
+              "toggles_dtr_rts": {"const": false},
+              "real_ptc_fan_action_attempted": {"const": false},
+              "external_programming_command_executed": {"const": true}
+            }
+          }
+        }
+      }
+    }
+  ],
+  "$defs": {
+    "nonEmptySha256": {
+      "type": "string",
+      "pattern": "^[0-9a-f]{64}$",
+      "not": {"const": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}
+    },
+    "artifact": {
+      "type": "object",
+      "required": ["path", "size", "sha256"],
+      "properties": {
+        "path": {"type": "string", "minLength": 1},
+        "size": {"type": "integer", "minimum": 0},
+        "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}
+      },
+      "additionalProperties": true
+    }
+  }
+}

+ 65 - 0
schemas/prod2u_td_build_receipt.schema.json

@@ -0,0 +1,65 @@
+{
+  "$schema": "https://json-schema.org/draft/2020-12/schema",
+  "$id": "prod2u-td-build-receipt-v1",
+  "title": "Prod2U TD build receipt",
+  "type": "object",
+  "required": ["schema", "status", "top", "top_module", "pin_profile"],
+  "properties": {
+    "schema": {"const": "prod2u-td-build-receipt-v1"},
+    "status": {"enum": ["pass", "skipped", "blocked", "blocked_pin_profile_invalid", "blocked_missing_real_fan_ptc_pin_inventory", "fail", "fail_build_identity"]},
+    "top": {"const": "prod2u_bmc_replay_binary921"},
+    "top_module": {"const": "prod2u_bmc_replay_binary921_top"},
+    "pin_profile": {"const": "prod2u-bmc-replay-binary921"},
+    "build_identity": {
+      "type": "object",
+      "properties": {
+        "status": {"type": "string"},
+        "build_id": {"type": "string", "pattern": "^[0-9A-F]{8}$"},
+        "source_manifest_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
+        "staged_manifest_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}
+      },
+      "additionalProperties": true
+    },
+    "build_id": {"type": ["string", "null"], "pattern": "^[0-9A-F]{8}$"},
+    "source_manifest_sha256": {"type": ["string", "null"], "pattern": "^[0-9a-f]{64}$"},
+    "por_initialization": {
+      "type": "object",
+      "required": ["status", "por_cycles", "counter_width", "expected_init", "register_count", "failures"],
+      "properties": {
+        "status": {"enum": ["pass", "fail", "not_applicable"]},
+        "por_cycles": {"const": 1024},
+        "counter_width": {"const": 10},
+        "expected_init": {"const": "0"},
+        "register_count": {"const": 11},
+        "failures": {"type": "array", "items": {"type": "string"}}
+      },
+      "additionalProperties": true
+    },
+    "bitstream": {
+      "type": ["object", "null"],
+      "properties": {
+        "path": {"type": "string", "minLength": 1},
+        "size": {"type": "integer", "minimum": 1},
+        "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"}
+      },
+      "additionalProperties": true
+    }
+  },
+  "allOf": [
+    {
+      "if": {"properties": {"status": {"const": "pass"}}, "required": ["status"]},
+      "then": {
+        "required": ["build_identity", "build_id", "source_manifest_sha256", "por_initialization", "bitstream", "resources", "timing", "timing_gate", "syn", "phy"],
+        "properties": {
+          "build_identity": {"properties": {"status": {"const": "pass"}}, "required": ["status", "build_id", "source_manifest_sha256", "staged_manifest_sha256"]},
+          "por_initialization": {"properties": {"status": {"const": "pass"}, "failures": {"maxItems": 0}}},
+          "bitstream": {"type": "object", "required": ["path", "size", "sha256"]},
+          "timing_gate": {"type": "object", "properties": {"status": {"const": "pass"}}, "required": ["status"]},
+          "syn": {"type": "object", "properties": {"returncode": {"const": 0}, "log_has_error": {"const": false}}, "required": ["returncode", "log_has_error"]},
+          "phy": {"type": "object", "properties": {"returncode": {"const": 0}, "log_has_error": {"const": false}}, "required": ["returncode", "log_has_error"]}
+        }
+      }
+    }
+  ],
+  "additionalProperties": true
+}

+ 41 - 11
src/rtl/binary921_diag_core.v

@@ -12,7 +12,9 @@ module binary921_diag_core #(
     parameter integer FAN_PWM_PERIOD_TICKS = 1000,
     parameter integer SNAPSHOT_PERIOD_TICKS = 25000000,
     parameter integer PIN_PROFILE = 0,
-    parameter integer COMBINED_HOST_DEBUG_UART = 0
+    parameter integer COMBINED_HOST_DEBUG_UART = 0,
+    parameter integer READY_REPEAT_COUNT = 3,
+    parameter [31:0] BUILD_ID = 32'h00000000
 ) (
     input  wire        sys_clk,
     input  wire        sys_rst_n,
@@ -32,9 +34,11 @@ module binary921_diag_core #(
     localparam [7:0] PROFILE_FORMAL = 8'd2;
     localparam [7:0] PROFILE_PRODUCTION = 8'd3;
     localparam [7:0] PROFILE_ID = (PIN_PROFILE == 2) ? PROFILE_PRODUCTION : ((PIN_PROFILE == 0) ? PROFILE_DEBUG : PROFILE_FORMAL);
+    localparam [7:0] POR_REASON_CONFIG = 8'h01;
     localparam [7:0] FT_READY = 8'h01;
     localparam [7:0] FT_BMC_PAYLOAD = 8'h03;
     localparam [7:0] FT_SENSOR_CACHE = 8'h04;
+    localparam [7:0] FT_HOST_CMD = 8'h05;
     localparam [7:0] FT_HOST_ACK = 8'h06;
     localparam [7:0] FT_PWM_STATE = 8'h07;
     localparam [7:0] FT_PID_STATE = 8'h08;
@@ -132,6 +136,9 @@ module binary921_diag_core #(
     reg [31:0] snapshot_counter;
     reg [31:0] startup_counter;
     reg ready_sent;
+    reg [31:0] ready_repeat_count;
+    reg [31:0] ready_timestamp_tick;
+    reg [7:0] ready_announcement_seq;
     reg [4:0] sensor_index;
     reg [4:0] bmc_pair_index;
     reg [7:0] bmc_prev_byte;
@@ -166,6 +173,7 @@ module binary921_diag_core #(
     localparam [1:0] COMBINED_OWNER_NONE = 2'd0;
     localparam [1:0] COMBINED_OWNER_ACK = 2'd1;
     localparam [1:0] COMBINED_OWNER_DIAG = 2'd2;
+    wire [31:0] diag_timestamp_tick = (diag_type == FT_READY) ? ready_timestamp_tick : tick;
 
     uart_rx_8n1 #(.CLKS_PER_BIT(HOST_UART_CLKS_PER_BIT)) u_host_rx (
         .clk(sys_clk),
@@ -280,8 +288,8 @@ module binary921_diag_core #(
         .profile_id(PROFILE_ID),
         .frame_type(diag_type),
         .frame_seq(diag_seq),
-        .timestamp_tick(tick),
-        .payload_len(diag_payload_len),
+        .timestamp_tick(diag_timestamp_tick),
+            .payload_len(diag_payload_len),
         .payload(diag_payload),
         .busy(diag_busy),
         .done(diag_done),
@@ -432,6 +440,9 @@ module binary921_diag_core #(
             ack_payload_len <= 8'd0;
             ack_payload <= 512'd0;
             ready_sent <= 1'b0;
+            ready_repeat_count <= 32'd0;
+            ready_timestamp_tick <= 32'd0;
+            ready_announcement_seq <= 8'd0;
             startup_counter <= 32'd0;
             status_counter <= 32'd0;
             snapshot_counter <= 32'd0;
@@ -506,9 +517,30 @@ module binary921_diag_core #(
 
             if (startup_counter < STARTUP_DELAY_TICKS[31:0]) begin
                 startup_counter <= startup_counter + 32'd1;
-            end else if (!ready_sent) begin
-                queue_diag_frame(FT_READY, 8'd4, {480'd0, 8'd0, 8'd0, 8'd0, PROFILE_ID});
-                ready_sent <= 1'b1;
+            end else if (ready_repeat_count < READY_REPEAT_COUNT) begin
+                if (!diag_busy && !diag_start) begin
+                    if (ready_repeat_count == 32'd0) begin
+                        debug_frame_seq <= 32'd1;
+                        ready_timestamp_tick <= tick;
+                    end
+                    diag_seq <= 32'd1;
+                    diag_type <= FT_READY;
+                    diag_payload_len <= 8'd7;
+                    diag_payload <= {
+                        456'd0,
+                        ready_announcement_seq,
+                        POR_REASON_CONFIG,
+                        BUILD_ID[31:24],
+                        BUILD_ID[23:16],
+                        BUILD_ID[15:8],
+                        BUILD_ID[7:0],
+                        PROFILE_ID
+                    };
+                    diag_start <= 1'b1;
+                    ready_repeat_count <= ready_repeat_count + 32'd1;
+                    ready_announcement_seq <= ready_announcement_seq + 8'd1;
+                    ready_sent <= 1'b1;
+                end
             end
 
             if (status_counter >= STATUS_PERIOD_TICKS[31:0]) begin
@@ -604,11 +636,9 @@ module binary921_diag_core #(
                 last_status_code <= cmd_status_value;
                 queue_ack(cmd_seq, cmd_id, cmd_status_value, cmd_hash_value);
                 queue_diag_frame(
-                    FT_HOST_ACK,
-                    8'd8,
-                    {448'd0,
-                     cmd_hash_value[15:8], cmd_hash_value[7:0],
-                     8'd0, cmd_status_value, cmd_pct, cmd_ch, cmd_id, cmd_seq[7:0]}
+                    FT_HOST_CMD,
+                    8'd3,
+                    {488'd0, cmd_pct, cmd_ch, cmd_id}
                 );
             end else if (host_timeout_counter >= HOST_TIMEOUT_TICKS[31:0]) begin
                 timeout_active <= 1'b1;

+ 47 - 29
src/rtl/binary921_frame_tx.v

@@ -30,6 +30,12 @@ module binary921_frame_tx #(
     reg [15:0] crc_after_accept;
     reg [7:0] next_byte_index;
     reg [7:0] next_send_byte;
+    reg [7:0] latched_profile_id;
+    reg [7:0] latched_frame_type;
+    reg [31:0] latched_frame_seq;
+    reg [31:0] latched_timestamp_tick;
+    reg [7:0] latched_payload_len;
+    reg [(MAX_PAYLOAD_BYTES*8)-1:0] latched_payload;
 
     binary921_crc16 u_crc (
         .crc_in(crc),
@@ -40,7 +46,7 @@ module binary921_frame_tx #(
     function [7:0] payload_byte;
         input [7:0] index;
         begin
-            payload_byte = payload[(index * 8) +: 8];
+            payload_byte = latched_payload[(index * 8) +: 8];
         end
     endfunction
 
@@ -49,21 +55,21 @@ module binary921_frame_tx #(
             8'd0: send_byte = MAGIC0;
             8'd1: send_byte = MAGIC1;
             8'd2: send_byte = VERSION;
-            8'd3: send_byte = profile_id;
-            8'd4: send_byte = frame_type;
-            8'd5: send_byte = frame_seq[7:0];
-            8'd6: send_byte = frame_seq[15:8];
-            8'd7: send_byte = frame_seq[23:16];
-            8'd8: send_byte = frame_seq[31:24];
-            8'd9: send_byte = timestamp_tick[7:0];
-            8'd10: send_byte = timestamp_tick[15:8];
-            8'd11: send_byte = timestamp_tick[23:16];
-            8'd12: send_byte = timestamp_tick[31:24];
-            8'd13: send_byte = payload_len;
+            8'd3: send_byte = latched_profile_id;
+            8'd4: send_byte = latched_frame_type;
+            8'd5: send_byte = latched_frame_seq[7:0];
+            8'd6: send_byte = latched_frame_seq[15:8];
+            8'd7: send_byte = latched_frame_seq[23:16];
+            8'd8: send_byte = latched_frame_seq[31:24];
+            8'd9: send_byte = latched_timestamp_tick[7:0];
+            8'd10: send_byte = latched_timestamp_tick[15:8];
+            8'd11: send_byte = latched_timestamp_tick[23:16];
+            8'd12: send_byte = latched_timestamp_tick[31:24];
+            8'd13: send_byte = latched_payload_len;
             default: begin
-                if (byte_index < (8'd14 + payload_len)) begin
+                if (byte_index < (8'd14 + latched_payload_len)) begin
                     send_byte = payload_byte(byte_index - 8'd14);
-                end else if (byte_index == (8'd14 + payload_len)) begin
+                end else if (byte_index == (8'd14 + latched_payload_len)) begin
                     send_byte = crc[7:0];
                 end else begin
                     send_byte = crc[15:8];
@@ -74,7 +80,7 @@ module binary921_frame_tx #(
 
     always @* begin
         crc_after_accept = crc;
-        if (byte_index >= 8'd2 && byte_index < (8'd14 + payload_len)) begin
+        if (byte_index >= 8'd2 && byte_index < (8'd14 + latched_payload_len)) begin
             crc_after_accept = crc_next;
         end
         next_byte_index = byte_index + 8'd1;
@@ -82,21 +88,21 @@ module binary921_frame_tx #(
             8'd0: next_send_byte = MAGIC0;
             8'd1: next_send_byte = MAGIC1;
             8'd2: next_send_byte = VERSION;
-            8'd3: next_send_byte = profile_id;
-            8'd4: next_send_byte = frame_type;
-            8'd5: next_send_byte = frame_seq[7:0];
-            8'd6: next_send_byte = frame_seq[15:8];
-            8'd7: next_send_byte = frame_seq[23:16];
-            8'd8: next_send_byte = frame_seq[31:24];
-            8'd9: next_send_byte = timestamp_tick[7:0];
-            8'd10: next_send_byte = timestamp_tick[15:8];
-            8'd11: next_send_byte = timestamp_tick[23:16];
-            8'd12: next_send_byte = timestamp_tick[31:24];
-            8'd13: next_send_byte = payload_len;
+            8'd3: next_send_byte = latched_profile_id;
+            8'd4: next_send_byte = latched_frame_type;
+            8'd5: next_send_byte = latched_frame_seq[7:0];
+            8'd6: next_send_byte = latched_frame_seq[15:8];
+            8'd7: next_send_byte = latched_frame_seq[23:16];
+            8'd8: next_send_byte = latched_frame_seq[31:24];
+            8'd9: next_send_byte = latched_timestamp_tick[7:0];
+            8'd10: next_send_byte = latched_timestamp_tick[15:8];
+            8'd11: next_send_byte = latched_timestamp_tick[23:16];
+            8'd12: next_send_byte = latched_timestamp_tick[31:24];
+            8'd13: next_send_byte = latched_payload_len;
             default: begin
-                if (next_byte_index < (8'd14 + payload_len)) begin
+                if (next_byte_index < (8'd14 + latched_payload_len)) begin
                     next_send_byte = payload_byte(next_byte_index - 8'd14);
-                end else if (next_byte_index == (8'd14 + payload_len)) begin
+                end else if (next_byte_index == (8'd14 + latched_payload_len)) begin
                     next_send_byte = crc_after_accept[7:0];
                 end else begin
                     next_send_byte = crc_after_accept[15:8];
@@ -114,6 +120,12 @@ module binary921_frame_tx #(
             byte_index <= 8'd0;
             total_bytes <= 8'd0;
             crc <= 16'hffff;
+            latched_profile_id <= 8'd0;
+            latched_frame_type <= 8'd0;
+            latched_frame_seq <= 32'd0;
+            latched_timestamp_tick <= 32'd0;
+            latched_payload_len <= 8'd0;
+            latched_payload <= {(MAX_PAYLOAD_BYTES*8){1'b0}};
         end else begin
             done <= 1'b0;
             if (start && !busy) begin
@@ -123,8 +135,14 @@ module binary921_frame_tx #(
                 crc <= 16'hffff;
                 tx_valid <= 1'b1;
                 tx_data <= MAGIC0;
+                latched_profile_id <= profile_id;
+                latched_frame_type <= frame_type;
+                latched_frame_seq <= frame_seq;
+                latched_timestamp_tick <= timestamp_tick;
+                latched_payload_len <= payload_len;
+                latched_payload <= payload;
             end else if (busy && tx_valid && tx_ready) begin
-                if (byte_index >= 8'd2 && byte_index < (8'd14 + payload_len)) begin
+                if (byte_index >= 8'd2 && byte_index < (8'd14 + latched_payload_len)) begin
                     crc <= crc_next;
                 end
                 if (byte_index == total_bytes - 8'd1) begin

+ 32 - 0
src/rtl/prod2u_por.v

@@ -0,0 +1,32 @@
+`timescale 1ns/1ps
+
+module prod2u_por #(
+    parameter integer POR_CYCLES = 1024
+) (
+    input  wire sys_clk,
+    output wire sys_rst_n
+);
+    localparam integer POR_COUNT_WIDTH = (POR_CYCLES <= 1) ? 1 : $clog2(POR_CYCLES);
+
+    reg [POR_COUNT_WIDTH-1:0] por_count;
+    reg por_reset_n;
+
+    initial begin
+        por_count = {POR_COUNT_WIDTH{1'b0}};
+        por_reset_n = 1'b0;
+    end
+
+    always @(posedge sys_clk) begin
+        if (!por_reset_n) begin
+            if (POR_CYCLES <= 1) begin
+                por_reset_n <= 1'b1;
+            end else if (por_count == POR_CYCLES - 1) begin
+                por_reset_n <= 1'b1;
+            end else begin
+                por_count <= por_count + 1'b1;
+            end
+        end
+    end
+
+    assign sys_rst_n = por_reset_n;
+endmodule

+ 19 - 7
src/rtl/uart_rx_8n1.v

@@ -26,6 +26,18 @@ module uart_rx_8n1 #(
     reg [7:0] shift_reg;
     reg [31:0] low_count;
     reg stop_bit_ok;
+    (* ASYNC_REG = "TRUE" *) reg rx_meta;
+    (* ASYNC_REG = "TRUE" *) reg rx_sync;
+
+    always @(posedge clk or negedge rst_n) begin
+        if (!rst_n) begin
+            rx_meta <= 1'b1;
+            rx_sync <= 1'b1;
+        end else begin
+            rx_meta <= rx_i;
+            rx_sync <= rx_meta;
+        end
+    end
 
     always @(posedge clk or negedge rst_n) begin
         if (!rst_n) begin
@@ -45,7 +57,7 @@ module uart_rx_8n1 #(
                 rx_valid <= 1'b0;
             end
 
-            if (!rx_i) begin
+            if (!rx_sync) begin
                 if (low_count < (CLKS_PER_BIT * BREAK_BITS)) begin
                     low_count <= low_count + 32'd1;
                 end else begin
@@ -59,13 +71,13 @@ module uart_rx_8n1 #(
                 clk_count <= 16'd0;
                 bit_index <= 3'd0;
                 stop_bit_ok <= 1'b0;
-                if (!rx_i) begin
+                if (!rx_sync) begin
                     state <= S_START;
                     clk_count <= 16'd0;
                 end
             end else if (state == S_START) begin
                 if (clk_count == (CLKS_PER_BIT[15:0] >> 1)) begin
-                    if (rx_i) begin
+                    if (rx_sync) begin
                         state <= S_IDLE;
                     end
                 end
@@ -78,7 +90,7 @@ module uart_rx_8n1 #(
                 end
             end else if (state == S_DATA) begin
                 if (clk_count == (CLKS_PER_BIT[15:0] >> 1)) begin
-                    shift_reg[bit_index] <= rx_i;
+                    shift_reg[bit_index] <= rx_sync;
                 end
                 if (clk_count == CLKS_PER_BIT[15:0] - 16'd1) begin
                     clk_count <= 16'd0;
@@ -93,14 +105,14 @@ module uart_rx_8n1 #(
                 end
             end else begin
                 if (clk_count == (CLKS_PER_BIT[15:0] >> 1)) begin
-                    stop_bit_ok <= rx_i;
-                    if (!rx_i) begin
+                    stop_bit_ok <= rx_sync;
+                    if (!rx_sync) begin
                         framing_error <= 1'b1;
                     end
                 end
                 if (clk_count == CLKS_PER_BIT[15:0] - 16'd1) begin
                     clk_count <= 16'd0;
-                    state <= rx_i ? S_IDLE : S_START;
+                    state <= rx_sync ? S_IDLE : S_START;
                     if (stop_bit_ok) begin
                         if (rx_valid && !rx_ready) begin
                             overflow <= 1'b1;

+ 21 - 3
src/top/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top.v

@@ -1,6 +1,6 @@
 `timescale 1ns/1ps
 
-module uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top #(
+module prod2u_bmc_replay_binary921_top #(
     parameter integer BMC_UART_CLKS_PER_BIT = 217,
     parameter integer HOST_UART_CLKS_PER_BIT = 27,
     parameter integer DEBUG_UART_CLKS_PER_BIT = 27,
@@ -10,10 +10,12 @@ module uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_bin
     parameter integer HOST_TIMEOUT_TICKS = 125000000,
     parameter integer PTC_PWM_PERIOD_TICKS = 2500000,
     parameter integer FAN_PWM_PERIOD_TICKS = 1000,
-    parameter integer SNAPSHOT_PERIOD_TICKS = 25000000
+    parameter integer SNAPSHOT_PERIOD_TICKS = 25000000,
+    parameter integer POR_CYCLES = 1024,
+    parameter integer READY_REPEAT_COUNT = 3,
+    parameter [31:0] BUILD_ID = 32'h00000000
 ) (
     input  wire        sys_clk,
-    input  wire        sys_rst_n,
     input  wire        bmc_uart_rx,
     output wire        bmc_uart_tx,
     input  wire        host_uart_rx,
@@ -24,8 +26,22 @@ module uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_bin
     input  wire [3:0]  fan_install_in,
     output wire [7:0]  led
 );
+    wire sys_rst_n;
     wire unused_debug_uart_tx;
 
+    generate
+        if (BUILD_ID == 32'h00000000) begin : g_build_identity_required
+            prod2u_build_id_must_be_nonzero u_build_identity_error();
+        end
+    endgenerate
+
+    prod2u_por #(
+        .POR_CYCLES(POR_CYCLES)
+    ) u_por (
+        .sys_clk(sys_clk),
+        .sys_rst_n(sys_rst_n)
+    );
+
     binary921_diag_core #(
         .BMC_UART_CLKS_PER_BIT(BMC_UART_CLKS_PER_BIT),
         .HOST_UART_CLKS_PER_BIT(HOST_UART_CLKS_PER_BIT),
@@ -37,6 +53,8 @@ module uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_bin
         .PTC_PWM_PERIOD_TICKS(PTC_PWM_PERIOD_TICKS),
         .FAN_PWM_PERIOD_TICKS(FAN_PWM_PERIOD_TICKS),
         .SNAPSHOT_PERIOD_TICKS(SNAPSHOT_PERIOD_TICKS),
+        .READY_REPEAT_COUNT(READY_REPEAT_COUNT),
+        .BUILD_ID(BUILD_ID),
         .PIN_PROFILE(2),
         .COMBINED_HOST_DEBUG_UART(1)
     ) u_core (

+ 16 - 0
td/phy/prod2u_bmc_replay_binary921.tcl

@@ -0,0 +1,16 @@
+import_device ef2_4.db -package EF2L45BG256B
+import_db ../syn/prod2u_bmc_replay_binary921_gate.db
+read_adc {constraints/prod2u_bmc_replay_binary921.adc}
+read_sdc {constraints/pid_study_01.sdc}
+set_param route effort routability
+place
+update_timing -mode manhattan
+report_area -io_info -file prod2u_bmc_replay_binary921_phy.area
+report_timing_summary -file prod2u_bmc_replay_binary921_place.timing
+export_db prod2u_bmc_replay_binary921_place.db
+route
+update_timing
+report_area -io_info -file prod2u_bmc_replay_binary921_phy.area
+report_timing_summary -file prod2u_bmc_replay_binary921_pr.timing
+export_db prod2u_bmc_replay_binary921_pr.db
+bitgen -bit prod2u_bmc_replay_binary921.bit

+ 0 - 15
td/phy/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.tcl

@@ -1,15 +0,0 @@
-import_device ef2_4.db -package EF2L45BG256B
-import_db ../syn/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_gate.db
-read_adc {constraints/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.adc}
-read_sdc {constraints/pid_study_01.sdc}
-place
-update_timing -mode manhattan
-report_area -io_info -file uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_phy.area
-report_timing_summary -file uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_place.timing
-export_db uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_place.db
-route
-update_timing
-report_area -io_info -file uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_phy.area
-report_timing_summary -file uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_pr.timing
-export_db uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_pr.db
-bitgen -bit uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.bit

+ 6 - 5
td/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.prj

@@ -2,7 +2,7 @@
 <Project Version="3" Minor="2" RunTime="2026-07-10T00:00:00">
     <Project_Created_Time></Project_Created_Time>
     <TD_Version>6.2.2.198412</TD_Version>
-    <Name>uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921</Name>
+    <Name>prod2u_bmc_replay_binary921</Name>
     <HardWare>
         <Family>EF2</Family>
         <Device>EF2L45BG256B</Device>
@@ -16,11 +16,12 @@
             <File Path="../src/rtl/binary921_crc16.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="4"/></FileInfo></File>
             <File Path="../src/rtl/binary921_frame_tx.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="5"/></FileInfo></File>
             <File Path="../src/rtl/binary921_host_rx.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="6"/></FileInfo></File>
-            <File Path="../src/rtl/binary921_diag_core.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="7"/></FileInfo></File>
-            <File Path="../src/top/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="8"/></FileInfo></File>
+            <File Path="../src/rtl/prod2u_por.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="7"/></FileInfo></File>
+            <File Path="../src/rtl/binary921_diag_core.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="8"/></FileInfo></File>
+            <File Path="../src/top/prod2u_bmc_replay_binary921_top.v"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="design_1"/><Attr Name="CompileOrder" Val="9"/></FileInfo></File>
         </Verilog>
         <ADC_FILE>
-            <File Path="../constraints/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.adc"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="constraint_1"/><Attr Name="CompileOrder" Val="1"/></FileInfo></File>
+            <File Path="../constraints/prod2u_bmc_replay_binary921.adc"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="constraint_1"/><Attr Name="CompileOrder" Val="1"/></FileInfo></File>
         </ADC_FILE>
         <SDC_FILE>
             <File Path="../constraints/pid_study_01.sdc"><FileInfo><Attr Name="UsedInSyn" Val="true"/><Attr Name="UsedInP&amp;R" Val="true"/><Attr Name="BelongTo" Val="constraint_1"/><Attr Name="CompileOrder" Val="2"/></FileInfo></File>
@@ -28,7 +29,7 @@
     </Source_Files>
     <TOP_MODULE>
         <LABEL></LABEL>
-        <MODULE>uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top</MODULE>
+        <MODULE>prod2u_bmc_replay_binary921_top</MODULE>
         <CREATEINDEX>user</CREATEINDEX>
     </TOP_MODULE>
 </Project>

+ 21 - 0
td/syn/prod2u_bmc_replay_binary921.tcl

@@ -0,0 +1,21 @@
+import_device ef2_4.db -package EF2L45BG256B
+analyze -file {src/rtl/uart_rx_8n1.v}
+analyze -file {src/rtl/uart_tx_8n1.v}
+analyze -file {src/rtl/bmc_uart_raw48_poll_lite.v}
+analyze -file {src/rtl/binary921_crc16.v}
+analyze -file {src/rtl/binary921_frame_tx.v}
+analyze -file {src/rtl/binary921_host_rx.v}
+analyze -file {src/rtl/prod2u_por.v}
+analyze -file {src/rtl/binary921_diag_core.v}
+analyze -file {src/top/prod2u_bmc_replay_binary921_top.v}
+elaborate -top {prod2u_bmc_replay_binary921_top}
+read_adc {constraints/prod2u_bmc_replay_binary921.adc}
+read_sdc {constraints/pid_study_01.sdc}
+optimize_rtl
+report_area -file prod2u_bmc_replay_binary921_rtl.area
+export_db prod2u_bmc_replay_binary921_rtl.db
+optimize_gate prod2u_bmc_replay_binary921_gate.area
+legalize_phy_inst
+update_timing
+report_timing_summary -file prod2u_bmc_replay_binary921_gate.timing
+export_db prod2u_bmc_replay_binary921_gate.db

+ 0 - 20
td/syn/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.tcl

@@ -1,20 +0,0 @@
-import_device ef2_4.db -package EF2L45BG256B
-analyze -file {src/rtl/uart_rx_8n1.v}
-analyze -file {src/rtl/uart_tx_8n1.v}
-analyze -file {src/rtl/bmc_uart_raw48_poll_lite.v}
-analyze -file {src/rtl/binary921_crc16.v}
-analyze -file {src/rtl/binary921_frame_tx.v}
-analyze -file {src/rtl/binary921_host_rx.v}
-analyze -file {src/rtl/binary921_diag_core.v}
-analyze -file {src/top/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top.v}
-elaborate -top {uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top}
-read_adc {constraints/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.adc}
-read_sdc {constraints/pid_study_01.sdc}
-optimize_rtl
-report_area -file uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_rtl.area
-export_db uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_rtl.db
-optimize_gate uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_gate.area
-legalize_phy_inst
-update_timing
-report_timing_summary -file uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_gate.timing
-export_db uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_gate.db

+ 9 - 0
tests/fixtures/prod2u_programmer/cli_success_excerpt.log

@@ -0,0 +1,9 @@
+RUN-1002 : start command "connect_cable -allink"
+RUN-1003 : finish command "connect_cable -allink" in 0.000374s wall
+RUN-1002 : start command "download -bit C:/P2U/A1B2C3D4/fw.bit -mode jtag -spd 2 -cable 0"
+PRG-2014 : Chip validation success: EF2L45
+RUN-1002 : start command "bit_to_vec -chip EF2L45 -m jtag_burst -freq 0.200000 -bit C:/P2U/A1B2C3D4/fw.bit"
+RUN-1003 : finish command "bit_to_vec -chip EF2L45 -m jtag_burst -freq 0.200000 -bit C:/P2U/A1B2C3D4/fw.bit" in 0.036617s wall
+RUN-1002 : start command "program -cable 0 -mode svf -spd 2 -p"
+RUN-1003 : finish command "program -cable 0 -mode svf -spd 2 -p" in 10.416059s wall
+RUN-1003 : finish command "download -bit C:/P2U/A1B2C3D4/fw.bit -mode jtag -spd 2 -cable 0" in 10.533266s wall

+ 7 - 0
tests/fixtures/prod2u_programmer/gui_success_excerpt.log

@@ -0,0 +1,7 @@
+RUN-1002 : start command "download -bit C:/P2U/A1B2C3D4/fw.bit -mode jtag -spd 2 -cable 0"
+PRG-2014 : Chip validation success: EF2L45
+RUN-1002 : start command "bit_to_vec -chip EF2L45 -m jtag_burst -freq 0.200000 -bit C:/P2U/A1B2C3D4/fw.bit"
+RUN-1003 : finish command "bit_to_vec -chip EF2L45 -m jtag_burst -freq 0.200000 -bit C:/P2U/A1B2C3D4/fw.bit" in 0.050000s wall
+RUN-1002 : start command "program -cable 0 -mode svf -spd 2 -p"
+RUN-1003 : finish command "program -cable 0 -mode svf -spd 2 -p" in 10.450000s wall
+RUN-1003 : finish command "download -bit C:/P2U/A1B2C3D4/fw.bit -mode jtag -spd 2 -cable 0" in 10.550000s wall

+ 5 - 0
tests/fixtures/prod2u_programmer/missing_bit_to_vec.log

@@ -0,0 +1,5 @@
+RUN-1002 : start command "download -bit C:/P2U/A1B2C3D4/fw.bit -mode jtag -spd 2 -cable 0"
+PRG-2014 : Chip validation success: EF2L45
+RUN-1002 : start command "program -cable 0 -mode svf -spd 2 -p"
+RUN-1003 : finish command "program -cable 0 -mode svf -spd 2 -p" in 10.450000s wall
+RUN-1003 : finish command "download -bit C:/P2U/A1B2C3D4/fw.bit -mode jtag -spd 2 -cable 0" in 10.550000s wall

+ 99 - 33
tests/sim/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top_tb.v

@@ -1,8 +1,7 @@
 `timescale 1ns/1ps
 
-module uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top_tb;
+module prod2u_bmc_replay_binary921_top_tb;
     reg clk;
-    reg rst_n;
     reg bmc_uart_rx;
     wire bmc_uart_tx;
     reg host_uart_rx;
@@ -17,8 +16,15 @@ module uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_bin
     integer timeout;
     integer high_count;
     integer low_count;
+    integer ready_count;
+    integer command_index;
+    integer ack_count;
+    integer host_cmd_count;
 
-    uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top #(
+    prod2u_bmc_replay_binary921_top #(
+        .POR_CYCLES(4),
+        .READY_REPEAT_COUNT(3),
+        .BUILD_ID(32'hA1B2C3D4),
         .BMC_UART_CLKS_PER_BIT(8),
         .HOST_UART_CLKS_PER_BIT(4),
         .DEBUG_UART_CLKS_PER_BIT(4),
@@ -31,7 +37,6 @@ module uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_bin
         .SNAPSHOT_PERIOD_TICKS(100000)
     ) dut (
         .sys_clk(clk),
-        .sys_rst_n(rst_n),
         .bmc_uart_rx(bmc_uart_rx),
         .bmc_uart_tx(bmc_uart_tx),
         .host_uart_rx(host_uart_rx),
@@ -126,6 +131,10 @@ module uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_bin
         output [7:0] payload_len;
         integer byte_index;
         integer payload_limit;
+        reg [15:0] frame_crc;
+        reg [7:0] discarded_payload_byte;
+        reg [7:0] actual_crc_low;
+        reg [7:0] actual_crc_high;
         begin
             frame_bytes[0] = 8'd0;
             frame_bytes[1] = 8'd0;
@@ -134,8 +143,10 @@ module uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_bin
                 capture_uart_byte_host(frame_bytes[1]);
             end
             frame_bytes[0] = 8'ha5;
+            frame_crc = 16'hffff;
             for (byte_index = 2; byte_index < 14; byte_index = byte_index + 1) begin
                 capture_uart_byte_host(frame_bytes[byte_index]);
+                frame_crc = crc16_update(frame_crc, frame_bytes[byte_index]);
             end
             profile_id = frame_bytes[3];
             frame_type = frame_bytes[4];
@@ -146,16 +157,27 @@ module uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_bin
             end
             for (byte_index = 0; byte_index < payload_limit; byte_index = byte_index + 1) begin
                 capture_uart_byte_host(frame_bytes[14 + byte_index]);
+                frame_crc = crc16_update(frame_crc, frame_bytes[14 + byte_index]);
             end
             for (byte_index = payload_limit; byte_index < payload_len; byte_index = byte_index + 1) begin
-                capture_uart_byte_host(frame_bytes[62]);
+                capture_uart_byte_host(discarded_payload_byte);
+                frame_crc = crc16_update(frame_crc, discarded_payload_byte);
+            end
+            capture_uart_byte_host(actual_crc_low);
+            capture_uart_byte_host(actual_crc_high);
+            if (actual_crc_low !== frame_crc[7:0] || actual_crc_high !== frame_crc[15:8]) begin
+                $display("combined binary921 CRC mismatch expected=%04x actual=%02x%02x type=%02x seq=%02x%02x%02x%02x",
+                         frame_crc, actual_crc_high, actual_crc_low, frame_bytes[4],
+                         frame_bytes[8], frame_bytes[7], frame_bytes[6], frame_bytes[5]);
+                $fatal;
             end
-            capture_uart_byte_host(frame_bytes[62]);
-            capture_uart_byte_host(frame_bytes[63]);
         end
     endtask
 
-    task send_set_ptc01_10_profile3;
+    task send_set_ptc_profile3;
+        input [31:0] seq;
+        input [7:0] channel;
+        input [7:0] percent;
         reg [15:0] crc;
         begin
             crc = 16'hffff;
@@ -164,49 +186,93 @@ module uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_bin
             drive_uart_byte_host(8'h01); crc = crc16_update(crc, 8'h01);
             drive_uart_byte_host(8'h03); crc = crc16_update(crc, 8'h03);
             drive_uart_byte_host(8'h05); crc = crc16_update(crc, 8'h05);
-            drive_uart_byte_host(8'h01); crc = crc16_update(crc, 8'h01);
-            drive_uart_byte_host(8'h00); crc = crc16_update(crc, 8'h00);
-            drive_uart_byte_host(8'h00); crc = crc16_update(crc, 8'h00);
-            drive_uart_byte_host(8'h00); crc = crc16_update(crc, 8'h00);
+            drive_uart_byte_host(seq[7:0]); crc = crc16_update(crc, seq[7:0]);
+            drive_uart_byte_host(seq[15:8]); crc = crc16_update(crc, seq[15:8]);
+            drive_uart_byte_host(seq[23:16]); crc = crc16_update(crc, seq[23:16]);
+            drive_uart_byte_host(seq[31:24]); crc = crc16_update(crc, seq[31:24]);
             drive_uart_byte_host(8'h00); crc = crc16_update(crc, 8'h00);
             drive_uart_byte_host(8'h00); crc = crc16_update(crc, 8'h00);
             drive_uart_byte_host(8'h00); crc = crc16_update(crc, 8'h00);
             drive_uart_byte_host(8'h00); crc = crc16_update(crc, 8'h00);
             drive_uart_byte_host(8'h03); crc = crc16_update(crc, 8'h03);
             drive_uart_byte_host(8'h20); crc = crc16_update(crc, 8'h20);
-            drive_uart_byte_host(8'h01); crc = crc16_update(crc, 8'h01);
-            drive_uart_byte_host(8'h0a); crc = crc16_update(crc, 8'h0a);
+            drive_uart_byte_host(channel); crc = crc16_update(crc, channel);
+            drive_uart_byte_host(percent); crc = crc16_update(crc, percent);
             drive_uart_byte_host(crc[7:0]);
             drive_uart_byte_host(crc[15:8]);
         end
     endtask
 
+    task capture_and_count_command_frame;
+        input [7:0] expected_channel;
+        input [7:0] expected_percent;
+        begin
+            capture_combined_binary_frame(frame_bytes[60], frame_bytes[61], frame_bytes[62]);
+            if (frame_bytes[60] !== 8'd3) begin
+                $display("production command response profile mismatch profile=%02x type=%02x", frame_bytes[60], frame_bytes[61]);
+                $fatal;
+            end
+            if (frame_bytes[61] == 8'h06) begin
+                ack_count = ack_count + 1;
+                if (frame_bytes[62] !== 8'd6 || frame_bytes[14] !== 8'h01 ||
+                    frame_bytes[15] !== 8'h20 || frame_bytes[16] !== 8'h00) begin
+                    $display("production HOST_ACK mismatch len=%02x ok=%02x cmd=%02x status=%02x",
+                             frame_bytes[62], frame_bytes[14], frame_bytes[15], frame_bytes[16]);
+                    $fatal;
+                end
+            end else if (frame_bytes[61] == 8'h05) begin
+                host_cmd_count = host_cmd_count + 1;
+                if (frame_bytes[62] !== 8'd3 || frame_bytes[14] !== 8'h20 ||
+                    frame_bytes[15] !== expected_channel || frame_bytes[16] !== expected_percent) begin
+                    $display("production HOST_CMD event mismatch len=%02x cmd=%02x ch=%02x pct=%02x expected_ch=%02x expected_pct=%02x",
+                             frame_bytes[62], frame_bytes[14], frame_bytes[15], frame_bytes[16],
+                             expected_channel, expected_percent);
+                    $fatal;
+                end
+            end else begin
+                $display("unexpected production command response type=%02x", frame_bytes[61]);
+                $fatal;
+            end
+        end
+    endtask
+
     initial begin
-        rst_n = 1'b0;
         bmc_uart_rx = 1'b1;
         host_uart_rx = 1'b1;
         fan_fg_in = 8'h00;
         fan_install_in = 4'hf;
-        repeat (5) @(posedge clk);
-        rst_n = 1'b1;
 
-        capture_combined_binary_frame(frame_bytes[60], frame_bytes[61], frame_bytes[62]);
-        if (frame_bytes[60] !== 8'd3 || frame_bytes[61] !== 8'h01 ||
-            frame_bytes[62] !== 8'd4 || frame_bytes[14] !== 8'd3) begin
-            $display("production READY frame mismatch profile=%02x type=%02x len=%02x payload0=%02x",
-                     frame_bytes[60], frame_bytes[61], frame_bytes[62], frame_bytes[14]);
-            $fatal;
+        for (ready_count = 0; ready_count < 3; ready_count = ready_count + 1) begin
+            capture_combined_binary_frame(frame_bytes[60], frame_bytes[61], frame_bytes[62]);
+            if (frame_bytes[60] !== 8'd3 || frame_bytes[61] !== 8'h01 ||
+                frame_bytes[62] !== 8'd7 || frame_bytes[14] !== 8'h03 ||
+                frame_bytes[15] !== 8'hD4 || frame_bytes[16] !== 8'hC3 ||
+                frame_bytes[17] !== 8'hB2 || frame_bytes[18] !== 8'hA1 ||
+                frame_bytes[19] !== 8'h01 || frame_bytes[20] !== ready_count[7:0] ||
+                frame_bytes[5] !== 8'h01 || frame_bytes[6] !== 8'h00 ||
+                frame_bytes[7] !== 8'h00 || frame_bytes[8] !== 8'h00 ||
+                frame_bytes[9] !== 8'h04 || frame_bytes[10] !== 8'h00 ||
+                frame_bytes[11] !== 8'h00 || frame_bytes[12] !== 8'h00) begin
+                $display("production READY metadata mismatch profile=%02x type=%02x len=%02x payload=%02x%02x%02x%02x%02x%02x%02x seq=%02x%02x%02x%02x tick=%02x%02x%02x%02x",
+                         frame_bytes[60], frame_bytes[61], frame_bytes[62],
+                         frame_bytes[20], frame_bytes[19], frame_bytes[18], frame_bytes[17], frame_bytes[16], frame_bytes[15], frame_bytes[14],
+                         frame_bytes[8], frame_bytes[7], frame_bytes[6], frame_bytes[5],
+                         frame_bytes[12], frame_bytes[11], frame_bytes[10], frame_bytes[9]);
+                $fatal;
+            end
         end
 
-        send_set_ptc01_10_profile3();
-
-        capture_combined_binary_frame(frame_bytes[60], frame_bytes[61], frame_bytes[62]);
-        if (frame_bytes[60] !== 8'd3 || frame_bytes[61] !== 8'h06 ||
-            frame_bytes[14] !== 8'h01 || frame_bytes[15] !== 8'h20 ||
-            frame_bytes[16] !== 8'h00) begin
-            $display("production combined HOST_ACK mismatch profile=%02x type=%02x ok=%02x cmd=%02x status=%02x",
-                     frame_bytes[60], frame_bytes[61], frame_bytes[14], frame_bytes[15], frame_bytes[16]);
-            $fatal;
+        for (command_index = 0; command_index < 12; command_index = command_index + 1) begin
+            send_set_ptc_profile3(command_index + 1, command_index + 1, command_index + 10);
+            ack_count = 0;
+            host_cmd_count = 0;
+            capture_and_count_command_frame(command_index + 1, command_index + 10);
+            capture_and_count_command_frame(command_index + 1, command_index + 10);
+            if (ack_count !== 1 || host_cmd_count !== 1) begin
+                $display("command %0d response multiplicity mismatch HOST_ACK=%0d HOST_CMD=%0d",
+                         command_index + 1, ack_count, host_cmd_count);
+                $fatal;
+            end
         end
 
         high_count = 0;
@@ -224,7 +290,7 @@ module uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_bin
             $fatal;
         end
 
-        $display("PASS: uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top_tb");
+        $display("PASS: prod2u_bmc_replay_binary921_top_tb");
         $finish;
     end
 endmodule

+ 61 - 0
tests/sim/prod2u_por_tb.v

@@ -0,0 +1,61 @@
+`timescale 1ns/1ps
+
+module prod2u_por_tb;
+    reg sys_clk;
+    wire sys_rst_n;
+    integer cycle_count;
+
+    prod2u_por #(
+        .POR_CYCLES(1024)
+    ) dut (
+        .sys_clk(sys_clk),
+        .sys_rst_n(sys_rst_n)
+    );
+
+    initial begin
+        sys_clk = 1'b0;
+        forever #20 sys_clk = ~sys_clk;
+    end
+
+    always @(sys_rst_n) begin
+        if (sys_rst_n === 1'b1 && ($time % 40) !== 20) begin
+            $display("POR release was not synchronous time=%0t", $time);
+            $fatal;
+        end
+    end
+
+    initial begin
+        cycle_count = 0;
+        if (sys_rst_n !== 1'b0) begin
+            $display("POR did not initialize asserted");
+            $fatal;
+        end
+
+        repeat (1023) begin
+            @(posedge sys_clk);
+            #1;
+            cycle_count = cycle_count + 1;
+            if (sys_rst_n !== 1'b0) begin
+                $display("POR released early at cycle=%0d", cycle_count);
+                $fatal;
+            end
+        end
+
+        @(posedge sys_clk);
+        #1;
+        cycle_count = cycle_count + 1;
+        if (cycle_count !== 1024 || sys_rst_n !== 1'b1) begin
+            $display("POR release mismatch cycles=%0d rst_n=%b", cycle_count, sys_rst_n);
+            $fatal;
+        end
+
+        @(negedge sys_clk);
+        if (sys_rst_n !== 1'b1) begin
+            $display("POR release did not remain asserted after synchronous release");
+            $fatal;
+        end
+
+        $display("PASS: prod2u_por_tb");
+        $finish;
+    end
+endmodule

+ 89 - 0
tests/test_project_structure.py

@@ -62,24 +62,45 @@ class ProjectStructureTests(unittest.TestCase):
             "src/top/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921_top.v",
             "src/top/uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_debug921_top.v",
             "src/top/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_debug921_top.v",
+            "src/top/uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921_top.v",
+            "src/top/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_binary921_top.v",
+            "src/top/prod2u_bmc_replay_binary921_top.v",
+            "src/rtl/binary921_crc16.v",
+            "src/rtl/binary921_frame_tx.v",
+            "src/rtl/binary921_host_rx.v",
+            "src/rtl/binary921_diag_core.v",
             "tests/sim/uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top_tb.v",
+            "tests/sim/uart_rs232_j6_host_sensor_real_fan_ptc_binary921_top_tb.v",
             "constraints/uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921.adc",
             "constraints/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921.adc",
             "constraints/uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_debug921.adc",
             "constraints/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_debug921.adc",
+            "constraints/uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921.adc",
+            "constraints/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_binary921.adc",
+            "constraints/prod2u_bmc_replay_binary921.adc",
             "td/uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921.prj",
             "td/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921.prj",
             "td/uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_debug921.prj",
             "td/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_debug921.prj",
+            "td/uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921.prj",
+            "td/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_binary921.prj",
+            "td/prod2u_bmc_replay_binary921.prj",
             "td/syn/uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921.tcl",
             "td/syn/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921.tcl",
             "td/syn/uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_debug921.tcl",
             "td/syn/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_debug921.tcl",
+            "td/syn/uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921.tcl",
+            "td/syn/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_binary921.tcl",
+            "td/syn/prod2u_bmc_replay_binary921.tcl",
             "td/phy/uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921.tcl",
             "td/phy/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921.tcl",
             "td/phy/uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_debug921.tcl",
             "td/phy/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_debug921.tcl",
+            "td/phy/uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921.tcl",
+            "td/phy/uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_binary921.tcl",
+            "td/phy/prod2u_bmc_replay_binary921.tcl",
             "tools/pid_harness.py",
+            "tools/binary921.py",
             "tools/bmc_replay_uart.py",
             "tools/uart_receipts.py",
             "tools/pin_inventory.py",
@@ -204,6 +225,74 @@ class ProjectStructureTests(unittest.TestCase):
                 self.assertIn(f"analyze -file {{src/top/{stem}_top.v}}", syn_text)
                 self.assertIn(f"elaborate -top {{{stem}_top}}", syn_text)
 
+    def test_binary921_profiles_use_binary_diag_core_not_ascii_debug921_top(self) -> None:
+        profiles = {
+            "uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921": 0,
+            "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_binary921": 1,
+        }
+        for stem, pin_profile in profiles.items():
+            with self.subTest(stem=stem):
+                wrapper_path = ROOT / "src" / "top" / f"{stem}_top.v"
+                wrapper = wrapper_path.read_text(encoding="utf-8", errors="replace")
+                self.assertIn(f"module {stem}_top", wrapper)
+                self.assertIn("binary921_diag_core #(", wrapper)
+                self.assertIn(f".PIN_PROFILE({pin_profile})", wrapper)
+                self.assertNotIn("uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top #(", wrapper)
+
+                prj_text = (ROOT / "td" / f"{stem}.prj").read_text(encoding="utf-8")
+                self.assertIn("../src/rtl/binary921_diag_core.v", prj_text)
+                self.assertIn(f"../src/top/{stem}_top.v", prj_text)
+                self.assertIn(f"<MODULE>{stem}_top</MODULE>", prj_text)
+
+                syn_text = (ROOT / "td" / "syn" / f"{stem}.tcl").read_text(encoding="utf-8")
+                self.assertIn("analyze -file {src/rtl/binary921_diag_core.v}", syn_text)
+                self.assertNotIn("analyze -file {src/top/uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top.v}", syn_text)
+                self.assertIn(f"elaborate -top {{{stem}_top}}", syn_text)
+
+    def test_production_two_uart_binary921_top_uses_combined_uart_and_real_pin_constraints(self) -> None:
+        stem = "prod2u_bmc_replay_binary921"
+        wrapper_path = ROOT / "src" / "top" / f"{stem}_top.v"
+        constraint_path = ROOT / "constraints" / f"{stem}.adc"
+
+        wrapper = wrapper_path.read_text(encoding="utf-8", errors="replace")
+        self.assertIn(f"module {stem}_top", wrapper)
+        self.assertIn("binary921_diag_core #(", wrapper)
+        self.assertIn(".COMBINED_HOST_DEBUG_UART(1)", wrapper)
+        self.assertIn(".PIN_PROFILE(2)", wrapper)
+        self.assertIn(".HOST_UART_CLKS_PER_BIT(HOST_UART_CLKS_PER_BIT)", wrapper)
+        self.assertNotIn("debug_uart_rx", wrapper.split(");", 1)[0])
+        self.assertNotIn("debug_uart_tx", wrapper.split(");", 1)[0])
+
+        constraints = constraint_path.read_text(encoding="utf-8", errors="replace")
+        self.assertIn("{ bmc_uart_tx } { LOCATION = L10", constraints)
+        self.assertIn("{ bmc_uart_rx } { LOCATION = M9", constraints)
+        self.assertIn("{ host_uart_tx } { LOCATION = M10", constraints)
+        self.assertIn("{ host_uart_rx } { LOCATION = N11", constraints)
+        self.assertNotIn("debug_uart", constraints)
+        self.assertIn("{ ptc_pwm_out[2] } { LOCATION = T4", constraints)
+        self.assertIn("{ fan_pwm_out[0] } { LOCATION = C4", constraints)
+
+        prj_text = (ROOT / "td" / f"{stem}.prj").read_text(encoding="utf-8")
+        self.assertIn("../src/rtl/binary921_diag_core.v", prj_text)
+        self.assertIn(f"../src/top/{stem}_top.v", prj_text)
+        self.assertIn(f"<MODULE>{stem}_top</MODULE>", prj_text)
+
+        syn_text = (ROOT / "td" / "syn" / f"{stem}.tcl").read_text(encoding="utf-8")
+        self.assertIn("analyze -file {src/rtl/binary921_diag_core.v}", syn_text)
+        self.assertIn(f"elaborate -top {{{stem}_top}}", syn_text)
+        self.assertIn(f"read_adc {{constraints/{stem}.adc}}", syn_text)
+
+    def test_binary921_host_rx_crc_output_is_net_for_td_frontend(self) -> None:
+        for path in [
+            ROOT / "src" / "rtl" / "binary921_host_rx.v",
+            ROOT / "src" / "rtl" / "binary921_frame_tx.v",
+        ]:
+            with self.subTest(path=path.name):
+                source = path.read_text(encoding="utf-8", errors="replace")
+
+                self.assertIn("wire [15:0] crc_next;", source)
+                self.assertNotIn("reg [15:0] crc_next;", source)
+
 
 if __name__ == "__main__":
     unittest.main()

+ 56 - 2
tests/unit/test_binary921_protocol.py

@@ -123,6 +123,41 @@ class Binary921ProtocolTests(unittest.TestCase):
         with self.assertRaisesRegex(ValueError, "percent"):
             build_host_command(seq=5, command=CommandId.SET_PTC, channel=1, percent=101)
 
+    def test_pid_request_decodes_enabled_flag_without_channel_or_percent_aliases(self) -> None:
+        command = decode_frame(
+            build_host_command(
+                seq=5,
+                command=CommandId.SET_PID_REQUESTED,
+                percent=1,
+                profile_id=3,
+            )
+        )
+
+        decoded = frame_to_dict(command)["decoded"]
+
+        self.assertEqual(
+            decoded,
+            {
+                "kind": "host_cmd",
+                "cmd": "SET_PID_REQUESTED",
+                "cmd_id": int(CommandId.SET_PID_REQUESTED),
+                "enabled": True,
+            },
+        )
+        with self.assertRaisesRegex(ValueError, "0/1"):
+            build_host_command(seq=6, command=CommandId.SET_PID_REQUESTED, percent=2)
+
+        invalid = decode_frame(
+            encode_frame(
+                profile_id=3,
+                frame_type=FrameType.HOST_CMD,
+                seq=6,
+                timestamp_tick=0,
+                payload=bytes([CommandId.SET_PID_REQUESTED, 2]),
+            )
+        )
+        self.assertEqual(frame_to_dict(invalid)["decoded"]["error"], "invalid_enabled_flag")
+
     def test_zero_payload_commands_have_stable_binary_payloads(self) -> None:
         for command in [
             CommandId.GET_SENSOR,
@@ -136,7 +171,13 @@ class Binary921ProtocolTests(unittest.TestCase):
 
     def test_frame_to_dict_decodes_ready_host_command_and_ack_payloads(self) -> None:
         ready = decode_frame(
-            encode_frame(profile_id=1, frame_type=FrameType.READY, seq=1, timestamp_tick=2, payload=bytes([1, 0, 0, 0]))
+            encode_frame(
+                profile_id=1,
+                frame_type=FrameType.READY,
+                seq=1,
+                timestamp_tick=2,
+                payload=bytes([1]) + (0x1234ABCD).to_bytes(4, "little") + bytes([1, 2]),
+            )
         )
         command = decode_frame(build_host_command(seq=9, command=CommandId.SET_PTC, channel=1, percent=10))
         ack = decode_frame(
@@ -149,7 +190,18 @@ class Binary921ProtocolTests(unittest.TestCase):
             )
         )
 
-        self.assertEqual(frame_to_dict(ready)["decoded"], {"kind": "ready", "profile_id_payload": 1})
+        self.assertEqual(
+            frame_to_dict(ready)["decoded"],
+            {
+                "kind": "ready",
+                "profile_id_payload": 1,
+                "build_id": "1234ABCD",
+                "startup_epoch": 1,
+                "startup_tick": 2,
+                "por_reason": 1,
+                "announcement_seq": 2,
+            },
+        )
         self.assertEqual(
             frame_to_dict(command)["decoded"],
             {"kind": "host_cmd", "cmd": "SET_PTC", "cmd_id": 32, "channel": 1, "percent": 10},
@@ -168,8 +220,10 @@ class Binary921ProtocolTests(unittest.TestCase):
 
     def test_production_two_uart_profile_has_stable_id_three(self) -> None:
         profile = "production-two-uart-bmc-replay-binary921"
+        alias = "prod2u-bmc-replay-binary921"
 
         self.assertEqual(profile_id_for_name(profile), 3)
+        self.assertEqual(profile_id_for_name(alias), 3)
         self.assertEqual(profile_name_for_id(3), profile)
 
         frame = decode_frame(

+ 70 - 0
tests/unit/test_collect_j6_binary921.py

@@ -0,0 +1,70 @@
+#!/usr/bin/env python3
+"""Public compatibility tests for the legacy J6 binary921 entrypoint."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+import unittest
+from pathlib import Path
+from unittest import mock
+
+
+ROOT = Path(__file__).resolve().parents[2]
+TOOLS = ROOT / "tools"
+REMOTE = TOOLS / "remote"
+sys.dont_write_bytecode = True
+sys.path.insert(0, str(TOOLS))
+sys.path.insert(0, str(REMOTE))
+
+import collect_j6_binary921 as legacy_collector  # noqa: E402
+import prod2u_collector  # noqa: E402
+
+
+class LegacyBinary921CollectorCompatibilityTests(unittest.TestCase):
+    def test_reexports_prod2u_public_collector_api(self) -> None:
+        public_names = (
+            "COMMAND_SEQUENCE",
+            "SerialWriteError",
+            "build_manifest_from_frames",
+            "collect_live",
+            "collector_manifest_name",
+            "collector_schema_for_profile",
+            "is_combined_uart_profile",
+            "run_selftest",
+            "wait_for_ready",
+            "write_blocked_manifest",
+        )
+
+        for name in public_names:
+            with self.subTest(name=name):
+                self.assertIs(getattr(legacy_collector, name), getattr(prod2u_collector, name))
+
+    def test_main_delegates_argv_to_prod2u_collector(self) -> None:
+        with mock.patch.object(prod2u_collector, "main", return_value=17) as prod2u_main:
+            result = legacy_collector.main(["--selftest"])
+
+        self.assertEqual(result, 17)
+        prod2u_main.assert_called_once_with(["--selftest"])
+
+    def test_legacy_script_selftest_emits_prod2u_contract(self) -> None:
+        result = subprocess.run(
+            [sys.executable, str(REMOTE / "collect_j6_binary921.py"), "--selftest", "--json"],
+            cwd=ROOT,
+            text=True,
+            capture_output=True,
+            check=False,
+        )
+
+        self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
+        payload_text, marker = result.stdout.rsplit("\nselftest=pass", maxsplit=1)
+        self.assertEqual(marker.strip(), "")
+        payload = json.loads(payload_text)
+        self.assertEqual(payload["schema"], "prod2u-collector-selftest-v1")
+        self.assertEqual(payload["status"], "pass")
+        self.assertEqual(payload["profile"], "prod2u-bmc-replay-binary921")
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 183 - 3
tests/unit/test_pid_harness.py

@@ -23,11 +23,13 @@ from pid_harness import (  # noqa: E402
     clean_runtime_payload,
     contract_coverage_matrix_payload,
     contract_replay_payload,
+    cmd_uart_validate,
     offline_fidelity_gate_v1_payload,
     offline_toolchain_bootstrap_payload,
     formal_payload,
     hdl_testbenches,
     hdl_sim_payload,
+    VERILATOR_LINT_WAIVERS,
     mutation_payload,
     parse_area_report,
     parse_td_version,
@@ -258,6 +260,17 @@ Clock Summary
         self.assertEqual(payload["status"], "blocked_missing_tool")
         self.assertEqual(payload["missing_tools"], ["iverilog", "vvp"])
 
+    def test_verilator_lint_supplies_only_a_test_stub_for_the_zero_build_id_guard(self) -> None:
+        payload = hdl_sim_payload(run=False, backend="verilator")
+        sources = payload["tests"][0]["sources"]
+        stub_rel = "tests/verilator_prod2u_build_id_guard_stub.v"
+
+        self.assertIn(stub_rel, sources)
+        stub = (ROOT / stub_rel).read_text(encoding="ascii")
+        self.assertIn("module prod2u_build_id_must_be_nonzero", stub)
+        self.assertNotIn(stub_rel, (ROOT / "td" / "prod2u_bmc_replay_binary921.prj").read_text(encoding="utf-8"))
+        self.assertIn("PINCONNECTEMPTY", VERILATOR_LINT_WAIVERS)
+
     def test_formal_reports_missing_tools_as_blocked(self) -> None:
         with self.missing_toolchain_context():
             payload = formal_payload(run=True)
@@ -270,6 +283,9 @@ Clock Summary
             "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921",
             "uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_debug921",
             "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_debug921",
+            "uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921",
+            "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_binary921",
+            "prod2u_bmc_replay_binary921",
         ]:
             with self.subTest(top=top):
                 payload = td_build_payload(run=False, top=top)
@@ -283,9 +299,22 @@ Clock Summary
         formal_top = "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921"
         debug_replay_top = "uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_debug921"
         formal_replay_top = "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_debug921"
+        debug_binary_top = "uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921"
+        formal_binary_top = "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_binary921"
+        production_binary_top = "prod2u_bmc_replay_binary921"
         self.assertEqual(
             set(TD_TOP_PROFILES),
-            {"system_contract", "debug_max", temp_top, formal_top, debug_replay_top, formal_replay_top},
+            {
+                "system_contract",
+                "debug_max",
+                temp_top,
+                formal_top,
+                debug_replay_top,
+                formal_replay_top,
+                debug_binary_top,
+                formal_binary_top,
+                production_binary_top,
+            },
         )
 
         profile = TD_TOP_PROFILES[temp_top]
@@ -334,12 +363,77 @@ Clock Summary
         self.assertIn("SPARE_GPIO44/45", formal_replay["authority_boundary"])
         self.assertIn("UART1/2", formal_replay["authority_boundary"])
 
+        debug_binary = TD_TOP_PROFILES[debug_binary_top]
+        self.assertEqual(debug_binary["pin_profile"], "debug-photo-bmc-replay-binary921")
+        self.assertEqual(debug_binary["protocol"], "binary921")
+        self.assertEqual(debug_binary["bmc_source"], "pc_replay_from_real_bmc_capture")
+        self.assertEqual(debug_binary["tx_ball"], "T4")
+        self.assertEqual(debug_binary["rx_ball"], "R5")
+        self.assertEqual(debug_binary["host_uart_tx_ball"], "P7")
+        self.assertEqual(debug_binary["host_uart_rx_ball"], "P8")
+        self.assertEqual(debug_binary["debug_uart_rx_ball"], "P10")
+        self.assertEqual(debug_binary["debug_uart_tx_ball"], "R10")
+        self.assertIn("binary921", debug_binary["authority_boundary"])
+
+        formal_binary = TD_TOP_PROFILES[formal_binary_top]
+        self.assertEqual(formal_binary["pin_profile"], "formal-uart1-bmc-replay-binary921")
+        self.assertEqual(formal_binary["protocol"], "binary921")
+        self.assertEqual(formal_binary["bmc_source"], "pc_replay_from_real_bmc_capture")
+        self.assertEqual(formal_binary["tx_ball"], "L10")
+        self.assertEqual(formal_binary["rx_ball"], "M9")
+        self.assertEqual(formal_binary["host_uart_tx_ball"], "M10")
+        self.assertEqual(formal_binary["host_uart_rx_ball"], "N11")
+        self.assertEqual(formal_binary["debug_uart_rx_ball"], "M14")
+        self.assertEqual(formal_binary["debug_uart_tx_ball"], "M15")
+        self.assertIn("real HEAT/FAN", formal_binary["authority_boundary"])
+
+    def test_production_two_uart_binary921_td_profile_is_registered(self) -> None:
+        top = "prod2u_bmc_replay_binary921"
+        self.assertIn(top, TD_TOP_PROFILES)
+
+        profile = TD_TOP_PROFILES[top]
+        self.assertEqual(profile["mode"], "implementation")
+        self.assertEqual(profile["top_module"], f"{top}_top")
+        self.assertEqual(profile["pin_profile"], "prod2u-bmc-replay-binary921")
+        self.assertEqual(profile["protocol"], "binary921")
+        self.assertEqual(profile["transport"], "combined_host_debug_uart")
+        self.assertEqual(profile["bmc_source"], "pc_replay_from_real_bmc_capture")
+        self.assertEqual(profile["tx_ball"], "L10")
+        self.assertEqual(profile["rx_ball"], "M9")
+        self.assertEqual(profile["host_uart_tx_ball"], "M10")
+        self.assertEqual(profile["host_uart_rx_ball"], "N11")
+        self.assertEqual(profile["host_uart_baud"], 921600)
+        self.assertEqual(profile["bmc_uart_baud"], 115200)
+        self.assertEqual(profile["debug_uart_baud"], 921600)
+        self.assertNotIn("debug_uart_rx_ball", profile)
+        payload = td_build_payload(run=False, top=top)
+        self.assertEqual(payload["status"], "skipped")
+        self.assertEqual(payload["top_module"], f"{top}_top")
+
+    def test_production_two_uart_combined_top_has_hdl_testbench(self) -> None:
+        tests_by_name = {item["name"]: item for item in hdl_testbenches()}
+        name = "prod2u_bmc_replay_binary921_top_tb"
+
+        self.assertIn(name, tests_by_name)
+        sources = tests_by_name[name]["sources"]
+        self.assertIn(
+            "src/top/prod2u_bmc_replay_binary921_top.v",
+            sources,
+        )
+        self.assertIn(
+            "tests/sim/prod2u_bmc_replay_binary921_top_tb.v",
+            sources,
+        )
+
     def test_latest_td_project_and_scripts_are_build_only(self) -> None:
         stems = [
             "uart_rs232_j6_host_sensor_real_fan_ptc_temp_uart_ptc_remap_debug921",
             "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart_debug921",
             "uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_debug921",
             "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_debug921",
+            "uart_rs232_j6_host_sensor_real_fan_ptc_debug_photo_uart_bmc_replay_binary921",
+            "uart_rs232_j6_host_sensor_real_fan_ptc_formal_uart1_bmc_replay_binary921",
+            "prod2u_bmc_replay_binary921",
         ]
         for stem in stems:
             with self.subTest(stem=stem):
@@ -349,7 +443,13 @@ Clock Summary
                 self.assertIn("../src/rtl/uart_tx_8n1.v", prj_text)
                 self.assertIn("../src/rtl/uart_rx_8n1.v", prj_text)
                 self.assertIn("../src/rtl/bmc_uart_raw48_poll_lite.v", prj_text)
-                self.assertIn("../src/top/uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top.v", prj_text)
+                if stem.endswith("_binary921"):
+                    self.assertIn("../src/rtl/binary921_diag_core.v", prj_text)
+                    self.assertIn("../src/rtl/binary921_frame_tx.v", prj_text)
+                    self.assertIn("../src/rtl/binary921_host_rx.v", prj_text)
+                    self.assertNotIn("../src/top/uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top.v", prj_text)
+                else:
+                    self.assertIn("../src/top/uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top.v", prj_text)
                 self.assertIn(f"../src/top/{stem}_top.v", prj_text)
                 self.assertIn(f"<MODULE>{top_module}</MODULE>", prj_text)
 
@@ -361,7 +461,11 @@ Clock Summary
                     markers = td_forbidden_script_markers(script_text)
                     self.assertEqual(markers, [], f"{stem}:{script_dir}:{markers}")
 
-                self.assertIn("uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top", combined)
+                if stem.endswith("_binary921"):
+                    self.assertIn("binary921", combined)
+                    self.assertNotIn("uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top", combined)
+                else:
+                    self.assertIn("uart_rs232_j6_host_sensor_real_fan_ptc_debug921_top", combined)
                 self.assertIn(top_module, combined)
                 self.assertIn(f"constraints/{stem}.adc", combined)
                 self.assertIn(f"{stem}.bit", combined)
@@ -476,6 +580,82 @@ connect_cable -open
         ]:
             self.assertNotIn(command, commands)
 
+    def test_uart_validate_accepts_changxin_temp_uart_receipt_schema(self) -> None:
+        payload = {
+            "schema": "changxin-temp-uart-publisher-receipt-v1",
+            "status": "pass",
+            "generated_at": "2026-07-07T00:00:00Z",
+            "workspace": {"python": sys.executable},
+            "tool_versions": {"python": "3.12"},
+            "config": {"toml_sha256": "a" * 64},
+            "bmc": {
+                "method": "serial_tty",
+                "device": "/dev/ttyUSB1",
+                "baudrate": 115200,
+                "raw_command": "0x36 0x6c 0xdf 0xdd 0x00 0x03",
+                "readonly_whitelist": ["0x36 0x6c 0xdf 0xdd 0x00 0x03"],
+                "raw_output_sha256": ["b" * 64],
+            },
+            "mapping": {
+                "source_groups": 24,
+                "destination_groups": 32,
+                "invalid_fill_groups": "25-32",
+                "table": [{"destination_group": index} for index in range(1, 33)],
+            },
+            "frame": {
+                "logical_length_bytes": 66,
+                "hashes": ["c" * 64],
+                "checksum": {
+                    "algorithm": "ones_complement_sum_first_49_bytes",
+                    "protected_length_bytes": 49,
+                    "results": [True],
+                    "protocol_risk": "document ambiguity recorded",
+                },
+            },
+            "serial": {
+                "virtual_serial": "pty_socat",
+                "pty_path": "/dev/pts/4",
+                "output_format": "ascii_hex_space_crlf",
+                "wire_transcript_sha256": "d" * 64,
+                "ascii_transcript_sha256": "d" * 64,
+                "consumer_transcript_sha256": "e" * 64,
+            },
+            "timing": {
+                "publish_interval": {"avg_sec": 0.5, "p95_sec": 0.51, "p99_sec": 0.52, "max_sec": 0.53},
+                "duplicate_frame_count": 1,
+                "sample_age_ms": {"count": 1, "max": 500, "values": [500]},
+            },
+            "errors": {"timeout": 0, "stale": 0, "parse_error": 0, "missing": 8},
+            "safety": {
+                "flash_attempted": False,
+                "programs_flash": False,
+                "programs_nonvolatile": False,
+                "driver_install_attempted": False,
+                "real_ptc_fan_action_attempted": False,
+                "uncontrolled_real_bmc_action_attempted": False,
+                "thermal_performance_claimed": False,
+                "cpld_bitstream_generated": False,
+                "program_sram_attempted": False,
+                "ipmi_lan_attempted": False,
+                "network_bmc_attempted": False,
+                "opens_unknown_serial_ports": False,
+                "toggles_dtr_rts": False,
+            },
+            "authority_boundary": "publisher evidence only; it does not prove thermal performance.",
+        }
+        with tempfile.TemporaryDirectory() as tmp:
+            receipt = Path(tmp) / "changxin.json"
+            report = Path(tmp) / "validation.json"
+            receipt.write_text(json.dumps(payload), encoding="utf-8")
+            parser = build_parser()
+            args = parser.parse_args(["uart-validate", "--receipt", str(receipt), "--strict", "--report-file", str(report)])
+
+            exit_code = cmd_uart_validate(args)
+
+            result = json.loads(report.read_text(encoding="utf-8"))
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(result["status"], "pass")
+
     def test_toolchain_clean_defaults_to_dry_run_and_requires_owner_marker(self) -> None:
         with tempfile.TemporaryDirectory() as tmp:
             root = Path(tmp) / "toolchain"

+ 17 - 0
tests/unit/test_pin_inventory.py

@@ -256,6 +256,17 @@ class PinInventoryTests(unittest.TestCase):
     def test_production_two_uart_binary921_profile_uses_uart1_uart2_combined_port_and_real_load_pins(self) -> None:
         inventory = load_pin_inventory(PRODUCT_INVENTORY)
         payload = diagnostic_profile_assignments(inventory, "production-two-uart-bmc-replay-binary921")
+        uart_pins = {row["signal"]: row for row in inventory["pins"] if row["signal"].startswith("UART")}
+
+        self.assertEqual(uart_pins["UART1_TX"]["direction"], "output")
+        self.assertEqual(uart_pins["UART1_TX"]["board_connector"], "CON77")
+        self.assertEqual(uart_pins["UART1_TX"]["connector_pin"], 1)
+        self.assertEqual(uart_pins["UART1_RX"]["connector_pin"], 2)
+        self.assertEqual(uart_pins["UART2_TX"]["board_connector"], "CON78")
+        self.assertEqual(uart_pins["UART2_TX"]["connector_pin"], 1)
+        self.assertEqual(uart_pins["UART2_RX"]["connector_pin"], 2)
+        self.assertEqual(uart_pins["UART2_RX"]["external_level"], "RS232")
+        self.assertEqual(uart_pins["UART2_RX"]["transceiver"], "U23 TRSF3232EIPWR")
 
         self.assertEqual(payload["status"], "pass")
         self.assertEqual(payload["profile"], "production-two-uart-bmc-replay-binary921")
@@ -280,6 +291,12 @@ class PinInventoryTests(unittest.TestCase):
         self.assertIn("J3", payload["authority_boundary"])
         self.assertIn("combined", payload["authority_boundary"])
 
+        active = diagnostic_profile_assignments(inventory, "prod2u-bmc-replay-binary921")
+        self.assertEqual(active["status"], "pass")
+        self.assertEqual(active["profile"], "prod2u-bmc-replay-binary921")
+        self.assertEqual(active["assignments"], payload["assignments"])
+        self.assertEqual(active["uart_assignments"], payload["uart_assignments"])
+
 
 if __name__ == "__main__":
     unittest.main()

+ 133 - 0
tests/unit/test_prod2u_bmc_replay.py

@@ -0,0 +1,133 @@
+#!/usr/bin/env python3
+"""Active Prod2U BMC replay naming and poll-response contract."""
+
+from __future__ import annotations
+
+import sys
+import json
+import tempfile
+import unittest
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "tools"))
+
+
+VALID_BMC_TEXT = """root@bmc:~# ipmitool raw 0x36 0x6c 0xdf 0xdd 0x00 0x03
+28 00 29 00 2a 00 2b 00 2c 00 2d 00 2e 00 2f 00
+30 00 31 00 32 00 33 00 34 00 35 00 36 00 37 00
+38 00 39 00 3a 00 3b 00 3c 00 3d 00 3e 00 3f 00
+"""
+
+
+class Prod2UBmcReplayTests(unittest.TestCase):
+    def test_replay_blocks_when_serial_write_returns_zero(self) -> None:
+        import prod2u_bmc_replay as replay
+
+        class ZeroWriteEndpoint(replay.FakeSerialEndpoint):
+            def write(self, data: bytes) -> int:
+                self.written += data
+                return 0
+
+        payload = replay.normalize_bmc_capture_text(VALID_BMC_TEXT, seq=1)
+        endpoint = ZeroWriteEndpoint(initial_rx=replay.POLL_COMMAND_TEXT.encode("ascii"))
+
+        receipt = replay.run_poll_response_session(endpoint, payload, iterations=1, timeout_sec=0.1)
+
+        self.assertEqual(receipt["status"], "blocked_serial_write_short")
+        self.assertEqual(receipt["matched_poll_count"], 0)
+        self.assertEqual(receipt["reply_count"], 0)
+
+    def test_replay_blocks_when_serial_write_is_partial(self) -> None:
+        import prod2u_bmc_replay as replay
+
+        class PartialWriteEndpoint(replay.FakeSerialEndpoint):
+            def write(self, data: bytes) -> int:
+                partial = data[:-1]
+                self.written += partial
+                return len(partial)
+
+        payload = replay.normalize_bmc_capture_text(VALID_BMC_TEXT, seq=1)
+        endpoint = PartialWriteEndpoint(initial_rx=replay.POLL_COMMAND_TEXT.encode("ascii"))
+
+        receipt = replay.run_poll_response_session(endpoint, payload, iterations=1, timeout_sec=0.1)
+
+        self.assertEqual(receipt["status"], "blocked_serial_write_short")
+        self.assertEqual(receipt["matched_poll_count"], 0)
+        self.assertEqual(receipt["reply_count"], 0)
+
+    def test_active_tool_generates_only_prod2u_schema_names(self) -> None:
+        import prod2u_bmc_replay as replay
+
+        payload = replay.normalize_bmc_capture_text(VALID_BMC_TEXT, seq=1)
+        endpoint = replay.FakeSerialEndpoint(initial_rx=replay.POLL_COMMAND_TEXT.encode("ascii"))
+        session = replay.run_poll_response_session(endpoint, payload, iterations=1, timeout_sec=0.1)
+
+        self.assertEqual(payload["schema"], "prod2u-bmc-replay-payload-v1")
+        self.assertEqual(session["schema"], "prod2u-bmc-replay-session-v1")
+        self.assertEqual(session["status"], "pass")
+        self.assertEqual(session["payload_hex"], payload["payload_hex"])
+        source = (ROOT / "tools" / "prod2u_bmc_replay.py").read_text(encoding="utf-8")
+        self.assertNotIn('"j6-bmc-replay-', source)
+
+    def test_replay_cli_writes_machine_readable_session_receipt(self) -> None:
+        import prod2u_bmc_replay as replay
+
+        payload = replay.normalize_bmc_capture_text(VALID_BMC_TEXT, seq=1)
+        with tempfile.TemporaryDirectory() as tmp:
+            payload_path = Path(tmp) / "payload.json"
+            receipt_path = Path(tmp) / "session.json"
+            payload_path.write_text(json.dumps(payload), encoding="utf-8")
+
+            result = replay.main(
+                [
+                    "replay",
+                    "--port",
+                    "COM9",
+                    "--payload",
+                    str(payload_path),
+                    "--iterations",
+                    "1",
+                    "--timeout-sec",
+                    "0.1",
+                    "--dry-run",
+                    "--receipt",
+                    str(receipt_path),
+                    "--json",
+                ]
+            )
+
+            self.assertEqual(result, 0)
+            receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
+            self.assertEqual(receipt["status"], "pass")
+            self.assertEqual(receipt["payload_hex"], payload["payload_hex"])
+
+    def test_load_payload_rejects_malformed_byte_count_even_with_valid_hash(self) -> None:
+        import prod2u_bmc_replay as replay
+
+        payload = replay.normalize_bmc_capture_text(VALID_BMC_TEXT, seq=1)
+        payload["byte_count"] = 47
+        with tempfile.TemporaryDirectory() as tmp:
+            payload_path = Path(tmp) / "payload.json"
+            payload_path.write_text(json.dumps(payload), encoding="utf-8")
+
+            with self.assertRaisesRegex(ValueError, "byte_count"):
+                replay._load_payload(payload_path)
+
+    def test_load_payload_rejects_stale_session_document_masquerading_as_payload(self) -> None:
+        import prod2u_bmc_replay as replay
+
+        stale_session = replay.normalize_bmc_capture_text(VALID_BMC_TEXT, seq=1)
+        stale_session["schema"] = "prod2u-bmc-replay-session-v1"
+        stale_session["session_id"] = "previous-session"
+        with tempfile.TemporaryDirectory() as tmp:
+            payload_path = Path(tmp) / "stale-session.json"
+            payload_path.write_text(json.dumps(stale_session), encoding="utf-8")
+
+            with self.assertRaisesRegex(ValueError, "schema"):
+                replay._load_payload(payload_path)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 158 - 0
tests/unit/test_prod2u_build_identity.py

@@ -0,0 +1,158 @@
+#!/usr/bin/env python3
+"""Tests for deterministic Prod2U source/build identity generation."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+MODULE_PATH = ROOT / "tools" / "prod2u_build_identity.py"
+
+
+def load_module():
+    if not MODULE_PATH.is_file():
+        raise AssertionError(f"missing build identity generator: {MODULE_PATH}")
+    spec = importlib.util.spec_from_file_location("prod2u_build_identity", MODULE_PATH)
+    if spec is None or spec.loader is None:
+        raise AssertionError("unable to load build identity generator")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+class Prod2UBuildIdentityTests(unittest.TestCase):
+    def test_manifest_is_stable_sorted_and_changes_with_any_input(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            (root / "b.v").write_text("module b; endmodule\n", encoding="ascii")
+            (root / "a.v").write_text("module a; endmodule\n", encoding="ascii")
+
+            first = module.build_source_manifest(
+                root=root,
+                inputs=[root / "b.v", root / "a.v"],
+                profile="prod2u-bmc-replay-binary921",
+                td_version="6.2.2.198412",
+            )
+            second = module.build_source_manifest(
+                root=root,
+                inputs=[root / "a.v", root / "b.v"],
+                profile="prod2u-bmc-replay-binary921",
+                td_version="6.2.2.198412",
+            )
+
+            self.assertEqual(first, second)
+            self.assertEqual([row["path"] for row in first["files"]], ["a.v", "b.v"])
+            self.assertRegex(first["source_manifest_sha256"], r"^[0-9a-f]{64}$")
+            self.assertEqual(first["build_id"], first["source_manifest_sha256"][:8].upper())
+            self.assertEqual(module.validate_source_manifest(first, root=root)["status"], "pass")
+
+            tampered = json.loads(json.dumps(first))
+            tampered["files"][0]["sha256"] = "0" * 64
+            validation = module.validate_source_manifest(tampered, root=root)
+            self.assertEqual(validation["status"], "fail")
+            self.assertIn("source_manifest_sha256_mismatch", validation["failures"])
+
+            (root / "a.v").write_text("module a; wire changed; endmodule\n", encoding="ascii")
+            changed = module.build_source_manifest(
+                root=root,
+                inputs=[root / "a.v", root / "b.v"],
+                profile="prod2u-bmc-replay-binary921",
+                td_version="6.2.2.198412",
+            )
+            self.assertNotEqual(first["source_manifest_sha256"], changed["source_manifest_sha256"])
+            self.assertNotEqual(first["build_id"], changed["build_id"])
+
+    def test_manifest_normalization_rehashes_injected_build_id_to_zero(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            top = root / "top.v"
+            top.write_text("parameter [31:0] BUILD_ID = 32'h00000000;\n", encoding="ascii")
+            manifest = module.build_source_manifest(
+                root=root,
+                inputs=[top],
+                profile="prod2u-bmc-replay-binary921",
+                td_version="6.2.2.198412",
+                normalizations={"top.v": "prod2u_build_id_zero"},
+            )
+
+            top.write_text("parameter [31:0] BUILD_ID = 32'h89ABCDEF;\n", encoding="ascii")
+            validation = module.validate_source_manifest(manifest, root=root)
+
+            self.assertEqual(validation["status"], "pass", validation["failures"])
+            self.assertEqual(manifest["files"][0]["normalization"], "prod2u_build_id_zero")
+
+    def test_generated_verilog_header_contains_exact_build_id(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            target = Path(tmp) / "prod2u_build_id.vh"
+            module.write_verilog_header({"build_id": "89ABCDEF"}, target)
+            self.assertEqual(
+                target.read_text(encoding="ascii"),
+                "`ifndef PROD2U_BUILD_ID\n`define PROD2U_BUILD_ID 32'h89ABCDEF\n`endif\n",
+            )
+
+    def test_cli_writes_manifest_and_header(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            source = root / "top.v"
+            source.write_text("module top; endmodule\n", encoding="ascii")
+            manifest = root / "manifest.json"
+            header = root / "prod2u_build_id.vh"
+            result = subprocess.run(
+                [
+                    sys.executable,
+                    str(MODULE_PATH),
+                    "--root",
+                    str(root),
+                    "--profile",
+                    "prod2u-bmc-replay-binary921",
+                    "--td-version",
+                    "6.2.2.198412",
+                    "--input",
+                    str(source),
+                    "--output",
+                    str(manifest),
+                    "--header",
+                    str(header),
+                ],
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(result.returncode, 0, result.stderr)
+            payload = json.loads(manifest.read_text(encoding="utf-8"))
+            self.assertEqual(payload["build_id"], payload["source_manifest_sha256"][:8].upper())
+            self.assertIn(payload["build_id"], header.read_text(encoding="ascii"))
+            self.assertEqual(json.loads(result.stdout)["status"], "pass")
+
+            validated = subprocess.run(
+                [sys.executable, str(MODULE_PATH), "--validate-manifest", str(manifest)],
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(validated.returncode, 0, validated.stderr + validated.stdout)
+
+            payload["files"][0]["sha256"] = "0" * 64
+            manifest.write_text(json.dumps(payload), encoding="utf-8")
+            rejected = subprocess.run(
+                [sys.executable, str(MODULE_PATH), "--validate-manifest", str(manifest)],
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertNotEqual(rejected.returncode, 0)
+            self.assertIn("source_manifest_sha256_mismatch", rejected.stdout)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 628 - 0
tests/unit/test_prod2u_contract.py

@@ -0,0 +1,628 @@
+#!/usr/bin/env python3
+"""Contract tests for the production two-UART SRAM evidence chain."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import copy
+import tempfile
+import unittest
+from pathlib import Path
+
+import jsonschema
+
+
+ROOT = Path(__file__).resolve().parents[2]
+MODULE_PATH = ROOT / "tools" / "prod2u_receipts.py"
+EXPECTED_PROGRAM_MARKERS = [
+    "download_start",
+    "chip_validation",
+    "bit_to_vec_start",
+    "bit_to_vec_finish",
+    "program_start",
+    "program_finish",
+    "download_finish",
+]
+EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+
+
+def load_module():
+    if not MODULE_PATH.is_file():
+        raise AssertionError(f"missing Prod2U receipt validator: {MODULE_PATH}")
+    spec = importlib.util.spec_from_file_location("prod2u_receipts", MODULE_PATH)
+    if spec is None or spec.loader is None:
+        raise AssertionError("unable to load Prod2U receipt validator")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+def program_receipt(build_id: str = "1234ABCD") -> dict:
+    receipt = {
+        "schema": "prod2u-program-sram-receipt-v1",
+        "status": "pass",
+        "run_id": "run-1",
+        "request": {
+            "operation": "PROGRAM_SRAM",
+            "target_chip": "EF2L45",
+            "cable_index": 0,
+            "speed_code": 2,
+            "speed_hz": 200000,
+            "attempt_limit": 1,
+            "power_cycle_allowed": False,
+        },
+        "bitstream": {
+            "path": f"C:/P2U/{build_id}/fw.bit",
+            "sha256": "a" * 64,
+            "build_id": build_id,
+        },
+        "execution": {
+            "exit_code": 0,
+            "timed_out": False,
+            "attempt_count": 1,
+            "retry_count": 0,
+            "power_cycle_count": 0,
+            "command_execution_attempted": True,
+            "timeout_seconds": 60,
+            "started_at": "2026-07-11T00:00:00Z",
+            "finished_at": "2026-07-11T00:00:01Z",
+            "duration_seconds": 1.0,
+        },
+        "parser": {
+            "status": "pass",
+            "exit_code_trusted": False,
+            "ordered_markers": list(EXPECTED_PROGRAM_MARKERS),
+            "ordered_markers_complete": True,
+            "observed_markers": list(EXPECTED_PROGRAM_MARKERS),
+            "observed_marker_lines": list(range(1, len(EXPECTED_PROGRAM_MARKERS) + 1)),
+            "error_markers": [],
+            "failures": [],
+            "transcript_sha256": "9" * 64,
+        },
+        "staging": {
+            "expected_path": f"C:\\P2U\\{build_id}\\fw.bit",
+            "observed_path": f"C:\\P2U\\{build_id}\\fw.bit",
+            "matches_expected_path": True,
+        },
+        "tool": {
+            "path": "C:\\Anlogic\\TD_Release_2026.1_SP1.198.412\\bin\\bw_commands_prompt.exe",
+            "td_root": "C:\\Anlogic\\TD_Release_2026.1_SP1.198.412",
+            "td_bin": "C:\\Anlogic\\TD_Release_2026.1_SP1.198.412\\bin",
+        },
+        "mutex": {"name": "Global\\Prod2UProgramSram", "acquired": True},
+        "process_cleanup": {
+            "status": "pass",
+            "td_root": "C:\\Anlogic\\TD_Release_2026.1_SP1.198.412",
+            "graceful_close_requested": [],
+            "forced_terminated": [],
+            "wait_seconds": 5.0,
+            "remaining": [],
+        },
+        "artifacts": {
+            name: {"path": name, "size": 1, "sha256": char * 64}
+            for name, char in (("tcl", "1"), ("stdout", "2"), ("stderr", "3"), ("log_delta", "4"))
+        },
+        "safety": {
+            "flash_attempted": False,
+            "programs_nonvolatile": False,
+            "power_cycle_attempted": False,
+            "driver_install_attempted": False,
+            "toggles_dtr_rts": False,
+            "real_ptc_fan_action_attempted": False,
+            "external_programming_command_executed": True,
+        },
+        "authority_boundary": "test",
+    }
+
+    receipt["artifacts"]["log_delta_sources"] = [
+        {
+            "path": "C:\\Anlogic\\TD_Release_2026.1_SP1.198.412\\log\\bw_20260711.log",
+            "start_offset": 100,
+            "byte_count": 200,
+            "sha256": "5" * 64,
+        }
+    ]
+    return receipt
+
+
+def evidence_manifest(build_id: str = "1234ABCD", *, bmc_status: str = "pass") -> dict:
+    return {
+        "schema": "prod2u-evidence-manifest-v1",
+        "status": "pass" if bmc_status == "pass" else "blocked_bmc_replay_not_run",
+        "protocol": "binary921",
+        "profile": "prod2u-bmc-replay-binary921",
+        "profile_id": 3,
+        "build_identity": {
+            "build_id": build_id,
+            "source_manifest_sha256": build_id.lower() + "b" * 56,
+        },
+        "programmer_receipt": {"path": "program-sram-receipt.json", "sha256": "c" * 64, "status": "pass"},
+        "startup_ready": {
+            "frame_type": 1,
+            "seq": 1,
+            "profile_id": 3,
+            "build_id": build_id,
+            "post_program_epoch": True,
+            "por_reason": 1,
+            "announcement_seq": 0,
+            "matching_ready_count": 1,
+            "selection_policy": "last_matching_ready",
+        },
+        "host_command_count": 12,
+        "host_ack_count": 12,
+        "host_ack_matched_count": 12,
+        "bmc_replay": {
+            "status": bmc_status,
+            "bmc_source": "pc_replay_from_real_bmc_capture" if bmc_status == "pass" else "not_run",
+            "payload_sha256": "d" * 64 if bmc_status == "pass" else None,
+        },
+        "artifact_hashes": {"combined-rx.raw": "e" * 64, "host-command-wire.bin": "f" * 64},
+        "real_fan_ptc_hardware_status": "not_run",
+        "safety": {
+            "flash_attempted": False,
+            "programs_nonvolatile": False,
+            "driver_install_attempted": False,
+            "power_cycle_attempted": False,
+            "toggles_dtr_rts": False,
+        },
+    }
+
+
+def collector_manifest(build_id: str = "1234ABCD") -> dict:
+    return {
+        "schema": "prod2u-collector-manifest-v1",
+        "status": "pass",
+        "protocol": "binary921",
+        "profile": "prod2u-bmc-replay-binary921",
+        "profile_id": 3,
+        "startup_ready": {
+            "frame_type": 1,
+            "seq": 1,
+            "profile_id": 3,
+            "matching_ready_count": 1,
+            "selection_policy": "last_matching_ready",
+            "decoded": {
+                "kind": "ready",
+                "profile_id_payload": 3,
+                "build_id": build_id,
+                "por_reason": 1,
+                "announcement_seq": 0,
+            },
+        },
+        "host_command_count": 12,
+        "host_ack_count": 12,
+        "host_ack_matched_count": 12,
+        "bmc_replay": {
+            "status": "pass",
+            "bmc_source": "pc_replay_from_real_bmc_capture",
+            "payload_sha256": "d" * 64,
+        },
+        "artifact_hashes": {"combined-rx.raw": "e" * 64, "host-command-wire.bin": "f" * 64},
+        "real_fan_ptc_hardware_status": "not_run",
+        "safety": {
+            "flash_attempted": False,
+            "programs_nonvolatile": False,
+            "driver_install_attempted": False,
+            "toggles_dtr_rts": False,
+        },
+    }
+
+
+class Prod2UContractTests(unittest.TestCase):
+    def test_source_manifest_text_inputs_are_checkout_stable(self) -> None:
+        attributes = (ROOT / ".gitattributes").read_text(encoding="ascii").splitlines()
+        expected = {
+            "*.adc text eol=lf",
+            "*.json text eol=lf",
+            "*.md text eol=lf",
+            "*.prj text eol=lf",
+            "*.py text eol=lf",
+            "*.sdc text eol=lf",
+            "*.tcl text eol=lf",
+            "*.v text eol=lf",
+            "*.vh text eol=lf",
+        }
+
+        self.assertTrue(expected.issubset(set(attributes)))
+
+    def test_versioned_schemas_exist_and_lock_profile_and_sram_mode(self) -> None:
+        program_schema_path = ROOT / "schemas" / "prod2u_program_sram_receipt.schema.json"
+        evidence_schema_path = ROOT / "schemas" / "prod2u_evidence_manifest.schema.json"
+        final_schema_path = ROOT / "schemas" / "prod2u_final_gate.schema.json"
+        td_schema_path = ROOT / "schemas" / "prod2u_td_build_receipt.schema.json"
+        for path in (program_schema_path, evidence_schema_path, final_schema_path, td_schema_path):
+            with self.subTest(path=path.name):
+                self.assertTrue(path.is_file(), path)
+
+        evidence_schema = json.loads(evidence_schema_path.read_text(encoding="utf-8"))
+        self.assertEqual(evidence_schema["properties"]["profile"]["const"], "prod2u-bmc-replay-binary921")
+        self.assertEqual(evidence_schema["properties"]["profile_id"]["const"], 3)
+
+        program_schema = json.loads(program_schema_path.read_text(encoding="utf-8"))
+        request_props = program_schema["properties"]["request"]["properties"]
+        self.assertEqual(request_props["operation"]["const"], "PROGRAM_SRAM")
+        self.assertEqual(request_props["speed_code"]["const"], 2)
+        self.assertEqual(request_props["speed_hz"]["const"], 200000)
+        self.assertEqual(request_props["attempt_limit"]["const"], 1)
+        self.assertEqual(request_props["power_cycle_allowed"]["const"], False)
+
+    def test_json_schemas_reject_false_pass_evidence_and_gate(self) -> None:
+        evidence_schema = json.loads(
+            (ROOT / "schemas" / "prod2u_evidence_manifest.schema.json").read_text(encoding="utf-8")
+        )
+        final_schema = json.loads(
+            (ROOT / "schemas" / "prod2u_final_gate.schema.json").read_text(encoding="utf-8")
+        )
+
+        valid_evidence = evidence_manifest()
+        jsonschema.validate(valid_evidence, evidence_schema)
+        for field in ("programmer_receipt", "bmc_replay", "artifact_hashes", "safety"):
+            with self.subTest(field=field):
+                invalid = copy.deepcopy(valid_evidence)
+                invalid[field] = {}
+                with self.assertRaises(jsonschema.ValidationError):
+                    jsonschema.validate(invalid, evidence_schema)
+
+        valid_gate = {
+            "schema": "prod2u-final-gate-v1",
+            "status": "pass",
+            "failures": [],
+            "layers": {
+                name: "pass"
+                for name in (
+                    "static",
+                    "rtl_sim",
+                    "formal",
+                    "td_build",
+                    "program_sram",
+                    "fresh_epoch",
+                    "host_uart",
+                    "bmc_replay",
+                )
+            },
+            "authority_boundary": "test",
+        }
+        jsonschema.validate(valid_gate, final_schema)
+        invalid_gate = copy.deepcopy(valid_gate)
+        invalid_gate["layers"]["bmc_replay"] = "blocked"
+        with self.assertRaises(jsonschema.ValidationError):
+            jsonschema.validate(invalid_gate, final_schema)
+
+    def test_td_pass_schema_requires_verified_zero_initialized_por_registers(self) -> None:
+        schema = json.loads(
+            (ROOT / "schemas" / "prod2u_td_build_receipt.schema.json").read_text(encoding="utf-8")
+        )
+        receipt = {
+            "schema": "prod2u-td-build-receipt-v1",
+            "status": "pass",
+            "top": "prod2u_bmc_replay_binary921",
+            "top_module": "prod2u_bmc_replay_binary921_top",
+            "pin_profile": "prod2u-bmc-replay-binary921",
+            "build_identity": {
+                "status": "pass",
+                "build_id": "1234ABCD",
+                "source_manifest_sha256": "1" * 64,
+                "staged_manifest_sha256": "2" * 64,
+            },
+            "build_id": "1234ABCD",
+            "source_manifest_sha256": "1" * 64,
+            "bitstream": {"path": "fw.bit", "size": 1, "sha256": "3" * 64},
+            "resources": {},
+            "timing": {},
+            "timing_gate": {"status": "pass"},
+            "syn": {"returncode": 0, "log_has_error": False},
+            "phy": {"returncode": 0, "log_has_error": False},
+            "por_initialization": {
+                "status": "pass",
+                "por_cycles": 1024,
+                "counter_width": 10,
+                "expected_init": "0",
+                "register_count": 11,
+                "failures": [],
+            },
+        }
+
+        jsonschema.validate(receipt, schema)
+        missing = copy.deepcopy(receipt)
+        missing.pop("por_initialization")
+        with self.assertRaises(jsonschema.ValidationError):
+            jsonschema.validate(missing, schema)
+        nonzero = copy.deepcopy(receipt)
+        nonzero["por_initialization"]["status"] = "fail"
+        with self.assertRaises(jsonschema.ValidationError):
+            jsonschema.validate(nonzero, schema)
+
+    def test_program_schema_rejects_false_pass_runtime_evidence(self) -> None:
+        schema = json.loads(
+            (ROOT / "schemas" / "prod2u_program_sram_receipt.schema.json").read_text(encoding="utf-8")
+        )
+        valid = program_receipt()
+        jsonschema.validate(valid, schema)
+
+        invalid_cases = []
+
+        wrong_markers = copy.deepcopy(valid)
+        wrong_markers["parser"]["observed_markers"] = list(reversed(EXPECTED_PROGRAM_MARKERS))
+        invalid_cases.append(("wrong_markers", wrong_markers))
+
+        missing_log_source = copy.deepcopy(valid)
+        missing_log_source["artifacts"]["log_delta_sources"] = []
+        invalid_cases.append(("missing_log_source", missing_log_source))
+
+        ambiguous_log_sources = copy.deepcopy(valid)
+        ambiguous_log_sources["artifacts"]["log_delta_sources"].append(
+            copy.deepcopy(ambiguous_log_sources["artifacts"]["log_delta_sources"][0])
+        )
+        invalid_cases.append(("ambiguous_log_sources", ambiguous_log_sources))
+
+        empty_log_artifact = copy.deepcopy(valid)
+        empty_log_artifact["artifacts"]["log_delta"]["size"] = 0
+        empty_log_artifact["artifacts"]["log_delta"]["sha256"] = EMPTY_SHA256
+        invalid_cases.append(("empty_log_artifact", empty_log_artifact))
+
+        empty_transcript_hash = copy.deepcopy(valid)
+        empty_transcript_hash["parser"]["transcript_sha256"] = EMPTY_SHA256
+        invalid_cases.append(("empty_transcript_hash", empty_transcript_hash))
+
+        empty_log_source_hash = copy.deepcopy(valid)
+        empty_log_source_hash["artifacts"]["log_delta_sources"][0]["sha256"] = EMPTY_SHA256
+        invalid_cases.append(("empty_log_source_hash", empty_log_source_hash))
+
+        non_bitwriter_log_source = copy.deepcopy(valid)
+        non_bitwriter_log_source["artifacts"]["log_delta_sources"][0]["path"] = "C:\\logs\\other.log"
+        invalid_cases.append(("non_bitwriter_log_source", non_bitwriter_log_source))
+
+        for name, invalid in invalid_cases:
+            with self.subTest(name=name):
+                with self.assertRaises(jsonschema.ValidationError):
+                    jsonschema.validate(invalid, schema)
+
+    def test_evidence_schema_rejects_empty_runtime_evidence_hashes(self) -> None:
+        schema = json.loads(
+            (ROOT / "schemas" / "prod2u_evidence_manifest.schema.json").read_text(encoding="utf-8")
+        )
+        valid = evidence_manifest()
+        jsonschema.validate(valid, schema)
+
+        empty_hash_paths = (
+            ("programmer_receipt", "sha256"),
+            ("bmc_replay", "payload_sha256"),
+            ("artifact_hashes", "combined-rx.raw"),
+            ("artifact_hashes", "host-command-wire.bin"),
+        )
+        for section, field in empty_hash_paths:
+            with self.subTest(section=section, field=field):
+                invalid = copy.deepcopy(valid)
+                invalid[section][field] = EMPTY_SHA256
+                with self.assertRaises(jsonschema.ValidationError):
+                    jsonschema.validate(invalid, schema)
+
+    def test_evidence_pass_requires_matching_program_and_ready_build_identity(self) -> None:
+        module = load_module()
+        result = module.validate_evidence_manifest(evidence_manifest(), program_receipt())
+        self.assertEqual(result["status"], "pass", result.get("failures"))
+
+        mismatched = evidence_manifest(build_id="DEADBEEF")
+        result = module.validate_evidence_manifest(mismatched, program_receipt(build_id="1234ABCD"))
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("program_ready_build_id_mismatch", result["failures"])
+
+        mismatched_source_hash = evidence_manifest()
+        mismatched_source_hash["build_identity"]["source_manifest_sha256"] = "deadbeef" + "b" * 56
+        result = module.validate_evidence_manifest(mismatched_source_hash, program_receipt())
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("source_manifest_build_id_mismatch", result["failures"])
+
+        bad_por = evidence_manifest()
+        bad_por["startup_ready"]["por_reason"] = 2
+        result = module.validate_evidence_manifest(bad_por, program_receipt())
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("startup_ready_por_reason_invalid", result["failures"])
+
+        bad_announcement = evidence_manifest()
+        bad_announcement["startup_ready"]["announcement_seq"] = 3
+        result = module.validate_evidence_manifest(bad_announcement, program_receipt())
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("startup_ready_announcement_seq_invalid", result["failures"])
+
+    def test_bmc_not_run_remains_blocked_even_when_programmer_and_uart_pass(self) -> None:
+        module = load_module()
+        result = module.validate_evidence_manifest(evidence_manifest(bmc_status="not_run"), program_receipt())
+        self.assertEqual(result["status"], "blocked_bmc_replay_not_run")
+        self.assertIn("bmc_replay_not_pass", result["failures"])
+
+    def test_bmc_not_run_evidence_may_declare_only_its_expected_blocker(self) -> None:
+        module = load_module()
+        evidence = evidence_manifest(bmc_status="not_run")
+        evidence["blockers"] = ["bmc_replay_not_pass"]
+
+        result = module.validate_evidence_manifest(evidence, program_receipt())
+
+        self.assertEqual(result["status"], "blocked_bmc_replay_not_run")
+        self.assertEqual(result["failures"], ["bmc_replay_not_pass"])
+
+    def test_final_gate_requires_every_required_layer_to_pass(self) -> None:
+        module = load_module()
+        layers = {
+            "static": "pass",
+            "rtl_sim": "pass",
+            "formal": "pass",
+            "td_build": "pass",
+            "program_sram": "pass",
+            "fresh_epoch": "pass",
+            "host_uart": "pass",
+            "bmc_replay": "pass",
+        }
+        result = module.build_final_gate(program_receipt(), evidence_manifest(), layers)
+        self.assertEqual(result["status"], "pass", result.get("failures"))
+
+        layers["bmc_replay"] = "not_run"
+        result = module.build_final_gate(program_receipt(), evidence_manifest(), layers)
+        self.assertEqual(result["status"], "blocked")
+        self.assertIn("required_layer_not_pass:bmc_replay:not_run", result["failures"])
+
+    def test_final_gate_rejects_evidence_that_declares_failure_or_blockers(self) -> None:
+        module = load_module()
+        layers = {
+            name: "pass"
+            for name in ("static", "rtl_sim", "formal", "td_build", "program_sram", "fresh_epoch", "host_uart", "bmc_replay")
+        }
+        evidence = evidence_manifest()
+        evidence["status"] = "fail"
+        evidence["blockers"] = ["forced_blocker"]
+
+        result = module.build_final_gate(program_receipt(), evidence, layers)
+
+        self.assertNotEqual(result["status"], "pass")
+        self.assertIn("evidence_manifest_not_pass:fail", result["failures"])
+
+    def test_schema_validation_rejects_non_sram_or_retry_receipt(self) -> None:
+        module = load_module()
+        payload = program_receipt()
+        payload["request"]["operation"] = "PROGRAM_FLASH"
+        payload["execution"]["attempt_count"] = 2
+        result = module.validate_program_receipt(payload)
+        self.assertEqual(result["status"], "fail_forbidden_action")
+        self.assertIn("operation_not_program_sram", result["failures"])
+        self.assertIn("attempt_count_not_one", result["failures"])
+
+    def test_program_gate_rejects_parser_only_receipt_or_incomplete_runtime_boundary(self) -> None:
+        module = load_module()
+        cases = {
+            "not_executed": ("execution", "command_execution_attempted", False, "program_command_not_executed"),
+            "wrong_timeout": ("execution", "timeout_seconds", 61, "program_timeout_boundary_not_60"),
+            "mutex_not_acquired": ("mutex", "acquired", False, "program_mutex_not_acquired"),
+            "cleanup_failed": ("process_cleanup", "status", "fail", "td_process_cleanup_not_pass"),
+            "cleanup_wait": ("process_cleanup", "wait_seconds", 0.0, "td_process_cleanup_wait_not_5s"),
+            "staging_mismatch": ("staging", "matches_expected_path", False, "staging_path_not_verified"),
+            "external_flag": ("safety", "external_programming_command_executed", False, "external_programming_command_not_recorded"),
+        }
+        for name, (section, key, value, failure) in cases.items():
+            with self.subTest(name=name):
+                payload = program_receipt()
+                payload[section][key] = value
+                result = module.validate_program_receipt(payload)
+                self.assertNotEqual(result["status"], "pass")
+                self.assertIn(failure, result["failures"])
+
+    def test_program_gate_requires_exact_markers_and_single_nonempty_log_source(self) -> None:
+        module = load_module()
+
+        wrong_markers = program_receipt()
+        wrong_markers["parser"]["observed_markers"] = EXPECTED_PROGRAM_MARKERS + ["download_finish"]
+        result = module.validate_program_receipt(wrong_markers)
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("program_observed_markers_not_exact", result["failures"])
+
+        log_source_cases = {
+            "missing": [],
+            "ambiguous": program_receipt()["artifacts"]["log_delta_sources"] * 2,
+            "empty": [
+                {
+                    "path": "C:\\Anlogic\\TD_Release_2026.1_SP1.198.412\\log\\bw_20260711.log",
+                    "start_offset": 100,
+                    "byte_count": 0,
+                    "sha256": EMPTY_SHA256,
+                }
+            ],
+            "empty_hash": [
+                {
+                    "path": "C:\\Anlogic\\TD_Release_2026.1_SP1.198.412\\log\\bw_20260711.log",
+                    "start_offset": 100,
+                    "byte_count": 200,
+                    "sha256": EMPTY_SHA256,
+                }
+            ],
+            "not_bitwriter": [
+                {
+                    "path": "C:\\logs\\other.log",
+                    "start_offset": 100,
+                    "byte_count": 200,
+                    "sha256": "5" * 64,
+                }
+            ],
+        }
+        for name, sources in log_source_cases.items():
+            with self.subTest(name=name):
+                payload = program_receipt()
+                payload["artifacts"]["log_delta_sources"] = sources
+                result = module.validate_program_receipt(payload)
+                self.assertEqual(result["status"], "fail")
+                self.assertIn("bitwriter_log_source_not_exactly_one_nonempty", result["failures"])
+
+        empty_log = program_receipt()
+        empty_log["artifacts"]["log_delta"]["size"] = 0
+        empty_log["artifacts"]["log_delta"]["sha256"] = EMPTY_SHA256
+        result = module.validate_program_receipt(empty_log)
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("program_log_delta_empty", result["failures"])
+
+        empty_transcript = program_receipt()
+        empty_transcript["parser"]["transcript_sha256"] = EMPTY_SHA256
+        result = module.validate_program_receipt(empty_transcript)
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("program_transcript_sha256_invalid_or_empty", result["failures"])
+
+    def test_program_gate_binds_cleanup_to_tool_td_root(self) -> None:
+        module = load_module()
+        payload = program_receipt()
+        payload["process_cleanup"]["td_root"] = "C:\\Anlogic\\Other_TD"
+        result = module.validate_program_receipt(payload)
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("cleanup_td_root_mismatch", result["failures"])
+
+    def test_evidence_gate_rejects_self_asserted_empty_runtime_hashes(self) -> None:
+        module = load_module()
+        cases = (
+            ("programmer_receipt", "sha256", "programmer_receipt_sha256_empty"),
+            ("bmc_replay", "payload_sha256", "bmc_payload_sha256_empty"),
+            ("artifact_hashes", "combined-rx.raw", "artifact_hash_empty:combined-rx.raw"),
+            ("artifact_hashes", "host-command-wire.bin", "artifact_hash_empty:host-command-wire.bin"),
+        )
+        for section, field, failure in cases:
+            with self.subTest(section=section, field=field):
+                evidence = evidence_manifest()
+                evidence[section][field] = EMPTY_SHA256
+                result = module.validate_evidence_manifest(evidence, program_receipt())
+                self.assertEqual(result["status"], "fail")
+                self.assertIn(failure, result["failures"])
+
+    def test_assemble_evidence_binds_program_collector_and_source_manifest(self) -> None:
+        module = load_module()
+        source = {
+            "schema": "prod2u-source-manifest-v1",
+            "profile": "prod2u-bmc-replay-binary921",
+            "source_manifest_sha256": "1234abcd" + "b" * 56,
+            "build_id": "1234ABCD",
+        }
+        assembled = module.assemble_evidence_manifest(
+            collector=collector_manifest(),
+            program=program_receipt(),
+            source_manifest=source,
+            programmer_receipt_path="program-sram-receipt.json",
+            programmer_receipt_sha256="c" * 64,
+        )
+        self.assertEqual(assembled["schema"], "prod2u-evidence-manifest-v1")
+        self.assertEqual(assembled["status"], "pass")
+        self.assertEqual(assembled["build_identity"]["source_manifest_sha256"], source["source_manifest_sha256"])
+        self.assertEqual(assembled["startup_ready"]["build_id"], "1234ABCD")
+        self.assertEqual(assembled["startup_ready"]["por_reason"], 1)
+        self.assertEqual(assembled["startup_ready"]["announcement_seq"], 0)
+        self.assertTrue(assembled["startup_ready"]["post_program_epoch"])
+        self.assertEqual(assembled["programmer_receipt"]["sha256"], "c" * 64)
+
+        wrong = collector_manifest(build_id="DEADBEEF")
+        assembled = module.assemble_evidence_manifest(
+            collector=wrong,
+            program=program_receipt(),
+            source_manifest=source,
+            programmer_receipt_path="program-sram-receipt.json",
+            programmer_receipt_sha256="c" * 64,
+        )
+        self.assertEqual(assembled["status"], "fail")
+        self.assertIn("program_ready_build_id_mismatch", assembled["blockers"])
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 538 - 0
tests/unit/test_prod2u_entrypoint.py

@@ -0,0 +1,538 @@
+#!/usr/bin/env python3
+"""Tests for the unified Prod2U Windows entrypoint."""
+
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "tools"))
+from prod2u_build_identity import build_source_manifest  # noqa: E402
+POWERSHELL_ENTRY = ROOT / "tools" / "prod2u.ps1"
+PYTHON_ENTRY = ROOT / "tools" / "prod2u_cli.py"
+
+
+def load_module():
+    spec = importlib.util.spec_from_file_location("prod2u_cli_test", PYTHON_ENTRY)
+    if spec is None or spec.loader is None:
+        raise AssertionError("unable to load Prod2U CLI")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+def fake_program_receipt(build_id: str, sha256: str) -> dict:
+    return {
+        "schema": "prod2u-program-sram-receipt-v1",
+        "status": "pass",
+        "run_id": "unit",
+        "request": {
+            "operation": "PROGRAM_SRAM",
+            "target_chip": "EF2L45",
+            "cable_index": 0,
+            "speed_code": 2,
+            "speed_hz": 200000,
+            "attempt_limit": 1,
+            "power_cycle_allowed": False,
+        },
+        "bitstream": {"path": f"C:/P2U/{build_id}/fw.bit", "sha256": sha256, "build_id": build_id},
+        "staging": {
+            "expected_path": f"C:/P2U/{build_id}/fw.bit",
+            "observed_path": f"C:/P2U/{build_id}/fw.bit",
+            "matches_expected_path": True,
+        },
+        "execution": {
+            "exit_code": 0,
+            "timed_out": False,
+            "attempt_count": 1,
+            "retry_count": 0,
+            "power_cycle_count": 0,
+            "command_execution_attempted": True,
+            "timeout_seconds": 60,
+        },
+        "parser": {"status": "pass", "ordered_markers_complete": True, "error_markers": [], "failures": []},
+        "tool": {"path": "C:/TD/bin/bw_commands_prompt.exe", "td_root": "C:/TD", "td_bin": "C:/TD/bin"},
+        "mutex": {"name": "Global\\Prod2UProgramSram", "acquired": True},
+        "process_cleanup": {
+            "status": "pass",
+            "td_root": "C:/TD",
+            "graceful_close_requested": [],
+            "forced_terminated": [],
+            "wait_seconds": 5.0,
+            "remaining": [],
+        },
+        "artifacts": {
+            name: {"path": name, "size": 1, "sha256": char * 64}
+            for name, char in (("tcl", "1"), ("stdout", "2"), ("stderr", "3"), ("log_delta", "4"))
+        },
+        "safety": {
+            "flash_attempted": False,
+            "programs_nonvolatile": False,
+            "power_cycle_attempted": False,
+            "driver_install_attempted": False,
+            "toggles_dtr_rts": False,
+            "real_ptc_fan_action_attempted": False,
+            "external_programming_command_executed": True,
+        },
+    }
+
+
+class Prod2UEntrypointTests(unittest.TestCase):
+    def make_inputs(self, root: Path) -> SimpleNamespace:
+        bitstream = root / "fw.bit"
+        bitstream.write_bytes(b"prod2u entrypoint bitstream")
+        bit_sha = hashlib.sha256(bitstream.read_bytes()).hexdigest()
+        identity_source = root / "identity-source.v"
+        identity_source.write_text("module identity_source; endmodule\n", encoding="ascii")
+        identity = build_source_manifest(
+            root=root,
+            inputs=[identity_source],
+            profile="prod2u-bmc-replay-binary921",
+            td_version="6.2.2.198412",
+        )
+        source_hash = str(identity["source_manifest_sha256"])
+        build_id = str(identity["build_id"])
+        source_manifest = root / "source-manifest.json"
+        source_manifest.write_text(json.dumps(identity), encoding="utf-8")
+        td_root = root / "TD"
+        (td_root / "bin").mkdir(parents=True)
+        (td_root / "bin" / "bw_commands_prompt.exe").write_bytes(b"fixture")
+        td_receipt = root / "td.json"
+        td_receipt.write_text(
+            json.dumps(
+                {
+                    "schema": "prod2u-td-build-receipt-v1",
+                    "status": "pass",
+                    "top": "prod2u_bmc_replay_binary921",
+                    "profile": "prod2u-bmc-replay-binary921",
+                    "pin_profile": "prod2u-bmc-replay-binary921",
+                    "top_module": "prod2u_bmc_replay_binary921_top",
+                    "source_manifest_sha256": source_hash,
+                    "build_id": build_id,
+                    "build_identity": {
+                        "status": "pass",
+                        "build_id": build_id,
+                        "source_manifest_sha256": source_hash,
+                        "staged_manifest_sha256": "f" * 64,
+                    },
+                    "bitstream": {"path": str(bitstream), "size": bitstream.stat().st_size, "sha256": bit_sha},
+                    "resources": {},
+                    "timing": {},
+                    "timing_gate": {"status": "pass"},
+                    "syn": {"returncode": 0, "log_has_error": False},
+                    "phy": {"returncode": 0, "log_has_error": False},
+                    "por_initialization": {
+                        "status": "pass",
+                        "por_cycles": 1024,
+                        "counter_width": 10,
+                        "expected_init": "0",
+                        "register_count": 11,
+                        "failures": [],
+                    },
+                }
+            ),
+            encoding="utf-8",
+        )
+        bmc = root / "bmc.json"
+        bmc.write_text(json.dumps({"status": "pass"}), encoding="utf-8")
+        return SimpleNamespace(
+            combined_port="COM5",
+            bitstream=str(bitstream),
+            td_receipt=str(td_receipt),
+            source_manifest=str(source_manifest),
+            bmc_replay_receipt=str(bmc),
+            output_dir=str(root / "evidence"),
+            td_root=str(td_root),
+            duration_sec=0.0,
+            ready_timeout_sec=1.0,
+            pre_program_observe_sec=0.0,
+            build_id=build_id,
+        )
+
+    def test_entrypoints_expose_all_modes_and_safe_defaults(self) -> None:
+        self.assertTrue(POWERSHELL_ENTRY.is_file(), POWERSHELL_ENTRY)
+        self.assertTrue(PYTHON_ENTRY.is_file(), PYTHON_ENTRY)
+        powershell = POWERSHELL_ENTRY.read_text(encoding="utf-8", errors="replace")
+        for marker in ("selftest", "preflight", "program-only", "collect-only", "all"):
+            self.assertIn(marker, powershell)
+        self.assertIn("COM5", powershell)
+        self.assertNotIn("Set-ExecutionPolicy", powershell)
+        self.assertNotIn("power cycle", powershell.lower())
+
+        python = PYTHON_ENTRY.read_text(encoding="utf-8", errors="replace")
+        self.assertIn("--combined-port", python)
+        self.assertIn("prod2u-bmc-replay-binary921", python)
+        self.assertIn("C:\\\\P2U", python)
+        self.assertNotIn("PROGRAM_FLASH", python)
+        self.assertNotIn("ERASE_FLASH", python)
+
+    def test_selftest_runs_without_opening_hardware(self) -> None:
+        result = subprocess.run(
+            [
+                "powershell.exe",
+                "-NoProfile",
+                "-ExecutionPolicy",
+                "Bypass",
+                "-File",
+                str(POWERSHELL_ENTRY),
+                "selftest",
+            ],
+            cwd=ROOT,
+            capture_output=True,
+            text=True,
+            check=False,
+        )
+        self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
+        self.assertIn('"status": "pass"', result.stdout)
+        self.assertIn('"hardware_opened": false', result.stdout)
+        self.assertIn('"program_sram_attempted": false', result.stdout)
+
+    def test_preflight_validates_identity_and_hashes_without_opening_hardware(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            args = self.make_inputs(Path(tmp))
+            payload = module.run_preflight(args)
+            self.assertEqual(payload["status"], "pass", payload)
+            self.assertEqual(payload["build_id"], args.build_id)
+            self.assertFalse(payload["hardware_opened"])
+            self.assertFalse(payload["program_sram_attempted"])
+
+            td = json.loads(Path(args.td_receipt).read_text(encoding="utf-8"))
+            td["bitstream"]["sha256"] = "0" * 64
+            Path(args.td_receipt).write_text(json.dumps(td), encoding="utf-8")
+            blocked = module.run_preflight(args)
+            self.assertEqual(blocked["status"], "fail_preflight")
+            self.assertIn("td_bitstream_sha256_mismatch", blocked["failures"])
+
+    def test_preflight_rejects_td_receipt_without_a_passing_por_init_gate(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            args = self.make_inputs(Path(tmp))
+            td_path = Path(args.td_receipt)
+            td = json.loads(td_path.read_text(encoding="utf-8"))
+            td["por_initialization"]["status"] = "fail"
+            td_path.write_text(json.dumps(td), encoding="utf-8")
+
+            blocked = module.run_preflight(args)
+
+        self.assertEqual(blocked["status"], "fail_preflight")
+        self.assertIn("td_por_initialization_not_pass", blocked["failures"])
+
+    def test_preflight_executes_full_td_receipt_schema(self) -> None:
+        module = load_module()
+        for field, value in (("timing_gate", {"status": "fail"}), ("syn", {"returncode": 1, "log_has_error": False})):
+            with self.subTest(field=field), tempfile.TemporaryDirectory() as tmp:
+                args = self.make_inputs(Path(tmp))
+                td_path = Path(args.td_receipt)
+                td = json.loads(td_path.read_text(encoding="utf-8"))
+                td[field] = value
+                td_path.write_text(json.dumps(td), encoding="utf-8")
+
+                blocked = module.run_preflight(args)
+
+                self.assertEqual(blocked["status"], "fail_preflight")
+                self.assertIn("td_receipt_schema_invalid", blocked["failures"])
+
+    def test_package_inventory_validates_every_declared_file_size_and_sha256(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            package_root = Path(tmp)
+            artifact = package_root / "payload.bin"
+            artifact.write_bytes(b"trusted payload")
+            manifest_path = package_root / "manifest.json"
+            manifest_path.write_text(
+                json.dumps({"schema": "prod2u-package-manifest-v1"}),
+                encoding="utf-8",
+            )
+            (package_root / "sha256-inventory.json").write_text(
+                json.dumps(
+                    {
+                        "schema": "prod2u-package-sha256-inventory-v1",
+                        "inventory": [
+                            {
+                                "path": "payload.bin",
+                                "size": artifact.stat().st_size,
+                                "sha256": hashlib.sha256(artifact.read_bytes()).hexdigest(),
+                            },
+                            {
+                                "path": "manifest.json",
+                                "size": manifest_path.stat().st_size,
+                                "sha256": hashlib.sha256(manifest_path.read_bytes()).hexdigest(),
+                            },
+                        ],
+                    }
+                ),
+                encoding="utf-8",
+            )
+
+            self.assertEqual(module._validate_package_integrity(package_root), [])
+
+            artifact.write_bytes(b"tampered payload")
+            failures = module._validate_package_integrity(package_root)
+            self.assertIn("package_inventory_size_mismatch:payload.bin", failures)
+            self.assertIn("package_inventory_sha256_mismatch:payload.bin", failures)
+
+            artifact.unlink()
+            self.assertIn(
+                "package_inventory_file_missing:payload.bin",
+                module._validate_package_integrity(package_root),
+            )
+
+    def test_package_inventory_rejects_empty_inventory_and_unlisted_files(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            package_root = Path(tmp)
+            manifest_path = package_root / "manifest.json"
+            manifest_path.write_text(json.dumps({"schema": "prod2u-package-manifest-v1"}), encoding="utf-8")
+            inventory_path = package_root / "sha256-inventory.json"
+            inventory_path.write_text(
+                json.dumps(
+                    {
+                        "schema": "prod2u-package-sha256-inventory-v1",
+                        "inventory": [
+                            {
+                                "path": "manifest.json",
+                                "size": manifest_path.stat().st_size,
+                                "sha256": hashlib.sha256(manifest_path.read_bytes()).hexdigest(),
+                            }
+                        ],
+                    }
+                ),
+                encoding="utf-8",
+            )
+            unlisted = package_root / "unlisted.py"
+            unlisted.write_text("raise SystemExit('must not run')\n", encoding="utf-8")
+
+            failures = module._validate_package_integrity(package_root)
+
+            self.assertIn("package_inventory_unlisted_file:unlisted.py", failures)
+            unlisted.unlink()
+            inventory_path.write_text(
+                json.dumps({"schema": "prod2u-package-sha256-inventory-v1", "inventory": []}),
+                encoding="utf-8",
+            )
+            self.assertIn("package_inventory_empty", module._validate_package_integrity(package_root))
+
+    def test_source_checkout_without_package_inventory_keeps_explicit_input_validation(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            args = self.make_inputs(Path(tmp))
+
+            payload = module.run_preflight(args)
+
+            self.assertEqual(payload["status"], "pass", payload)
+            self.assertNotIn("package_integrity", payload["failures"])
+
+    def test_preflight_rejects_internally_tampered_source_manifest(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            args = self.make_inputs(Path(tmp))
+            manifest = json.loads(Path(args.source_manifest).read_text(encoding="utf-8"))
+            manifest["files"][0]["sha256"] = "0" * 64
+            Path(args.source_manifest).write_text(json.dumps(manifest), encoding="utf-8")
+
+            payload = module.run_preflight(args)
+
+            self.assertEqual(payload["status"], "fail_preflight")
+            self.assertIn("source_manifest_sha256_mismatch", payload["failures"])
+
+    def test_preflight_rejects_wrong_td_receipt_identity_contract(self) -> None:
+        module = load_module()
+        cases = {
+            "schema": ("schema", "wrong", "td_receipt_schema_mismatch"),
+            "top": ("top_module", "wrong_top", "td_top_module_mismatch"),
+            "pin": ("pin_profile", "wrong-profile", "td_pin_profile_mismatch"),
+        }
+        for name, (field, value, expected) in cases.items():
+            with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp:
+                args = self.make_inputs(Path(tmp))
+                receipt = json.loads(Path(args.td_receipt).read_text(encoding="utf-8"))
+                receipt[field] = value
+                Path(args.td_receipt).write_text(json.dumps(receipt), encoding="utf-8")
+
+                payload = module.run_preflight(args)
+
+            self.assertEqual(payload["status"], "fail_preflight")
+            self.assertIn(expected, payload["failures"])
+
+    def test_preflight_requires_td_source_identity_fields_to_exactly_match_manifest(self) -> None:
+        module = load_module()
+        cases = {
+            "missing_source_manifest_sha256": ("source_manifest_sha256", None, "td_source_manifest_sha256_missing"),
+            "missing_build_id": ("build_id", None, "td_build_id_missing"),
+            "mismatched_source_manifest_sha256": ("source_manifest_sha256", "0" * 64, "td_source_manifest_sha256_mismatch"),
+            "mismatched_build_id": ("build_id", "00000000", "td_build_id_mismatch"),
+        }
+        for name, (field, value, expected) in cases.items():
+            with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp:
+                args = self.make_inputs(Path(tmp))
+                receipt = json.loads(Path(args.td_receipt).read_text(encoding="utf-8"))
+                if value is None:
+                    receipt.pop(field)
+                else:
+                    receipt[field] = value
+                Path(args.td_receipt).write_text(json.dumps(receipt), encoding="utf-8")
+
+                payload = module.run_preflight(args)
+
+                self.assertEqual(payload["status"], "fail_preflight")
+                self.assertIn(expected, payload["failures"])
+
+    def test_program_only_calls_single_programmer_boundary(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            args = self.make_inputs(Path(tmp))
+            calls: list[dict] = []
+
+            def fake_executor(**kwargs):
+                calls.append(kwargs)
+                return fake_program_receipt(args.build_id, hashlib.sha256(Path(args.bitstream).read_bytes()).hexdigest())
+
+            payload = module.run_program_only(args, program_executor=fake_executor)
+            self.assertEqual(payload["status"], "pass")
+            self.assertEqual(len(calls), 1)
+            self.assertEqual(calls[0]["build_id"], args.build_id)
+            self.assertEqual(calls[0]["source_bitstream"], Path(args.bitstream))
+
+            failed = module.run_program_only(
+                args,
+                program_executor=lambda **kwargs: (_ for _ in ()).throw(TimeoutError("mutex busy")),
+            )
+            self.assertEqual(failed["status"], "fail_programmer_exception")
+            self.assertEqual(failed["attempt_count"], 0)
+            self.assertIn("mutex busy", failed["error"])
+
+    def test_collect_only_is_diagnostic_and_never_fresh_epoch_eligible(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            args = self.make_inputs(Path(tmp))
+            calls: list[object] = []
+
+            def fake_collector(collector_args, **kwargs):
+                calls.append((collector_args, kwargs))
+                return {"schema": "prod2u-collector-manifest-v1", "status": "pass"}
+
+            payload = module.run_collect_only(args, collector_runner=fake_collector)
+            self.assertEqual(payload["status"], "diagnostic_complete")
+            self.assertFalse(payload["strict_pass_eligible"])
+            self.assertEqual(len(calls), 1)
+            self.assertNotIn("before_ready", calls[0][1])
+
+    def test_all_enters_collector_before_program_and_validates_raw_bound_evidence(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            args = self.make_inputs(Path(tmp))
+            events: list[str] = []
+            bit_sha = hashlib.sha256(Path(args.bitstream).read_bytes()).hexdigest()
+
+            def fake_programmer(**kwargs):
+                events.append("program")
+                receipt = fake_program_receipt(args.build_id, bit_sha)
+                receipt_path = Path(kwargs["output_dir"]) / "program-sram-receipt.json"
+                receipt_path.parent.mkdir(parents=True, exist_ok=True)
+                receipt_path.write_text(json.dumps(receipt), encoding="utf-8")
+                return receipt
+
+            def fake_collector(collector_args, *, before_ready):
+                events.append("collector_open")
+                program = before_ready()
+                self.assertEqual(program["status"], "pass")
+                events.append("collector_after_program")
+                return {
+                    "schema": "prod2u-collector-manifest-v1",
+                    "status": "pass",
+                    "startup_ready": {"decoded": {"build_id": args.build_id}},
+                }
+
+            assembled = {"schema": "prod2u-evidence-manifest-v1", "status": "blocked_bmc_replay_not_run"}
+            validator_calls: list[dict] = []
+
+            def fake_validator(**kwargs):
+                validator_calls.append(kwargs)
+                return assembled
+
+            payload = module.run_all(
+                args,
+                program_executor=fake_programmer,
+                collector_runner=fake_collector,
+                evidence_validator=fake_validator,
+            )
+            self.assertEqual(events, ["collector_open", "program", "collector_after_program"])
+            self.assertEqual(payload["status"], "blocked_bmc_replay_not_run")
+            self.assertEqual(len(validator_calls), 1)
+            self.assertEqual(validator_calls[0]["collector_dir"], Path(args.output_dir) / "collector")
+            self.assertEqual(validator_calls[0]["bmc_replay_receipt_path"], Path(args.bmc_replay_receipt))
+            self.assertTrue((Path(args.output_dir) / "prod2u-evidence-manifest.json").is_file())
+
+    def test_all_rejects_reused_before_ready_callback_without_second_program(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            args = self.make_inputs(Path(tmp))
+            calls: list[dict] = []
+            bit_sha = hashlib.sha256(Path(args.bitstream).read_bytes()).hexdigest()
+
+            def fake_programmer(**kwargs):
+                calls.append(kwargs)
+                receipt = fake_program_receipt(args.build_id, bit_sha)
+                receipt_path = Path(kwargs["output_dir"]) / "program-sram-receipt.json"
+                receipt_path.parent.mkdir(parents=True, exist_ok=True)
+                receipt_path.write_text(json.dumps(receipt), encoding="utf-8")
+                return receipt
+
+            def fake_collector(collector_args, *, before_ready):
+                first = before_ready()
+                second = before_ready()
+                self.assertEqual(first["status"], "pass")
+                self.assertEqual(second["status"], "fail_programmer_callback_reused")
+                return {"schema": "prod2u-collector-manifest-v1", "status": "pass"}
+
+            payload = module.run_all(
+                args,
+                program_executor=fake_programmer,
+                collector_runner=fake_collector,
+                evidence_validator=lambda **kwargs: self.fail("validator must not run after callback reuse"),
+            )
+
+            self.assertEqual(payload["status"], "fail_programmer_callback_reused")
+            self.assertEqual(len(calls), 1)
+
+    def test_all_rejects_persisted_program_receipt_that_differs_from_callback_result(self) -> None:
+        module = load_module()
+        with tempfile.TemporaryDirectory() as tmp:
+            args = self.make_inputs(Path(tmp))
+            bit_sha = hashlib.sha256(Path(args.bitstream).read_bytes()).hexdigest()
+
+            def fake_programmer(**kwargs):
+                in_memory = fake_program_receipt(args.build_id, bit_sha)
+                persisted = json.loads(json.dumps(in_memory))
+                persisted["request"]["attempt_limit"] = True
+                receipt_path = Path(kwargs["output_dir"]) / "program-sram-receipt.json"
+                receipt_path.parent.mkdir(parents=True, exist_ok=True)
+                receipt_path.write_text(json.dumps(persisted), encoding="utf-8")
+                return in_memory
+
+            def fake_collector(collector_args, *, before_ready):
+                self.assertEqual(before_ready()["status"], "pass")
+                return {"schema": "prod2u-collector-manifest-v1", "status": "pass"}
+
+            payload = module.run_all(
+                args,
+                program_executor=fake_programmer,
+                collector_runner=fake_collector,
+                evidence_validator=lambda **kwargs: self.fail("validator must not run for a receipt mismatch"),
+            )
+
+            self.assertEqual(payload["status"], "fail_programmer_receipt_mismatch")
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 461 - 0
tests/unit/test_prod2u_package.py

@@ -0,0 +1,461 @@
+#!/usr/bin/env python3
+"""Package-level tests for the active Prod2U delivery."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+import zipfile
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(ROOT / "tools"))
+from prod2u_build_identity import build_source_manifest  # noqa: E402
+PACKAGER = ROOT / "tools" / "package_prod2u.ps1"
+
+
+def sha256(path: Path) -> str:
+    return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+class Prod2UPackageTests(unittest.TestCase):
+    def test_packager_rejects_legacy_j6_bmc_payload_before_packaging(self) -> None:
+        legacy_payload = ROOT / "receipts" / "bmc_replay_payload_production_two_uart_20260710T0805Z.json"
+        result = subprocess.run(
+            [
+                "powershell.exe",
+                "-NoProfile",
+                "-ExecutionPolicy",
+                "Bypass",
+                "-File",
+                str(PACKAGER),
+                "-OutputDir",
+                str(ROOT / "tmp" / "prod2u-invalid-payload-package"),
+                "-Bitstream",
+                str(ROOT / "tmp" / "missing.bit"),
+                "-TdReceipt",
+                str(ROOT / "tmp" / "missing-td.json"),
+                "-SourceManifest",
+                str(ROOT / "tmp" / "missing-source-manifest.json"),
+                "-BmcReplayPayload",
+                str(legacy_payload),
+            ],
+            cwd=ROOT,
+            capture_output=True,
+            text=True,
+            check=False,
+        )
+
+        self.assertNotEqual(result.returncode, 0)
+        self.assertIn("BMC replay payload validation failed", result.stderr + result.stdout)
+
+    def test_packager_creates_short_selftesting_directory_and_zip(self) -> None:
+        self.assertTrue(PACKAGER.is_file(), PACKAGER)
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            bit = temp / "input.bit"
+            bit.write_bytes(b"prod2u-test-bit")
+            identity_source = temp / "identity-source.v"
+            identity_source.write_text("module identity_source; endmodule\n", encoding="ascii")
+            identity = build_source_manifest(
+                root=temp,
+                inputs=[identity_source],
+                profile="prod2u-bmc-replay-binary921",
+                td_version="6.2.2.198412",
+            )
+            build_id = str(identity["build_id"])
+            source_hash = str(identity["source_manifest_sha256"])
+            source_manifest = temp / "source-manifest.json"
+            source_manifest.write_text(json.dumps(identity), encoding="utf-8")
+            td = temp / "td.json"
+            td.write_text(
+                json.dumps(
+                    {
+                        "schema": "prod2u-td-build-receipt-v1",
+                        "status": "pass",
+                        "top": "prod2u_bmc_replay_binary921",
+                        "pin_profile": "prod2u-bmc-replay-binary921",
+                        "top_module": "prod2u_bmc_replay_binary921_top",
+                        "build_identity": {
+                            "status": "pass",
+                            "build_id": build_id,
+                            "source_manifest_sha256": source_hash,
+                            "staged_manifest_sha256": "f" * 64,
+                        },
+                        "bitstream": {"path": str(bit), "size": bit.stat().st_size, "sha256": sha256(bit)},
+                        "source_manifest_sha256": source_hash,
+                        "build_id": build_id,
+                        "resources": {},
+                        "timing": {},
+                        "timing_gate": {"status": "pass"},
+                        "syn": {"returncode": 0, "log_has_error": False},
+                        "phy": {"returncode": 0, "log_has_error": False},
+                        "por_initialization": {
+                            "status": "pass",
+                            "por_cycles": 1024,
+                            "counter_width": 10,
+                            "expected_init": "0",
+                            "register_count": 11,
+                            "failures": [],
+                        },
+                    }
+                ),
+                encoding="utf-8",
+            )
+            bmc = ROOT / "receipts" / "prod2u_bmc_replay_payload_real_capture_20260711.json"
+            out = temp / "out"
+            result = subprocess.run(
+                [
+                    "powershell.exe",
+                    "-NoProfile",
+                    "-ExecutionPolicy",
+                    "Bypass",
+                    "-File",
+                    str(PACKAGER),
+                    "-OutputDir",
+                    str(out),
+                    "-Bitstream",
+                    str(bit),
+                    "-TdReceipt",
+                    str(td),
+                    "-SourceManifest",
+                    str(source_manifest),
+                    "-BmcReplayPayload",
+                    str(bmc),
+                ],
+                cwd=ROOT,
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(result.returncode, 0, result.stderr + result.stdout)
+
+            package = out / f"prod2u-{build_id}"
+            archive = out / f"prod2u-{build_id}.zip"
+            self.assertTrue(package.is_dir())
+            self.assertTrue(archive.is_file())
+            for name in (
+                "fw.bit",
+                "prod2u.ps1",
+                "prod2u_collector.py",
+                "prod2u_validate.py",
+                "prod2u_bmc_replay.py",
+                "prod2u_programmer.py",
+                "START-HERE.zh-CN.md",
+                "prod2u-program-sram-runbook.zh-CN.md",
+                "images/prod2u-con77-con78-rs232-schematic.png",
+                "manifest.json",
+                "source-manifest.json",
+                "td.json",
+                "bmc-replay-payload.json",
+                "sha256-inventory.json",
+            ):
+                with self.subTest(name=name):
+                    self.assertTrue((package / name).is_file(), name)
+
+            start_here = (package / "START-HERE.zh-CN.md").read_text(encoding="utf-8-sig")
+            runbook = (package / "prod2u-program-sram-runbook.zh-CN.md").read_text(encoding="utf-8-sig")
+            self.assertIn("生产温控板", start_here)
+            self.assertIn("CON78 电气针序", start_here)
+            self.assertIn("pin1=`RS232_TX2`", start_here)
+            self.assertIn("必须使用 USB-RS232 适配器", start_here)
+            self.assertIn("禁止把 USB-TTL 适配器直接接到 CON77/CON78", start_here)
+            self.assertIn("prod2u_bmc_replay.py replay", start_here)
+            self.assertIn(
+                f"--receipt ..\\prod2u-{build_id}-runtime\\bmc-replay-session.json",
+                start_here,
+            )
+            self.assertIn(f"-OutputDir ..\\prod2u-{build_id}-evidence", start_here)
+            self.assertNotIn("-OutputDir .\\evidence-prod2u", start_here)
+            self.assertIn("READY payload 固定为 7 字节", runbook)
+            self.assertIn("preflight 不打开 AL-Link", runbook)
+            self.assertIn("先保存 raw", runbook)
+            self.assertIn("Prod2U 子 gate", runbook)
+            self.assertIn("final-gate-v2", runbook)
+            self.assertIn("UART2 从生产板 `CON78` 引出", runbook)
+            self.assertIn("UART1 从生产板 `CON77` 引出", runbook)
+            self.assertIn("不能接 USB-TTL", runbook)
+            self.assertIn("images/prod2u-con77-con78-rs232-schematic.png", start_here)
+            self.assertIn("images/prod2u-con77-con78-rs232-schematic.png", runbook)
+
+            manifest = json.loads((package / "manifest.json").read_text(encoding="utf-8-sig"))
+            self.assertEqual(manifest["schema"], "prod2u-package-manifest-v1")
+            self.assertEqual(manifest["profile"], "prod2u-bmc-replay-binary921")
+            self.assertEqual(manifest["build_identity"]["build_id"], build_id)
+            self.assertEqual(manifest["bitstream"]["path"], "fw.bit")
+            self.assertEqual(manifest["jtag_programming"]["speed_code"], 2)
+            self.assertEqual(manifest["jtag_programming"]["speed_hz"], 200000)
+            self.assertFalse(manifest["jtag_programming"]["power_cycle_required"])
+            self.assertEqual(manifest["jtag_programming"]["attempt_limit"], 1)
+            self.assertTrue(manifest["startup_chain"]["automatic_program_sram"])
+            self.assertEqual(manifest["startup_chain"]["ready_payload_bytes"], 7)
+            self.assertFalse(manifest["startup_chain"]["preflight_opens_al_link"])
+            self.assertEqual(manifest["startup_chain"]["evidence_order"], "raw-first")
+            self.assertEqual(manifest["repository_gate"]["name"], "final-gate-v2")
+            self.assertEqual(manifest["repository_gate"]["role"], "prod2u_subgate_input")
+            self.assertEqual(manifest["ports"]["combined_host_debug"]["board_connector"], "CON78")
+            self.assertEqual(manifest["ports"]["combined_host_debug"]["external_level"], "RS232")
+            self.assertEqual(manifest["ports"]["combined_host_debug"]["connector_pins"]["tx"], 1)
+            self.assertEqual(manifest["ports"]["combined_host_debug"]["connector_pins"]["rx"], 2)
+            self.assertEqual(manifest["ports"]["bmc_replay"]["board_connector"], "CON77")
+            self.assertEqual(manifest["ports"]["bmc_replay"]["external_level"], "RS232")
+            self.assertEqual(
+                manifest["documentation"]["schematic_source_sha256"],
+                "caabc66444c7b9d59682155f5971c3eb635033a846e478930700237b8104fc64",
+            )
+            self.assertEqual(
+                manifest["documentation"]["uart_connector_image_sha256"],
+                sha256(package / "images" / "prod2u-con77-con78-rs232-schematic.png"),
+            )
+
+            replay_payload = json.loads((package / "bmc-replay-payload.json").read_text(encoding="utf-8-sig"))
+            self.assertEqual(replay_payload["schema"], "prod2u-bmc-replay-payload-v1")
+            replay_dry_run = subprocess.run(
+                [
+                    sys.executable,
+                    "-B",
+                    str(package / "prod2u_bmc_replay.py"),
+                    "replay",
+                    "--port",
+                    "COM1",
+                    "--payload",
+                    str(package / "bmc-replay-payload.json"),
+                    "--iterations",
+                    "1",
+                    "--timeout-sec",
+                    "0.1",
+                    "--dry-run",
+                    "--json",
+                ],
+                cwd=package,
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(replay_dry_run.returncode, 0, replay_dry_run.stderr + replay_dry_run.stdout)
+            self.assertEqual(json.loads(replay_dry_run.stdout)["status"], "pass")
+
+            combined_text = "\n".join(
+                path.read_text(encoding="utf-8", errors="ignore")
+                for path in package.rglob("*")
+                if path.is_file() and path.suffix.lower() in {".ps1", ".py", ".json", ".md"}
+            )
+            self.assertNotIn("Set-ExecutionPolicy", combined_text)
+            self.assertNotIn("PROGRAM_FLASH", combined_text)
+            self.assertNotIn("ERASE_FLASH", combined_text)
+            self.assertNotIn("PROGRAM_SPIBIN", combined_text)
+            self.assertNotIn("DIRECT_FLASH_WRITE", combined_text)
+            self.assertNotIn("pip install", combined_text.lower())
+            self.assertNotIn("serial.tools.list_ports", combined_text)
+            self.assertNotIn("Get-CimInstance Win32_SerialPort", combined_text)
+            self.assertNotIn(".dtr = True", combined_text)
+            self.assertNotIn(".rts = True", combined_text)
+
+            inventory = json.loads((package / "sha256-inventory.json").read_text(encoding="utf-8-sig"))
+            inventory_paths = {row["path"] for row in inventory["inventory"]}
+            for required in (
+                "fw.bit",
+                "prod2u_validate.py",
+                "prod2u-program-sram-runbook.zh-CN.md",
+                "images/prod2u-con77-con78-rs232-schematic.png",
+                "schemas/prod2u_program_sram_receipt.schema.json",
+                "schemas/prod2u_evidence_manifest.schema.json",
+                "schemas/prod2u_final_gate.schema.json",
+                "schemas/prod2u_td_build_receipt.schema.json",
+            ):
+                self.assertIn(required, inventory_paths)
+            for row in inventory["inventory"]:
+                artifact = package / Path(row["path"])
+                self.assertEqual(artifact.stat().st_size, row["size"], row["path"])
+                self.assertEqual(sha256(artifact), row["sha256"], row["path"])
+
+            sidecar = out / f"prod2u-{build_id}.zip.sha256.txt"
+            self.assertTrue(sidecar.is_file())
+            self.assertEqual(sidecar.read_text(encoding="ascii").split()[0], sha256(archive))
+
+            selftest = subprocess.run(
+                ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", ".\\prod2u.ps1", "selftest"],
+                cwd=package,
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(selftest.returncode, 0, selftest.stderr + selftest.stdout)
+            self.assertIn('"status": "pass"', selftest.stdout)
+            self.assertFalse((package / "__pycache__").exists())
+
+            fake_td = temp / "TD"
+            (fake_td / "bin").mkdir(parents=True)
+            (fake_td / "bin" / "bw_commands_prompt.exe").write_bytes(b"fixture")
+
+            def run_preflight(cwd: Path) -> subprocess.CompletedProcess[str]:
+                return subprocess.run(
+                    [
+                        "powershell.exe",
+                        "-NoProfile",
+                        "-ExecutionPolicy",
+                        "Bypass",
+                        "-File",
+                        ".\\prod2u.ps1",
+                        "preflight",
+                        "-CombinedPort",
+                        "COM5",
+                        "-Bitstream",
+                        ".\\fw.bit",
+                        "-TdReceipt",
+                        ".\\td.json",
+                        "-SourceManifest",
+                        ".\\source-manifest.json",
+                        "-BmcReplayReceipt",
+                        ".\\bmc-replay-session.json",
+                        "-OutputDir",
+                        ".\\evidence-preflight",
+                        "-TdRoot",
+                        str(fake_td),
+                    ],
+                    cwd=cwd,
+                    capture_output=True,
+                    text=True,
+                    check=False,
+                )
+
+            package_preflight = run_preflight(package)
+            self.assertEqual(package_preflight.returncode, 0, package_preflight.stderr + package_preflight.stdout)
+            self.assertIn('"status": "pass"', package_preflight.stdout)
+            preflight = json.loads(package_preflight.stdout)
+            self.assertFalse(preflight["hardware_opened"])
+            self.assertFalse(preflight["program_sram_attempted"])
+
+            tampered_directory_file = package / "prod2u_validate.py"
+            original_directory_bytes = tampered_directory_file.read_bytes()
+            tampered_directory_file.write_bytes(bytes([original_directory_bytes[0] ^ 1]) + original_directory_bytes[1:])
+            tampered_directory_preflight = run_preflight(package)
+            self.assertNotEqual(tampered_directory_preflight.returncode, 0)
+            tampered_directory_payload = json.loads(tampered_directory_preflight.stdout)
+            self.assertEqual(tampered_directory_payload["status"], "fail_preflight")
+            self.assertIn(
+                "package_inventory_sha256_mismatch:prod2u_validate.py",
+                tampered_directory_payload["failures"],
+            )
+            self.assertFalse(tampered_directory_payload["hardware_opened"])
+            self.assertFalse(tampered_directory_payload["program_sram_attempted"])
+            tampered_directory_file.write_bytes(original_directory_bytes)
+
+            unzip = temp / "unzip"
+            with zipfile.ZipFile(archive) as handle:
+                names = set(handle.namelist())
+                self.assertIn("prod2u_validate.py", names)
+                self.assertIn("prod2u-program-sram-runbook.zh-CN.md", names)
+                self.assertIn("images/prod2u-con77-con78-rs232-schematic.png", names)
+                self.assertIn("schemas/prod2u_td_build_receipt.schema.json", names)
+                handle.extractall(unzip)
+            unzip_test = subprocess.run(
+                ["powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", ".\\prod2u.ps1", "selftest"],
+                cwd=unzip,
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertEqual(unzip_test.returncode, 0, unzip_test.stderr + unzip_test.stdout)
+            unzip_preflight = run_preflight(unzip)
+            self.assertEqual(unzip_preflight.returncode, 0, unzip_preflight.stderr + unzip_preflight.stdout)
+
+            tampered_zip_file = unzip / "prod2u_collector.py"
+            original_zip_bytes = tampered_zip_file.read_bytes()
+            tampered_zip_file.write_bytes(bytes([original_zip_bytes[0] ^ 1]) + original_zip_bytes[1:])
+            tampered_zip_preflight = run_preflight(unzip)
+            self.assertNotEqual(tampered_zip_preflight.returncode, 0)
+            tampered_zip_payload = json.loads(tampered_zip_preflight.stdout)
+            self.assertEqual(tampered_zip_payload["status"], "fail_preflight")
+            self.assertIn(
+                "package_inventory_sha256_mismatch:prod2u_collector.py",
+                tampered_zip_payload["failures"],
+            )
+            self.assertFalse(tampered_zip_payload["hardware_opened"])
+            self.assertFalse(tampered_zip_payload["program_sram_attempted"])
+
+            bad_td = json.loads(td.read_text(encoding="utf-8"))
+            bad_td["timing_gate"] = {"status": "fail"}
+            td.write_text(json.dumps(bad_td), encoding="utf-8")
+            bad_package = subprocess.run(
+                [
+                    "powershell.exe", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(PACKAGER),
+                    "-OutputDir", str(temp / "bad-out"), "-Bitstream", str(bit), "-TdReceipt", str(td),
+                    "-SourceManifest", str(source_manifest), "-BmcReplayPayload", str(bmc),
+                ],
+                cwd=ROOT,
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            self.assertNotEqual(bad_package.returncode, 0)
+            self.assertIn("TD receipt schema validation failed", bad_package.stderr + bad_package.stdout)
+
+    def test_packager_rejects_td_receipt_without_verified_por_initialization(self) -> None:
+        with tempfile.TemporaryDirectory() as tmp:
+            temp = Path(tmp)
+            bit = temp / "input.bit"
+            bit.write_bytes(b"prod2u-test-bit")
+            identity_source = temp / "identity-source.v"
+            identity_source.write_text("module identity_source; endmodule\n", encoding="ascii")
+            identity = build_source_manifest(
+                root=temp,
+                inputs=[identity_source],
+                profile="prod2u-bmc-replay-binary921",
+                td_version="6.2.2.198412",
+            )
+            source_manifest = temp / "source-manifest.json"
+            source_manifest.write_text(json.dumps(identity), encoding="utf-8")
+            td = temp / "td.json"
+            td.write_text(
+                json.dumps(
+                    {
+                        "schema": "prod2u-td-build-receipt-v1",
+                        "status": "pass",
+                        "pin_profile": "prod2u-bmc-replay-binary921",
+                        "top_module": "prod2u_bmc_replay_binary921_top",
+                        "bitstream": {"sha256": sha256(bit)},
+                        "source_manifest_sha256": identity["source_manifest_sha256"],
+                        "build_id": identity["build_id"],
+                        "por_initialization": {"status": "fail"},
+                    }
+                ),
+                encoding="utf-8",
+            )
+
+            result = subprocess.run(
+                [
+                    "powershell.exe",
+                    "-NoProfile",
+                    "-ExecutionPolicy",
+                    "Bypass",
+                    "-File",
+                    str(PACKAGER),
+                    "-OutputDir",
+                    str(temp / "out"),
+                    "-Bitstream",
+                    str(bit),
+                    "-TdReceipt",
+                    str(td),
+                    "-SourceManifest",
+                    str(source_manifest),
+                    "-BmcReplayPayload",
+                    str(ROOT / "receipts" / "prod2u_bmc_replay_payload_real_capture_20260711.json"),
+                ],
+                cwd=ROOT,
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+
+        self.assertNotEqual(result.returncode, 0)
+        self.assertIn("POR initialization", result.stderr + result.stdout)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 267 - 0
tests/unit/test_prod2u_programmer.py

@@ -0,0 +1,267 @@
+#!/usr/bin/env python3
+"""TDD contract for the offline Prod2U SRAM transcript parser."""
+
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import io
+import json
+import tempfile
+import unittest
+from contextlib import redirect_stdout
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+MODULE_PATH = ROOT / "tools" / "prod2u_programmer.py"
+FIXTURES = ROOT / "tests" / "fixtures" / "prod2u_programmer"
+BUILD_ID = "A1B2C3D4"
+STAGED_PATH = rf"C:\P2U\{BUILD_ID}\fw.bit"
+BITSTREAM_BYTES = b"prod2u offline parser fixture bitstream\n"
+TD_BIN = r"C:\Anlogic\TD_Release_2026.1_SP1.198.412\bin"
+EXPECTED_MARKERS = [
+    "download_start",
+    "chip_validation",
+    "bit_to_vec_start",
+    "bit_to_vec_finish",
+    "program_start",
+    "program_finish",
+    "download_finish",
+]
+
+
+def load_module():
+    if not MODULE_PATH.is_file():
+        raise AssertionError(f"missing Prod2U programmer parser: {MODULE_PATH}")
+    spec = importlib.util.spec_from_file_location("prod2u_programmer", MODULE_PATH)
+    if spec is None or spec.loader is None:
+        raise AssertionError("unable to load Prod2U programmer parser")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+class Prod2UProgrammerTests(unittest.TestCase):
+    def build_receipt(
+        self,
+        module,
+        transcript: str,
+        *,
+        bitstream_path: str = STAGED_PATH,
+        bitstream_sha256: str | None = None,
+        exit_code: int = 0,
+        command_execution_attempted: bool = True,
+        timed_out: bool = False,
+    ) -> dict:
+        return module.build_program_sram_receipt(
+            transcript=transcript,
+            build_id=BUILD_ID,
+            bitstream_path=bitstream_path,
+            bitstream_bytes=BITSTREAM_BYTES,
+            expected_bitstream_sha256=bitstream_sha256 or hashlib.sha256(BITSTREAM_BYTES).hexdigest(),
+            exit_code=exit_code,
+            run_id="parser-unit-test",
+            command_execution_attempted=command_execution_attempted,
+            timed_out=timed_out,
+            td_bin=TD_BIN,
+        )
+
+    def test_success_gui_excerpt_builds_a_schema_valid_sram_only_receipt(self) -> None:
+        module = load_module()
+        transcript = (FIXTURES / "gui_success_excerpt.log").read_text(encoding="utf-8")
+
+        receipt = self.build_receipt(module, transcript)
+
+        self.assertEqual(receipt["schema"], "prod2u-program-sram-receipt-v1")
+        self.assertEqual(receipt["status"], "pass", receipt["parser"]["failures"])
+        self.assertEqual(receipt["bitstream"]["path"], STAGED_PATH)
+        self.assertEqual(receipt["bitstream"]["build_id"], BUILD_ID)
+        self.assertEqual(receipt["request"]["operation"], "PROGRAM_SRAM")
+        self.assertEqual(receipt["request"]["attempt_limit"], 1)
+        self.assertFalse(receipt["request"]["power_cycle_allowed"])
+        self.assertEqual(receipt["execution"]["attempt_count"], 1)
+        self.assertEqual(receipt["execution"]["retry_count"], 0)
+        self.assertEqual(receipt["execution"]["power_cycle_count"], 0)
+        self.assertTrue(receipt["execution"]["command_execution_attempted"])
+        self.assertFalse(receipt["parser"]["exit_code_trusted"])
+        self.assertEqual(receipt["parser"]["ordered_markers"], EXPECTED_MARKERS)
+        self.assertTrue(receipt["parser"]["ordered_markers_complete"])
+        self.assertEqual(receipt["parser"]["error_markers"], [])
+        self.assertFalse(receipt["safety"]["flash_attempted"])
+        self.assertFalse(receipt["safety"]["programs_nonvolatile"])
+        self.assertTrue(receipt["safety"]["external_programming_command_executed"])
+
+    def test_success_cli_excerpt_accepts_the_exact_connect_cable_setup_pair(self) -> None:
+        module = load_module()
+        transcript = (FIXTURES / "cli_success_excerpt.log").read_text(encoding="utf-8")
+
+        receipt = self.build_receipt(module, transcript)
+
+        self.assertEqual(receipt["status"], "pass", receipt["parser"]["failures"])
+        self.assertEqual(
+            receipt["parser"]["setup_markers"],
+            ["connect_cable_start", "connect_cable_finish"],
+        )
+        self.assertEqual(receipt["parser"]["observed_markers"], EXPECTED_MARKERS)
+
+    def test_zero_exit_code_does_not_override_a_missing_bit_to_vec_marker(self) -> None:
+        module = load_module()
+        transcript = (FIXTURES / "missing_bit_to_vec.log").read_text(encoding="utf-8")
+
+        receipt = self.build_receipt(module, transcript, exit_code=0)
+
+        self.assertEqual(receipt["status"], "fail")
+        self.assertFalse(receipt["parser"]["ordered_markers_complete"])
+        self.assertIn("missing_marker:bit_to_vec_start", receipt["parser"]["failures"])
+        self.assertIn("missing_marker:bit_to_vec_finish", receipt["parser"]["failures"])
+
+    def test_parser_rejects_transaction_errors_and_non_sram_actions(self) -> None:
+        module = load_module()
+        success = (FIXTURES / "gui_success_excerpt.log").read_text(encoding="utf-8")
+        wrong_path = success.replace("C:/P2U/A1B2C3D4/fw.bit", "C:/P2U/A1B2C3D4/other.bit")
+        wrong_chip = success.replace("chip EF2L45", "chip EF2L46")
+        wrong_speed = success.replace("-freq 0.200000", "-freq 0.100000")
+        out_of_order = success.replace(
+            'PRG-2014 : Chip validation success: EF2L45\n',
+            '',
+        ) + 'PRG-2014 : Chip validation success: EF2L45\n'
+        cases = {
+            "duplicate": (success + success, {}, "transaction_count_not_one"),
+            "out_of_order": (out_of_order, {}, "out_of_order_marker:chip_validation"),
+            "wrong_path": (wrong_path, {}, "staging_path_mismatch"),
+            "wrong_chip": (wrong_chip, {}, "chip_mismatch"),
+            "wrong_speed": (wrong_speed, {}, "bit_to_vec_frequency_mismatch"),
+            "wrong_hash": (success, {"bitstream_sha256": "0" * 64}, "bitstream_sha256_mismatch"),
+            "tool_error": (success + "\nPRG-8001 ERROR program failed\n", {}, "error_marker:PRG-8001"),
+            "forbidden_spi": (success + "\nSPI erase requested\n", {}, "forbidden_action:erase"),
+        }
+
+        for name, (transcript, kwargs, expected_failure) in cases.items():
+            with self.subTest(name=name):
+                receipt = self.build_receipt(module, transcript, **kwargs)
+                self.assertNotEqual(receipt["status"], "pass")
+                self.assertIn(expected_failure, receipt["parser"]["failures"])
+
+        forbidden = self.build_receipt(module, success + "\n" + ("program" + "_flash").upper() + "\n")
+        self.assertEqual(forbidden["status"], "fail_forbidden_action")
+
+    def test_parser_rejects_tcl_script_load_error_even_with_exit_zero(self) -> None:
+        module = load_module()
+        receipt = self.build_receipt(
+            module,
+            'couldn\'t read file "C:broken\\program-sram.tcl": no such file or directory\n',
+            exit_code=0,
+        )
+
+        self.assertEqual(receipt["status"], "fail")
+        self.assertIn("error_marker:couldn't read file", receipt["parser"]["failures"])
+
+    def test_parser_rejects_every_unrecognized_run_operation(self) -> None:
+        module = load_module()
+        success = (FIXTURES / "gui_success_excerpt.log").read_text(encoding="utf-8")
+        cases = (
+            ('RUN-1002 : start command "report_qor -step gate"', "unrecognized_run_operation:report_qor"),
+            ('RUN-1003 : finish command "connect_cable -allink" in 0.010000s wall', "connect_cable_marker_mismatch"),
+            ('RUN-1002 : start command "   "', "unrecognized_run_operation:<empty>"),
+        )
+
+        for extra_line, expected_failure in cases:
+            with self.subTest(extra_line=extra_line):
+                try:
+                    receipt = self.build_receipt(module, success + extra_line + "\n")
+                except Exception as exc:  # pragma: no cover - assertion reports parser crashes clearly
+                    self.fail(f"unrecognized RUN operation raised {type(exc).__name__}: {exc}")
+                self.assertEqual(receipt["status"], "fail")
+                self.assertIn(expected_failure, receipt["parser"]["failures"])
+
+    def test_parser_requires_exactly_one_of_each_transaction_operation(self) -> None:
+        module = load_module()
+        success = (FIXTURES / "gui_success_excerpt.log").read_text(encoding="utf-8")
+        program_start = 'RUN-1002 : start command "program -cable 0 -mode svf -spd 2 -p"\n'
+        program_finish = (
+            'RUN-1003 : finish command "program -cable 0 -mode svf -spd 2 -p" '
+            "in 10.450000s wall\n"
+        )
+        duplicate_program = success.replace(program_start, program_start + program_finish + program_start)
+
+        receipt = self.build_receipt(module, duplicate_program)
+
+        self.assertEqual(receipt["status"], "fail")
+        self.assertIn("transaction_count_not_one", receipt["parser"]["failures"])
+
+    def test_exit_zero_cannot_pass_without_real_execution_or_after_timeout(self) -> None:
+        module = load_module()
+        success = (FIXTURES / "gui_success_excerpt.log").read_text(encoding="utf-8")
+
+        not_executed = self.build_receipt(module, success, command_execution_attempted=False)
+        self.assertEqual(not_executed["status"], "fail")
+        self.assertIn("program_command_not_executed", not_executed["parser"]["failures"])
+
+        timed_out = self.build_receipt(module, success, timed_out=True)
+        self.assertEqual(timed_out["status"], "fail")
+        self.assertIn("program_timeout", timed_out["parser"]["failures"])
+
+    def test_generated_tcl_is_exactly_one_sram_download_at_200khz(self) -> None:
+        module = load_module()
+
+        tcl = module.build_program_tcl(STAGED_PATH)
+
+        self.assertEqual(
+            tcl,
+            "connect_cable -allink\n"
+            "download -bit {C:/P2U/A1B2C3D4/fw.bit} -mode jtag -spd 2 -cable 0\n"
+            "exit\n",
+        )
+        self.assertEqual(tcl.count("download "), 1)
+        self.assertNotIn("flash", tcl.lower())
+        self.assertNotIn("erase", tcl.lower())
+        self.assertNotIn("spi", tcl.lower())
+
+    def test_staging_path_comparison_accepts_equivalent_windows_slashes(self) -> None:
+        module = load_module()
+        transcript = (FIXTURES / "gui_success_excerpt.log").read_text(encoding="utf-8")
+
+        receipt = self.build_receipt(
+            module,
+            transcript,
+            bitstream_path="C:/P2U/A1B2C3D4/fw.bit",
+        )
+
+        self.assertEqual(receipt["status"], "pass", receipt["parser"]["failures"])
+
+    def test_cli_writes_an_offline_failure_receipt_for_a_non_staged_bitstream(self) -> None:
+        module = load_module()
+        transcript = FIXTURES / "gui_success_excerpt.log"
+        with tempfile.TemporaryDirectory() as root_text:
+            root = Path(root_text)
+            bitstream = root / "fw.bit"
+            bitstream.write_bytes(BITSTREAM_BYTES)
+            receipt_path = root / "receipt.json"
+            stdout = io.StringIO()
+            with redirect_stdout(stdout):
+                exit_code = module.main(
+                    [
+                        "--transcript",
+                        str(transcript),
+                        "--bitstream",
+                        str(bitstream),
+                        "--build-id",
+                        BUILD_ID,
+                        "--sha256",
+                        hashlib.sha256(BITSTREAM_BYTES).hexdigest(),
+                        "--run-id",
+                        "cli-unit-test",
+                        "--receipt",
+                        str(receipt_path),
+                    ]
+                )
+
+            receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
+            self.assertEqual(exit_code, 1)
+            self.assertEqual(receipt["status"], "fail")
+            self.assertIn("staging_path_mismatch", receipt["parser"]["failures"])
+            self.assertEqual(json.loads(stdout.getvalue())["run_id"], "cli-unit-test")
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 476 - 0
tests/unit/test_prod2u_programmer_runtime.py

@@ -0,0 +1,476 @@
+#!/usr/bin/env python3
+"""TDD coverage for the live-capable Prod2U PROGRAM_SRAM runner boundary."""
+
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import copy
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+import uuid
+from pathlib import Path
+
+import jsonschema
+
+
+ROOT = Path(__file__).resolve().parents[2]
+MODULE_PATH = ROOT / "tools" / "prod2u_programmer.py"
+FIXTURE = ROOT / "tests" / "fixtures" / "prod2u_programmer" / "gui_success_excerpt.log"
+CLI_FIXTURE = ROOT / "tests" / "fixtures" / "prod2u_programmer" / "cli_success_excerpt.log"
+BITSTREAM_BYTES = b"prod2u runtime fixture bitstream\n"
+
+
+def load_module():
+    spec = importlib.util.spec_from_file_location("prod2u_programmer_runtime", MODULE_PATH)
+    if spec is None or spec.loader is None:
+        raise AssertionError("unable to load Prod2U programmer")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+class FakeMutex:
+    def __init__(self, acquired: bool = True) -> None:
+        self.acquired = acquired
+        self.entered = False
+
+    def __enter__(self):
+        self.entered = True
+        if not self.acquired:
+            raise TimeoutError("mutex busy")
+        return self
+
+    def __exit__(self, exc_type, exc, tb):
+        return False
+
+
+class Prod2UProgrammerRuntimeTests(unittest.TestCase):
+    def test_cleanup_targets_stale_bitwriter_cli_but_not_td_cli_or_hwserver(self) -> None:
+        source = MODULE_PATH.read_text(encoding="utf-8")
+
+        self.assertIn("'bw_commands_prompt'", source)
+        allowed_line = next(line for line in source.splitlines() if "$allowed = @(" in line)
+        self.assertNotIn("td_commands_prompt", allowed_line)
+        self.assertNotIn("hwserver", allowed_line)
+
+    def test_cleanup_td_root_match_requires_a_path_component_boundary(self) -> None:
+        source = MODULE_PATH.read_text(encoding="utf-8")
+
+        self.assertIn("$rootWithSeparator = $root + [System.IO.Path]::DirectorySeparatorChar", source)
+        self.assertIn(".StartsWith($rootWithSeparator, [System.StringComparison]::OrdinalIgnoreCase)", source)
+        self.assertNotIn(".StartsWith($root, [System.StringComparison]::OrdinalIgnoreCase)", source)
+
+    def setUp(self) -> None:
+        self.module = load_module()
+        self.build_id = uuid.uuid4().hex[:8].upper()
+        self.source_root = tempfile.TemporaryDirectory()
+        self.output_root = tempfile.TemporaryDirectory()
+        self.td_root = tempfile.TemporaryDirectory()
+        self.source_bit = Path(self.source_root.name) / "source.bit"
+        self.source_bit.write_bytes(BITSTREAM_BYTES)
+        self.expected_sha256 = hashlib.sha256(BITSTREAM_BYTES).hexdigest()
+        self.output_dir = Path(self.output_root.name)
+        self.td_root_path = Path(self.td_root.name)
+        self.td_bin = self.td_root_path / "bin"
+        self.log_dir = self.td_bin / "log"
+        self.log_dir.mkdir(parents=True)
+        self.bw_exe = self.td_bin / "bw_commands_prompt.exe"
+        self.bw_exe.write_bytes(b"fixture executable placeholder")
+
+    def tearDown(self) -> None:
+        staged = Path(self.module.staged_bitstream_path(self.build_id))
+        if staged.is_file():
+            staged.unlink()
+        if staged.parent.is_dir():
+            staged.parent.rmdir()
+        self.source_root.cleanup()
+        self.output_root.cleanup()
+        self.td_root.cleanup()
+
+    def success_log(self) -> str:
+        staged_forward = self.module.staged_bitstream_path(self.build_id).replace("\\", "/")
+        return FIXTURE.read_text(encoding="utf-8").replace(
+            "C:/P2U/A1B2C3D4/fw.bit",
+            staged_forward,
+        )
+
+    def cli_success_log(self) -> str:
+        staged_forward = self.module.staged_bitstream_path(self.build_id).replace("\\", "/")
+        return CLI_FIXTURE.read_text(encoding="utf-8").replace(
+            "C:/P2U/A1B2C3D4/fw.bit",
+            staged_forward,
+        )
+
+    def cleanup_result(self) -> dict:
+        return {
+            "td_root": str(self.td_root_path),
+            "graceful_close_requested": ["bw.exe:101"],
+            "forced_terminated": [],
+            "wait_seconds": 5.0,
+            "remaining": [],
+            "status": "pass",
+        }
+
+    def test_runner_stages_hashes_executes_once_and_parses_only_new_log_bytes(self) -> None:
+        old_log = self.log_dir / "bw_existing.log"
+        old_log.write_text("PRG-8002 ERROR stale historical failure\n", encoding="utf-8")
+        calls: list[dict] = []
+
+        def fake_runner(command, *, cwd, timeout, capture_output, text, check):
+            calls.append({"command": command, "cwd": cwd, "timeout": timeout})
+            old_log.write_text(
+                old_log.read_text(encoding="utf-8") + self.success_log(),
+                encoding="utf-8",
+            )
+            return subprocess.CompletedProcess(command, 0, stdout="bw > ", stderr="")
+
+        receipt = self.module.execute_program_sram(
+            source_bitstream=self.source_bit,
+            expected_bitstream_sha256=self.expected_sha256,
+            build_id=self.build_id,
+            output_dir=self.output_dir,
+            td_root=self.td_root_path,
+            run_id="runtime-pass",
+            process_runner=fake_runner,
+            cleanup_runner=lambda _td_root: self.cleanup_result(),
+            mutex_factory=lambda: FakeMutex(),
+        )
+
+        staged = Path(self.module.staged_bitstream_path(self.build_id))
+        self.assertEqual(staged.read_bytes(), BITSTREAM_BYTES)
+        self.assertEqual(receipt["status"], "pass", receipt["parser"]["failures"])
+        self.assertEqual(receipt["execution"]["attempt_count"], 1)
+        self.assertEqual(receipt["execution"]["retry_count"], 0)
+        self.assertEqual(receipt["execution"]["timeout_seconds"], 60)
+        self.assertTrue(receipt["execution"]["command_execution_attempted"])
+        self.assertTrue(receipt["mutex"]["acquired"])
+        self.assertEqual(receipt["process_cleanup"]["wait_seconds"], 5.0)
+        self.assertEqual(len(calls), 1)
+        self.assertEqual(calls[0]["timeout"], 60)
+        self.assertEqual(Path(calls[0]["command"][0]), self.bw_exe)
+        self.assertEqual(Path(calls[0]["command"][1]), self.output_dir / "program-sram.tcl")
+        self.assertEqual(
+            calls[0]["command"][1],
+            (self.output_dir / "program-sram.tcl").absolute().as_posix(),
+        )
+        self.assertNotIn("\\", calls[0]["command"][1])
+        self.assertNotIn("stale historical failure", (self.output_dir / "bitwriter-log-delta.log").read_text(encoding="utf-8"))
+        self.assertEqual(receipt["artifacts"]["tcl"]["sha256"], hashlib.sha256((self.output_dir / "program-sram.tcl").read_bytes()).hexdigest())
+        self.assertEqual(receipt["artifacts"]["log_delta"]["sha256"], hashlib.sha256((self.output_dir / "bitwriter-log-delta.log").read_bytes()).hexdigest())
+
+        schema = json.loads((ROOT / "schemas" / "prod2u_program_sram_receipt.schema.json").read_text(encoding="utf-8"))
+        jsonschema.validate(receipt, schema)
+        contradictions = (
+            ("execution", "timed_out", True),
+            ("execution", "command_execution_attempted", False),
+            ("parser", "status", "fail"),
+            ("staging", "matches_expected_path", False),
+            ("safety", "flash_attempted", True),
+        )
+        for section, key, value in contradictions:
+            with self.subTest(schema_contradiction=f"{section}.{key}"):
+                invalid = copy.deepcopy(receipt)
+                invalid[section][key] = value
+                with self.assertRaises(jsonschema.ValidationError):
+                    jsonschema.validate(invalid, schema)
+
+    def test_zero_exit_without_new_transaction_log_fails_closed(self) -> None:
+        (self.log_dir / "bw_existing.log").write_text(self.success_log(), encoding="utf-8")
+
+        receipt = self.module.execute_program_sram(
+            source_bitstream=self.source_bit,
+            expected_bitstream_sha256=self.expected_sha256,
+            build_id=self.build_id,
+            output_dir=self.output_dir,
+            td_root=self.td_root_path,
+            run_id="runtime-no-delta",
+            process_runner=lambda command, **kwargs: subprocess.CompletedProcess(command, 0, stdout="bw > ", stderr=""),
+            cleanup_runner=lambda _td_root: self.cleanup_result(),
+            mutex_factory=lambda: FakeMutex(),
+        )
+
+        self.assertEqual(receipt["status"], "fail")
+        self.assertIn("missing_bitwriter_log_delta", receipt["parser"]["failures"])
+        self.assertFalse(receipt["parser"]["ordered_markers_complete"])
+
+    def test_real_cli_stdout_mirror_and_connect_setup_are_accepted(self) -> None:
+        cli_log = self.cli_success_log()
+
+        def fake_runner(command, **kwargs):
+            (self.log_dir / "bw_cli.log").write_text(cli_log, encoding="utf-8")
+            return subprocess.CompletedProcess(command, 0, stdout=cli_log, stderr="")
+
+        receipt = self.module.execute_program_sram(
+            source_bitstream=self.source_bit,
+            expected_bitstream_sha256=self.expected_sha256,
+            build_id=self.build_id,
+            output_dir=self.output_dir,
+            td_root=self.td_root_path,
+            run_id="runtime-cli-pass",
+            process_runner=fake_runner,
+            cleanup_runner=lambda _td_root: self.cleanup_result(),
+            mutex_factory=lambda: FakeMutex(),
+        )
+
+        self.assertEqual(receipt["status"], "pass", receipt["parser"]["failures"])
+        self.assertTrue(receipt["parser"]["stdout_transaction_mirror"])
+
+    def test_tcl_script_load_failure_from_stdout_is_reported_explicitly(self) -> None:
+        receipt = self.module.execute_program_sram(
+            source_bitstream=self.source_bit,
+            expected_bitstream_sha256=self.expected_sha256,
+            build_id=self.build_id,
+            output_dir=self.output_dir,
+            td_root=self.td_root_path,
+            run_id="runtime-tcl-load-failure",
+            process_runner=lambda command, **kwargs: subprocess.CompletedProcess(
+                command,
+                0,
+                stdout='couldn\'t read file "C:broken\\program-sram.tcl": no such file or directory\nbw > ',
+                stderr="",
+            ),
+            cleanup_runner=lambda _td_root: self.cleanup_result(),
+            mutex_factory=lambda: FakeMutex(),
+        )
+
+        self.assertEqual(receipt["status"], "fail")
+        self.assertIn("error_marker:couldn't read file", receipt["parser"]["failures"])
+
+    def test_exit_zero_with_prg_error_or_multiple_transactions_fails(self) -> None:
+        for name, delta, expected in (
+            ("prg_error", "PRG-8002 ERROR Cannot open file\n", "error_marker:PRG-8002"),
+            ("multiple", self.success_log() + self.success_log(), "transaction_count_not_one"),
+        ):
+            with self.subTest(name=name):
+                output_dir = self.output_dir / name
+
+                def fake_runner(command, **kwargs):
+                    (self.log_dir / f"bw_{name}.log").write_text(delta, encoding="utf-8")
+                    return subprocess.CompletedProcess(command, 0, stdout="bw > ", stderr="")
+
+                receipt = self.module.execute_program_sram(
+                    source_bitstream=self.source_bit,
+                    expected_bitstream_sha256=self.expected_sha256,
+                    build_id=self.build_id,
+                    output_dir=output_dir,
+                    td_root=self.td_root_path,
+                    run_id=f"runtime-{name}",
+                    process_runner=fake_runner,
+                    cleanup_runner=lambda _td_root: self.cleanup_result(),
+                    mutex_factory=lambda: FakeMutex(),
+                )
+                self.assertNotEqual(receipt["status"], "pass")
+                self.assertIn(expected, receipt["parser"]["failures"])
+
+    def test_markers_cannot_be_joined_across_log_sources_or_stdout(self) -> None:
+        success_lines = self.success_log().splitlines()
+        cases = {
+            "split_sources": (
+                "\n".join(success_lines[:3]) + "\n",
+                "\n".join(success_lines[3:]) + "\n",
+                "",
+                "ambiguous_bitwriter_log_sources",
+            ),
+            "stdout_supplement": (
+                "\n".join(success_lines[:-1]) + "\n",
+                "",
+                success_lines[-1] + "\n",
+                "missing_marker:download_finish",
+            ),
+        }
+        for name, (first, second, stdout, expected) in cases.items():
+            with self.subTest(name=name):
+                output_dir = self.output_dir / name
+
+                def fake_runner(command, **kwargs):
+                    (self.log_dir / f"bw_{name}_1.log").write_text(first, encoding="utf-8")
+                    if second:
+                        (self.log_dir / f"bw_{name}_2.log").write_text(second, encoding="utf-8")
+                    return subprocess.CompletedProcess(command, 0, stdout=stdout, stderr="")
+
+                receipt = self.module.execute_program_sram(
+                    source_bitstream=self.source_bit,
+                    expected_bitstream_sha256=self.expected_sha256,
+                    build_id=self.build_id,
+                    output_dir=output_dir,
+                    td_root=self.td_root_path,
+                    run_id=f"runtime-{name}",
+                    process_runner=fake_runner,
+                    cleanup_runner=lambda _td_root: self.cleanup_result(),
+                    mutex_factory=lambda: FakeMutex(),
+                )
+                self.assertNotEqual(receipt["status"], "pass")
+                self.assertIn(expected, receipt["parser"]["failures"])
+
+    def test_partial_or_stderr_transaction_markers_outside_authoritative_log_fail(self) -> None:
+        markers = {
+            "run": 'RUN-1002 : start command "program -cable 0 -mode svf -spd 2 -p"\n',
+            "chip": "PRG-2014 : Chip validation success: EF2L45\n",
+        }
+        for marker_name, marker in markers.items():
+            for stream_name in ("stdout", "stderr"):
+                with self.subTest(marker=marker_name, stream=stream_name):
+                    output_dir = self.output_dir / marker_name / stream_name
+
+                    def fake_runner(command, **kwargs):
+                        (self.log_dir / f"bw_{marker_name}_{stream_name}.log").write_text(
+                            self.success_log(), encoding="utf-8"
+                        )
+                        outputs = {"stdout": "bw > ", "stderr": ""}
+                        outputs[stream_name] = marker
+                        return subprocess.CompletedProcess(command, 0, **outputs)
+
+                    receipt = self.module.execute_program_sram(
+                        source_bitstream=self.source_bit,
+                        expected_bitstream_sha256=self.expected_sha256,
+                        build_id=self.build_id,
+                        output_dir=output_dir,
+                        td_root=self.td_root_path,
+                        run_id=f"runtime-marker-{marker_name}-{stream_name}",
+                        process_runner=fake_runner,
+                        cleanup_runner=lambda _td_root: self.cleanup_result(),
+                        mutex_factory=lambda: FakeMutex(),
+                    )
+
+                    self.assertEqual(receipt["status"], "fail")
+                    self.assertIn(
+                        f"transaction_marker_mismatch:{stream_name}",
+                        receipt["parser"]["failures"],
+                    )
+
+    def test_replaced_log_file_is_not_treated_as_an_append_delta(self) -> None:
+        existing = self.log_dir / "bw_existing.log"
+        existing.write_text("historical\n", encoding="utf-8")
+
+        def fake_runner(command, **kwargs):
+            existing.unlink()
+            existing.write_text(self.success_log(), encoding="utf-8")
+            return subprocess.CompletedProcess(command, 0, stdout="", stderr="")
+
+        receipt = self.module.execute_program_sram(
+            source_bitstream=self.source_bit,
+            expected_bitstream_sha256=self.expected_sha256,
+            build_id=self.build_id,
+            output_dir=self.output_dir / "replaced",
+            td_root=self.td_root_path,
+            run_id="runtime-replaced",
+            process_runner=fake_runner,
+            cleanup_runner=lambda _td_root: self.cleanup_result(),
+            mutex_factory=lambda: FakeMutex(),
+        )
+
+        self.assertEqual(receipt["status"], "fail")
+        self.assertIn("bitwriter_log_replaced_or_truncated", receipt["parser"]["failures"])
+
+    def test_windows_job_runner_kills_spawned_process_tree_on_timeout(self) -> None:
+        if sys.platform != "win32":
+            self.skipTest("Windows Job Object coverage")
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            child_pid_path = root / "child.pid"
+            script = root / "parent.py"
+            script.write_text(
+                "import pathlib, subprocess, sys, time\n"
+                "child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)'])\n"
+                "pathlib.Path(sys.argv[1]).write_text(str(child.pid), encoding='ascii')\n"
+                "time.sleep(60)\n",
+                encoding="ascii",
+            )
+            with self.assertRaises(subprocess.TimeoutExpired):
+                self.module.run_process_in_job(
+                    [sys.executable, str(script), str(child_pid_path)],
+                    cwd=str(root),
+                    timeout=1.0,
+                    capture_output=True,
+                    text=True,
+                    check=False,
+                )
+            startup_deadline = time.monotonic() + 2.0
+            while not child_pid_path.is_file() and time.monotonic() < startup_deadline:
+                time.sleep(0.01)
+            self.assertTrue(child_pid_path.is_file(), "parent did not report the spawned child PID")
+            child_pid = int(child_pid_path.read_text(encoding="ascii"))
+            termination_deadline = time.monotonic() + 2.0
+            while (
+                self.module.windows_process_is_running(child_pid)
+                and time.monotonic() < termination_deadline
+            ):
+                time.sleep(0.01)
+            self.assertFalse(
+                self.module.windows_process_is_running(child_pid),
+                "Job Object did not terminate the spawned child process",
+            )
+
+    def test_td_process_cleanup_accepts_a_normal_absolute_windows_path(self) -> None:
+        if sys.platform != "win32":
+            self.skipTest("Windows PowerShell process cleanup coverage")
+        with tempfile.TemporaryDirectory() as tmp:
+            td_root = Path(tmp) / "TD"
+            td_root.mkdir()
+
+            result = self.module.close_td_processes(td_root)
+
+        self.assertEqual(result["status"], "pass", result)
+        self.assertEqual(Path(result["td_root"]), td_root.resolve())
+        self.assertEqual(result["remaining"], [])
+
+    def test_hash_mismatch_and_busy_mutex_do_not_launch_bitwriter(self) -> None:
+        calls: list[str] = []
+
+        def fake_runner(command, **kwargs):
+            calls.append("called")
+            return subprocess.CompletedProcess(command, 0, stdout="", stderr="")
+
+        with self.assertRaisesRegex(ValueError, "bitstream SHA256 mismatch"):
+            self.module.execute_program_sram(
+                source_bitstream=self.source_bit,
+                expected_bitstream_sha256="0" * 64,
+                build_id=self.build_id,
+                output_dir=self.output_dir / "hash",
+                td_root=self.td_root_path,
+                run_id="runtime-hash",
+                process_runner=fake_runner,
+                cleanup_runner=lambda _td_root: self.cleanup_result(),
+                mutex_factory=lambda: FakeMutex(),
+            )
+        self.assertEqual(calls, [])
+
+        reused = self.output_dir / "reused"
+        reused.mkdir()
+        (reused / "existing.txt").write_text("do not overwrite", encoding="ascii")
+        with self.assertRaisesRegex(FileExistsError, "output directory is not empty"):
+            self.module.execute_program_sram(
+                source_bitstream=self.source_bit,
+                expected_bitstream_sha256=self.expected_sha256,
+                build_id=self.build_id,
+                output_dir=reused,
+                td_root=self.td_root_path,
+                run_id="runtime-reused",
+                process_runner=fake_runner,
+                cleanup_runner=lambda _td_root: self.cleanup_result(),
+                mutex_factory=lambda: FakeMutex(),
+            )
+        self.assertEqual(calls, [])
+
+        with self.assertRaisesRegex(TimeoutError, "mutex busy"):
+            self.module.execute_program_sram(
+                source_bitstream=self.source_bit,
+                expected_bitstream_sha256=self.expected_sha256,
+                build_id=self.build_id,
+                output_dir=self.output_dir / "mutex",
+                td_root=self.td_root_path,
+                run_id="runtime-mutex",
+                process_runner=fake_runner,
+                cleanup_runner=lambda _td_root: self.cleanup_result(),
+                mutex_factory=lambda: FakeMutex(acquired=False),
+            )
+        self.assertEqual(calls, [])
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 147 - 0
tests/unit/test_prod2u_rtl_slice.py

@@ -0,0 +1,147 @@
+#!/usr/bin/env python3
+"""Contract tests for the approved Prod2U reset, pin, and READY RTL slice."""
+
+from __future__ import annotations
+
+import json
+import sys
+import unittest
+from pathlib import Path
+
+
+ROOT = Path(__file__).resolve().parents[2]
+STEM = "prod2u_bmc_replay_binary921"
+TOP = ROOT / "src" / "top" / f"{STEM}_top.v"
+CORE = ROOT / "src" / "rtl" / "binary921_diag_core.v"
+POR = ROOT / "src" / "rtl" / "prod2u_por.v"
+UART_RX = ROOT / "src" / "rtl" / "uart_rx_8n1.v"
+INVENTORY = ROOT / "config" / "pin_inventory.fcb_fpga_mcu0611.json"
+ADC = ROOT / "constraints" / f"{STEM}.adc"
+PROJECT = ROOT / "td" / f"{STEM}.prj"
+SYN_TCL = ROOT / "td" / "syn" / f"{STEM}.tcl"
+PHY_TCL = ROOT / "td" / "phy" / f"{STEM}.tcl"
+
+sys.path.insert(0, str(ROOT / "tools"))
+
+from binary921 import FrameType, decode_frame, encode_frame, frame_to_dict  # noqa: E402
+
+
+class Prod2URtlSliceTests(unittest.TestCase):
+    def test_inventory_records_pdf_page_three_key_and_gpio49_mapping(self) -> None:
+        payload = json.loads(INVENTORY.read_text(encoding="utf-8"))
+        by_ball = {pin["fpga_ball"]: pin for pin in payload["pins"]}
+
+        self.assertEqual(by_ball["N6"]["signal"], "KEY_1")
+        self.assertEqual(by_ball["N6"]["function_net"], "KEY_1")
+        self.assertEqual(by_ball["L7"]["signal"], "RX485_RX")
+        self.assertEqual(by_ball["L7"]["function_net"], "RX485_RX")
+        self.assertEqual(by_ball["L7"]["bank_io_net"], "BANK2_GPIO49")
+        self.assertEqual(by_ball["L7"]["direction"], "input")
+        self.assertTrue(by_ball["L7"]["reserved"])
+        self.assertNotIn("uart", by_ball["L7"]["capability"])
+
+    def test_production_wrapper_uses_internal_por_and_build_id_parameter(self) -> None:
+        source = TOP.read_text(encoding="ascii")
+        header = source.split(");", 1)[0]
+
+        self.assertNotIn("sys_rst_n", header)
+        self.assertIn("parameter integer POR_CYCLES = 1024", header)
+        self.assertIn("parameter integer READY_REPEAT_COUNT = 3", header)
+        self.assertIn("parameter [31:0] BUILD_ID = 32'h00000000", header)
+        self.assertIn("prod2u_build_id_must_be_nonzero", source)
+        self.assertIn("prod2u_por", source)
+        self.assertIn(".POR_CYCLES(POR_CYCLES)", source)
+        self.assertIn(".BUILD_ID(BUILD_ID)", source)
+
+    def test_core_ready_contract_contains_build_identity_and_limited_repeat(self) -> None:
+        source = CORE.read_text(encoding="ascii")
+
+        self.assertIn("parameter [31:0] BUILD_ID = 32'h00000000", source)
+        self.assertIn("parameter integer READY_REPEAT_COUNT = 3", source)
+        self.assertIn("diag_payload_len <= 8'd7", source)
+        self.assertIn("POR_REASON_CONFIG = 8'h01", source)
+        self.assertIn("ready_announcement_seq", source)
+        self.assertIn("BUILD_ID[31:24]", source)
+        self.assertIn("BUILD_ID[23:16]", source)
+        self.assertIn("BUILD_ID[15:8]", source)
+        self.assertIn("BUILD_ID[7:0]", source)
+
+    def test_existing_binary921_decoder_contract_exposes_ready_payload_bytes(self) -> None:
+        frame = decode_frame(
+            encode_frame(
+                profile_id=3,
+                frame_type=FrameType.READY,
+                seq=1,
+                timestamp_tick=4,
+                payload=bytes([3, 0xD4, 0xC3, 0xB2, 0xA1, 0x01, 0x02]),
+            )
+        )
+        decoded = frame_to_dict(frame)
+
+        self.assertEqual(decoded["profile_id"], 3)
+        self.assertEqual(decoded["seq"], 1)
+        self.assertEqual(decoded["timestamp_tick"], 4)
+        self.assertEqual(decoded["payload_hex"], "03d4c3b2a10102")
+        ready_payload_contract = {
+            "profile_id_payload": frame.payload[0],
+            "build_id": int.from_bytes(frame.payload[1:5], "little"),
+            "por_reason": frame.payload[5],
+            "announcement_seq": frame.payload[6],
+        }
+        self.assertEqual(
+            ready_payload_contract,
+            {
+                "profile_id_payload": 3,
+                "build_id": 0xA1B2C3D4,
+                "por_reason": 1,
+                "announcement_seq": 2,
+            },
+        )
+
+    def test_production_constraints_and_td_sources_match_internal_reset_boundary(self) -> None:
+        adc = ADC.read_text(encoding="ascii")
+        project = PROJECT.read_text(encoding="utf-8")
+        syn = SYN_TCL.read_text(encoding="ascii")
+        phy = PHY_TCL.read_text(encoding="ascii")
+
+        self.assertNotIn("sys_rst_n", adc)
+        self.assertNotIn("N6", adc)
+        self.assertIn("../src/rtl/prod2u_por.v", project)
+        self.assertIn("analyze -file {src/rtl/prod2u_por.v}", syn)
+        self.assertIn("read_adc {constraints/" + ADC.name + "}", syn)
+        self.assertIn("read_adc {constraints/" + ADC.name + "}", phy)
+
+    def test_production_phy_uses_vendor_routability_effort_before_route(self) -> None:
+        phy = PHY_TCL.read_text(encoding="ascii")
+
+        setting = "set_param route effort routability"
+        self.assertIn(setting, phy)
+        self.assertLess(phy.index(setting), phy.index("\nroute\n"))
+
+    def test_protocol_docs_define_ready_reason_and_announcement_offsets(self) -> None:
+        docs = (ROOT / "docs" / "j6-bmc-replay-binary921-protocol-v1.zh-CN.md").read_text(encoding="utf-8")
+
+        self.assertIn("READY startup identity", docs)
+        self.assertIn("por_reason", docs)
+        self.assertIn("announcement_seq", docs)
+        self.assertIn("seq=1", docs)
+        self.assertIn("same timestamp", docs)
+
+    def test_por_module_is_present_with_1024_cycle_default(self) -> None:
+        source = POR.read_text(encoding="ascii")
+        self.assertIn("parameter integer POR_CYCLES = 1024", source)
+        self.assertIn("output wire sys_rst_n", source)
+        self.assertIn("initial begin", source)
+
+    def test_uart_rx_has_explicit_two_stage_async_input_synchronizer(self) -> None:
+        source = UART_RX.read_text(encoding="ascii")
+
+        self.assertIn('(* ASYNC_REG = "TRUE" *)', source)
+        self.assertIn("reg rx_meta", source)
+        self.assertIn("reg rx_sync", source)
+        self.assertIn("rx_meta <= rx_i", source)
+        self.assertIn("rx_sync <= rx_meta", source)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 210 - 0
tests/unit/test_prod2u_td_build_identity.py

@@ -0,0 +1,210 @@
+#!/usr/bin/env python3
+"""TDD contract for embedding the deterministic Prod2U build ID in TD staging."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import os
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from unittest import mock
+
+
+ROOT = Path(__file__).resolve().parents[2]
+HARNESS = ROOT / "tools" / "pid_harness.py"
+sys.path.insert(0, str(ROOT / "tools"))
+TOP_NAME = "prod2u_bmc_replay_binary921"
+TOP_FILE = f"{TOP_NAME}_top.v"
+
+
+def load_harness():
+    spec = importlib.util.spec_from_file_location("pid_harness_prod2u_identity", HARNESS)
+    if spec is None or spec.loader is None:
+        raise AssertionError("unable to load pid_harness")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+class Prod2UTdBuildIdentityTests(unittest.TestCase):
+    def test_td_cleanup_removes_profile_specific_prod2u_build_outputs(self) -> None:
+        harness = load_harness()
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            profile_root = root / "td" / "build" / TOP_NAME
+            stale_files = [
+                profile_root / "syn" / "stale_gate.db",
+                profile_root / "phy" / "stale.bit",
+            ]
+            shared_files = [
+                root / "td" / "build" / "syn" / "other-profile-gate.db",
+                root / "td" / "build" / "phy" / "other-profile.bit",
+            ]
+            for path in stale_files + shared_files:
+                path.parent.mkdir(parents=True, exist_ok=True)
+                path.write_bytes(b"stale")
+
+            result = harness.clean_td_outputs(root, top=TOP_NAME)
+
+            self.assertEqual(result["status"], "pass")
+            for path in stale_files:
+                self.assertFalse(path.exists(), path)
+            for path in shared_files:
+                self.assertTrue(path.is_file(), path)
+            self.assertEqual(list((profile_root / "syn").iterdir()), [])
+            self.assertEqual(list((profile_root / "phy").iterdir()), [])
+            deleted = set(result["deleted"])
+            self.assertIn(f"td/build/{TOP_NAME}/syn/stale_gate.db", deleted)
+            self.assertIn(f"td/build/{TOP_NAME}/phy/stale.bit", deleted)
+
+    def test_por_init_probe_requires_reset_and_all_counter_registers_at_zero(self) -> None:
+        harness = load_harness()
+        lines = ["PROD2U_POR_INIT|u_por/por_reset_n_reg|0"]
+        lines.extend(
+            f"PROD2U_POR_INIT|u_por/por_count_reg[{index}]|0"
+            for index in range(10)
+        )
+
+        result = harness.parse_prod2u_por_init_probe("\n".join(lines), por_cycles=1024)
+
+        self.assertEqual(result["status"], "pass")
+        self.assertEqual(result["register_count"], 11)
+        self.assertEqual(result["expected_init"], "0")
+
+    def test_por_init_probe_fails_closed_for_missing_or_nonzero_registers(self) -> None:
+        harness = load_harness()
+        stdout = "\n".join(
+            ["PROD2U_POR_INIT|u_por/por_reset_n_reg|1"]
+            + [
+                f"PROD2U_POR_INIT|u_por/por_count_reg[{index}]|0"
+                for index in range(9)
+            ]
+        )
+
+        result = harness.parse_prod2u_por_init_probe(stdout, por_cycles=1024)
+
+        self.assertEqual(result["status"], "fail")
+        self.assertIn("nonzero_init:u_por/por_reset_n_reg:1", result["failures"])
+        self.assertIn("missing_register:u_por/por_count_reg[9]", result["failures"])
+
+    def test_por_init_runner_imports_the_gate_database_by_absolute_path(self) -> None:
+        harness = load_harness()
+        markers = ["PROD2U_POR_INIT|u_por/por_reset_n_reg|0"] + [
+            f"PROD2U_POR_INIT|u_por/por_count_reg[{index}]|0"
+            for index in range(10)
+        ]
+        with tempfile.TemporaryDirectory() as tmp:
+            syn_dir = Path(tmp) / "syn"
+            syn_dir.mkdir()
+            (syn_dir / "prod2u_bmc_replay_binary921_gate.db").write_bytes(b"db")
+            relative_syn_dir = Path(os.path.relpath(syn_dir, ROOT))
+            completed = subprocess.CompletedProcess(
+                ["td"], 0, stdout="\n".join(markers), stderr=""
+            )
+            with mock.patch.object(harness, "run_td_script", return_value=completed):
+                result = harness.run_prod2u_por_init_probe(relative_syn_dir, por_cycles=1024)
+            script = (syn_dir / "prod2u_por_init_probe.tcl").read_text(encoding="ascii")
+
+        self.assertEqual(result["status"], "pass")
+        self.assertIn((syn_dir / "prod2u_bmc_replay_binary921_gate.db").resolve().as_posix(), script)
+        self.assertNotIn("regexp", script)
+
+    def test_prod2u_td_payload_uses_versioned_receipt_schema_even_when_not_run(self) -> None:
+        harness = load_harness()
+
+        payload = harness.td_build_payload(run=False, top=TOP_NAME)
+
+        self.assertEqual(payload["schema"], "prod2u-td-build-receipt-v1")
+        self.assertEqual(payload["status"], "skipped")
+
+    def test_td_build_blocks_before_td_when_staged_identity_fails(self) -> None:
+        harness = load_harness()
+        with tempfile.TemporaryDirectory() as tmp:
+            syn_dir = Path(tmp) / "syn"
+            phy_dir = Path(tmp) / "phy"
+            syn_dir.mkdir()
+            phy_dir.mkdir()
+            with (
+                mock.patch.object(harness, "clean_td_outputs", return_value={"status": "pass"}),
+                mock.patch.object(harness, "prepare_td_build_dirs", return_value=(syn_dir, phy_dir)),
+                mock.patch.object(
+                    harness,
+                    "read_prod2u_staged_identity",
+                    return_value={"status": "fail", "reason": "staged source identity mismatch"},
+                ),
+                mock.patch.object(harness, "run_td_script") as run_td,
+            ):
+                payload = harness.td_build_payload(run=True, top=TOP_NAME)
+
+        self.assertEqual(payload["status"], "fail_build_identity")
+        self.assertEqual(payload["build_identity"]["status"], "fail")
+        self.assertFalse(run_td.called)
+
+    def test_prepare_td_staging_embeds_manifest_build_id_without_editing_active_top(self) -> None:
+        harness = load_harness()
+        active_top = ROOT / "src" / "top" / TOP_FILE
+        active_before = active_top.read_text(encoding="ascii")
+        self.assertIn("parameter [31:0] BUILD_ID = 32'h00000000", active_before)
+
+        syn_dir, phy_dir = harness.prepare_td_build_dirs(TOP_NAME)
+
+        syn_manifest = json.loads((syn_dir / "source-manifest.json").read_text(encoding="utf-8"))
+        phy_manifest = json.loads((phy_dir / "source-manifest.json").read_text(encoding="utf-8"))
+        self.assertEqual(syn_manifest, phy_manifest)
+        self.assertEqual(syn_manifest["schema"], "prod2u-source-manifest-v1")
+        self.assertEqual(syn_manifest["profile"], "prod2u-bmc-replay-binary921")
+        self.assertEqual(syn_manifest["build_id"], syn_manifest["source_manifest_sha256"][:8].upper())
+
+        paths = {row["path"] for row in syn_manifest["files"]}
+        for required in (
+            f"src/top/{TOP_FILE}",
+            "src/rtl/prod2u_por.v",
+            "src/rtl/binary921_diag_core.v",
+            f"constraints/{TOP_NAME}.adc",
+            "constraints/pid_study_01.sdc",
+            f"td/{TOP_NAME}.prj",
+            f"td/syn/{TOP_NAME}.tcl",
+            f"td/phy/{TOP_NAME}.tcl",
+            "config/pin_inventory.fcb_fpga_mcu0611.json",
+            "docs/j6-bmc-replay-binary921-protocol-v1.zh-CN.md",
+            "tools/prod2u_build_identity.py",
+            "tools/pid_harness.py",
+            "tools/pin_inventory.py",
+        ):
+            with self.subTest(required=required):
+                self.assertIn(required, paths)
+
+        top_row = next(row for row in syn_manifest["files"] if row["path"] == f"src/top/{TOP_FILE}")
+        self.assertEqual(top_row["normalization"], "prod2u_build_id_zero")
+
+        expected_literal = f"parameter [31:0] BUILD_ID = 32'h{syn_manifest['build_id']}"
+        self.assertIn(expected_literal, (syn_dir / "src" / "top" / TOP_FILE).read_text(encoding="ascii"))
+        self.assertIn(expected_literal, (phy_dir / "src" / "top" / TOP_FILE).read_text(encoding="ascii"))
+        self.assertEqual(active_top.read_text(encoding="ascii"), active_before)
+
+        identity = harness.read_prod2u_staged_identity(TOP_NAME, syn_dir, phy_dir)
+        self.assertEqual(identity["status"], "pass")
+        self.assertEqual(identity["build_id"], syn_manifest["build_id"])
+        self.assertEqual(identity["source_manifest_sha256"], syn_manifest["source_manifest_sha256"])
+        self.assertRegex(identity["staged_manifest_sha256"], r"^[0-9a-f]{64}$")
+        staged_by_path = {row["path"]: row for row in identity["staged_files"]}
+        self.assertNotEqual(staged_by_path[f"src/top/{TOP_FILE}"]["sha256"], top_row["sha256"])
+        self.assertEqual(staged_by_path[f"src/top/{TOP_FILE}"]["normalized_sha256"], top_row["sha256"])
+
+        staged_top = syn_dir / "src" / "top" / TOP_FILE
+        original_staged = staged_top.read_text(encoding="ascii")
+        try:
+            staged_top.write_text(original_staged + "// identity corruption\n", encoding="ascii")
+            failed = harness.read_prod2u_staged_identity(TOP_NAME, syn_dir, phy_dir)
+            self.assertEqual(failed["status"], "fail")
+            self.assertIn("staged source", failed["reason"])
+        finally:
+            harness.prepare_td_build_dirs(TOP_NAME)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 772 - 0
tests/unit/test_prod2u_validator.py

@@ -0,0 +1,772 @@
+#!/usr/bin/env python3
+"""TDD coverage for raw-first Prod2U evidence validation."""
+
+from __future__ import annotations
+
+import hashlib
+import importlib.util
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest import mock
+
+import jsonschema
+
+
+ROOT = Path(__file__).resolve().parents[2]
+VALIDATOR = ROOT / "tools" / "prod2u_validate.py"
+TOOLS = ROOT / "tools"
+if str(TOOLS) not in sys.path:
+    sys.path.insert(0, str(TOOLS))
+
+
+def load_validator():
+    if not VALIDATOR.is_file():
+        raise AssertionError(f"missing validator: {VALIDATOR}")
+    spec = importlib.util.spec_from_file_location("prod2u_validate_test", VALIDATOR)
+    if spec is None or spec.loader is None:
+        raise AssertionError("unable to load Prod2U validator")
+    module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(module)
+    return module
+
+
+def program_receipt() -> dict:
+    build_id = "1234ABCD"
+    return {
+        "schema": "prod2u-program-sram-receipt-v1",
+        "status": "pass",
+        "request": {
+            "operation": "PROGRAM_SRAM",
+            "target_chip": "EF2L45",
+            "cable_index": 0,
+            "speed_code": 2,
+            "speed_hz": 200000,
+            "attempt_limit": 1,
+            "power_cycle_allowed": False,
+        },
+        "bitstream": {"path": f"C:/P2U/{build_id}/fw.bit", "sha256": "a" * 64, "build_id": build_id},
+        "staging": {
+            "expected_path": f"C:/P2U/{build_id}/fw.bit",
+            "observed_path": f"C:/P2U/{build_id}/fw.bit",
+            "matches_expected_path": True,
+        },
+        "execution": {
+            "exit_code": 0,
+            "timed_out": False,
+            "attempt_count": 1,
+            "retry_count": 0,
+            "power_cycle_count": 0,
+            "command_execution_attempted": True,
+            "timeout_seconds": 60,
+            "started_at": "2026-07-10T10:00:00Z",
+            "finished_at": "2026-07-10T10:00:02Z",
+            "duration_seconds": 2.0,
+        },
+        "parser": {
+            "status": "pass",
+            "exit_code_trusted": False,
+            "ordered_markers": [
+                "download_start",
+                "chip_validation",
+                "bit_to_vec_start",
+                "bit_to_vec_finish",
+                "program_start",
+                "program_finish",
+                "download_finish",
+            ],
+            "ordered_markers_complete": True,
+            "observed_markers": [
+                "download_start",
+                "chip_validation",
+                "bit_to_vec_start",
+                "bit_to_vec_finish",
+                "program_start",
+                "program_finish",
+                "download_finish",
+            ],
+            "observed_marker_lines": [1, 2, 3, 4, 5, 6, 7],
+            "error_markers": [],
+            "failures": [],
+            "transcript_sha256": "9" * 64,
+        },
+        "tool": {"path": "C:/TD/bin/bw_commands_prompt.exe", "td_root": "C:/TD", "td_bin": "C:/TD/bin"},
+        "mutex": {"name": "Global\\Prod2UProgramSram", "acquired": True},
+        "process_cleanup": {"status": "pass", "td_root": "C:/TD", "wait_seconds": 5.0, "remaining": []},
+        "artifacts": {
+            "tcl": {"path": "program-sram.tcl", "size": 1, "sha256": "1" * 64},
+            "stdout": {"path": "bitwriter-stdout.log", "size": 1, "sha256": "2" * 64},
+            "stderr": {"path": "bitwriter-stderr.log", "size": 1, "sha256": "3" * 64},
+            "log_delta": {"path": "bitwriter-log-delta.log", "size": 1, "sha256": "4" * 64},
+            "log_delta_sources": [
+                {
+                    "path": "C:/TD/log/bw_test.log",
+                    "start_offset": 0,
+                    "byte_count": 1,
+                    "sha256": "8" * 64,
+                }
+            ],
+        },
+        "safety": {
+            "flash_attempted": False,
+            "programs_nonvolatile": False,
+            "power_cycle_attempted": False,
+            "driver_install_attempted": False,
+            "toggles_dtr_rts": False,
+            "real_ptc_fan_action_attempted": False,
+            "external_programming_command_executed": True,
+        },
+    }
+
+
+class Prod2UValidatorTests(unittest.TestCase):
+    def build_fixture(self, root: Path) -> tuple[dict, dict, Path]:
+        import prod2u_collector as collector
+        from binary921 import CommandId, FrameType, build_host_command, encode_frame
+
+        profile_id = 3
+        build_id = "1234ABCD"
+        command_wire = b"".join(
+            build_host_command(
+                seq=index,
+                command=command,
+                channel=channel,
+                percent=percent,
+                profile_id=profile_id,
+            )
+            for index, (_, command, channel, percent) in enumerate(collector.COMMAND_SEQUENCE, start=1)
+        )
+        ready = encode_frame(
+            profile_id=profile_id,
+            frame_type=FrameType.READY,
+            seq=1,
+            timestamp_tick=250000,
+            payload=bytes([profile_id]) + int(build_id, 16).to_bytes(4, "little") + bytes([1, 0]),
+        )
+        acks = b"".join(
+            encode_frame(
+                profile_id=profile_id,
+                frame_type=FrameType.HOST_ACK,
+                seq=index,
+                timestamp_tick=0,
+                payload=bytes([1, command, 0, 0, 0x34, 0x12]),
+            )
+            for index, (_, command, _, _) in enumerate(collector.COMMAND_SEQUENCE, start=1)
+        )
+        bmc_payload_bytes = bytes([0x1E, 0x4B] + [0xFF] * 22 + [0x20, 0x19] + [0xFF] * 22)
+        bmc_checksum = sum(bmc_payload_bytes) & 0xFFFF
+        bmc = encode_frame(
+            profile_id=profile_id,
+            frame_type=FrameType.BMC_PAYLOAD,
+            seq=30,
+            timestamp_tick=0,
+            payload=bytes(
+                [48, 48, 1, 0, bmc_payload_bytes[0], bmc_payload_bytes[-1], bmc_checksum & 0xFF, bmc_checksum >> 8]
+            ),
+        )
+        sensor = encode_frame(
+            profile_id=profile_id,
+            frame_type=FrameType.SENSOR_CACHE,
+            seq=31,
+            timestamp_tick=0,
+            payload=bytes([profile_id, 0, 1, 0xFE, 0xEF, 0xFF, 2, 22]),
+        )
+        snapshot = encode_frame(
+            profile_id=profile_id,
+            frame_type=FrameType.MODULE_SNAPSHOT,
+            seq=32,
+            timestamp_tick=0,
+            payload=bytes(
+                [
+                    profile_id,
+                    0,
+                    12,
+                    0,
+                    0x1E,
+                    0xFF,
+                    0x08,
+                    0x14,
+                    CommandId.DISABLE,
+                    0,
+                    0,
+                    0,
+                    0,
+                    1,
+                    2,
+                    22,
+                    0,
+                    0,
+                    30,
+                    30,
+                    0,
+                    0x0F,
+                    0,
+                    0,
+                ]
+            ),
+        )
+        combined = ready + acks + bmc + sensor + snapshot
+        (root / "combined-rx.raw").write_bytes(combined)
+        (root / "host-command-wire.bin").write_bytes(command_wire)
+        collector_manifest = {
+            "schema": "prod2u-collector-manifest-v1",
+            "status": "pass",
+            "artifact_hashes": {
+                "combined-rx.raw": hashlib.sha256(combined).hexdigest(),
+                "host-command-wire.bin": hashlib.sha256(command_wire).hexdigest(),
+            },
+            "safety": {
+                "flash_attempted": False,
+                "programs_nonvolatile": False,
+                "driver_install_attempted": False,
+                "toggles_dtr_rts": False,
+            },
+        }
+        source_manifest = {
+            "schema": "prod2u-source-manifest-v1",
+            "profile": "prod2u-bmc-replay-binary921",
+            "source_manifest_sha256": "1234abcd" + "b" * 56,
+            "build_id": build_id,
+        }
+        bmc_receipt = root / "bmc-replay-session.json"
+        bmc_receipt.write_text(
+            json.dumps(
+                {
+                    "schema": "prod2u-bmc-replay-session-v1",
+                    "status": "pass",
+                    "bmc_source": "pc_replay_from_real_bmc_capture",
+                    "reply_sha256": hashlib.sha256(
+                        (" ".join(f"{value:02x}" for value in bmc_payload_bytes) + "\r\n").encode("ascii")
+                    ).hexdigest(),
+                    "payload_hex": [f"{value:02x}" for value in bmc_payload_bytes],
+                    "byte_count": 48,
+                    "valid_count": 2,
+                    "missing_count": 22,
+                    "matched_poll_count": 1,
+                    "reply_count": 1,
+                    "started_at": "2026-07-10T09:59:59Z",
+                    "last_reply_at": "2026-07-10T10:00:01Z",
+                }
+            ),
+            encoding="utf-8",
+        )
+        return collector_manifest, source_manifest, bmc_receipt
+
+    def test_raw_first_validator_passes_complete_software_chain(self) -> None:
+        validator = load_validator()
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            collector, source, bmc = self.build_fixture(root)
+            evidence = validator.validate_evidence_directory(
+                collector_dir=root,
+                collector=collector,
+                program=program_receipt(),
+                source_manifest=source,
+                programmer_receipt_path="programmer/program-sram-receipt.json",
+                programmer_receipt_sha256="c" * 64,
+                bmc_replay_receipt_path=bmc,
+            )
+
+            self.assertEqual(evidence["status"], "pass", evidence["blockers"])
+            self.assertEqual(evidence["startup_ready"]["build_id"], "1234ABCD")
+            self.assertEqual(evidence["host_command_count"], 12)
+            self.assertEqual(evidence["host_ack_matched_count"], 12)
+            self.assertEqual(evidence["raw_validation"]["combined"]["status"], "pass")
+            self.assertEqual(evidence["raw_validation"]["sensor_cache"]["valid_count"], 2)
+            self.assertEqual(evidence["raw_validation"]["sensor_cache"]["missing_count"], 22)
+            self.assertEqual(evidence["raw_validation"]["timeout_fallback"]["status"], "pass")
+
+    def test_missing_bmc_replay_receipt_remains_schema_valid_blocked_evidence(self) -> None:
+        validator = load_validator()
+        schema = json.loads(
+            (ROOT / "schemas" / "prod2u_evidence_manifest.schema.json").read_text(encoding="utf-8")
+        )
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            collector, source, bmc = self.build_fixture(root)
+            bmc.unlink()
+
+            evidence = validator.validate_evidence_directory(
+                collector_dir=root,
+                collector=collector,
+                program=program_receipt(),
+                source_manifest=source,
+                programmer_receipt_path="programmer/program-sram-receipt.json",
+                programmer_receipt_sha256="c" * 64,
+                bmc_replay_receipt_path=bmc,
+            )
+
+            self.assertEqual(evidence["status"], "blocked_bmc_replay_not_run")
+            self.assertEqual(
+                evidence["bmc_replay"],
+                {
+                    "status": "not_run",
+                    "bmc_source": "not_run",
+                    "payload_sha256": None,
+                },
+            )
+            jsonschema.validate(evidence, schema)
+
+    def test_missing_bmc_uart_frames_are_not_independent_failures_when_replay_was_not_run(self) -> None:
+        validator = load_validator()
+        from binary921 import FrameType, decode_stream
+
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            collector, source, bmc = self.build_fixture(root)
+            frames, remainder = decode_stream((root / "combined-rx.raw").read_bytes())
+            self.assertEqual(remainder, b"")
+            combined = b"".join(
+                frame.raw
+                for frame in frames
+                if frame.frame_type not in (FrameType.BMC_PAYLOAD, FrameType.SENSOR_CACHE)
+            )
+            (root / "combined-rx.raw").write_bytes(combined)
+            collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(combined).hexdigest()
+            bmc.unlink()
+
+            evidence = validator.validate_evidence_directory(
+                collector_dir=root,
+                collector=collector,
+                program=program_receipt(),
+                source_manifest=source,
+                programmer_receipt_path="programmer/program-sram-receipt.json",
+                programmer_receipt_sha256="c" * 64,
+                bmc_replay_receipt_path=bmc,
+            )
+
+            self.assertEqual(evidence["status"], "blocked_bmc_replay_not_run")
+            self.assertEqual(evidence["blockers"], ["bmc_replay_not_pass"])
+            self.assertEqual(evidence["raw_validation"]["sensor_cache"]["status"], "not_run")
+
+    def test_invalid_bmc_replay_receipt_remains_schema_valid_failed_evidence(self) -> None:
+        validator = load_validator()
+        schema = json.loads(
+            (ROOT / "schemas" / "prod2u_evidence_manifest.schema.json").read_text(encoding="utf-8")
+        )
+        for invalid_payload in ("{", "[]"):
+            with self.subTest(invalid_payload=invalid_payload), tempfile.TemporaryDirectory() as tmp:
+                root = Path(tmp)
+                collector, source, bmc = self.build_fixture(root)
+                bmc.write_text(invalid_payload, encoding="utf-8")
+
+                evidence = validator.validate_evidence_directory(
+                    collector_dir=root,
+                    collector=collector,
+                    program=program_receipt(),
+                    source_manifest=source,
+                    programmer_receipt_path="programmer/program-sram-receipt.json",
+                    programmer_receipt_sha256="c" * 64,
+                    bmc_replay_receipt_path=bmc,
+                )
+
+                self.assertEqual(evidence["status"], "fail")
+                self.assertEqual(evidence["bmc_replay"]["bmc_source"], "not_run")
+                self.assertIsNone(evidence["bmc_replay"]["payload_sha256"])
+                jsonschema.validate(evidence, schema)
+
+    def test_ready_epoch_selects_last_matching_ready_in_the_post_callback_stream(self) -> None:
+        validator = load_validator()
+        from binary921 import FrameType, decode_stream, encode_frame
+
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            collector, source, bmc = self.build_fixture(root)
+            combined = (root / "combined-rx.raw").read_bytes()
+            frames, remainder = decode_stream(combined)
+            self.assertEqual(remainder, b"")
+            first_ready_len = len(frames[0].raw)
+            later_ready = encode_frame(
+                profile_id=3,
+                frame_type=FrameType.READY,
+                seq=1,
+                timestamp_tick=250001,
+                payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, 2]),
+            )
+            combined = combined[:first_ready_len] + later_ready + combined[first_ready_len:]
+            (root / "combined-rx.raw").write_bytes(combined)
+            collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(combined).hexdigest()
+
+            evidence = validator.validate_evidence_directory(
+                collector_dir=root,
+                collector=collector,
+                program=program_receipt(),
+                source_manifest=source,
+                programmer_receipt_path="programmer/program-sram-receipt.json",
+                programmer_receipt_sha256="c" * 64,
+                bmc_replay_receipt_path=bmc,
+            )
+
+            self.assertEqual(evidence["status"], "pass", evidence["blockers"])
+            self.assertEqual(evidence["startup_ready"]["announcement_seq"], 2)
+            self.assertEqual(evidence["startup_ready"]["matching_ready_count"], 2)
+            self.assertEqual(evidence["startup_ready"]["selection_policy"], "last_matching_ready")
+
+    def test_collector_wait_selects_last_matching_ready_from_one_buffered_chunk(self) -> None:
+        import prod2u_collector as collector
+        from binary921 import FrameType, encode_frame
+
+        ready_frames = b"".join(
+            encode_frame(
+                profile_id=3,
+                frame_type=FrameType.READY,
+                seq=1,
+                timestamp_tick=250000 + announcement,
+                payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, announcement]),
+            )
+            for announcement in (0, 2)
+        )
+
+        class BufferedSerial:
+            def __init__(self, payload: bytes) -> None:
+                self.payload = payload
+
+            def read(self, _size: int) -> bytes:
+                payload, self.payload = self.payload, b""
+                return payload
+
+        result = collector.wait_for_ready(
+            BufferedSerial(ready_frames),
+            timeout_sec=0.05,
+            expected_profile_id=3,
+            expected_build_id="1234ABCD",
+            expected_epoch=1,
+            expected_por_reason=1,
+            max_announcement_seq=2,
+        )
+
+        self.assertEqual(result["status"], "pass")
+        self.assertEqual(result["ready"]["decoded"]["announcement_seq"], 2)
+        self.assertEqual(result["matching_ready_count"], 2)
+        self.assertEqual(result["selection_policy"], "last_matching_ready")
+
+    def test_collector_splits_corrupt_and_old_build_bytes_before_three_matching_ready_frames(self) -> None:
+        import prod2u_collector as collector
+        from binary921 import FrameType, encode_frame
+
+        old_ready = encode_frame(
+            profile_id=3,
+            frame_type=FrameType.READY,
+            seq=1,
+            timestamp_tick=249999,
+            payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
+        )
+        corrupt_ready = bytearray(old_ready)
+        corrupt_ready[-1] ^= 1
+        matching_ready = b"".join(
+            encode_frame(
+                profile_id=3,
+                frame_type=FrameType.READY,
+                seq=1,
+                timestamp_tick=250000 + announcement,
+                payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, announcement]),
+            )
+            for announcement in (0, 1, 2)
+        )
+        pre_ready = bytes(corrupt_ready) + old_ready
+        stream = pre_ready + matching_ready
+
+        class BufferedSerial:
+            def __init__(self, payload: bytes) -> None:
+                self.payload = payload
+
+            def read(self, _size: int) -> bytes:
+                payload, self.payload = self.payload, b""
+                return payload
+
+        result = collector.wait_for_ready(
+            BufferedSerial(stream),
+            timeout_sec=0.05,
+            expected_profile_id=3,
+            expected_build_id="1234ABCD",
+            expected_epoch=1,
+            expected_por_reason=1,
+            max_announcement_seq=2,
+        )
+
+        self.assertEqual(result["status"], "pass")
+        self.assertEqual(result["raw"], stream)
+        self.assertEqual(result["pre_ready_raw"], pre_ready)
+        self.assertEqual(result["epoch_start_offset"], len(pre_ready))
+        self.assertEqual(result["epoch_raw"], matching_ready)
+        self.assertEqual(result["matching_ready_count"], 3)
+        self.assertEqual(result["ready"]["decoded"]["announcement_seq"], 2)
+
+    def test_combined_collector_writes_pre_ready_diagnostics_and_formal_epoch_separately(self) -> None:
+        import prod2u_collector as collector
+        from binary921 import FrameType, encode_frame
+
+        old_ready = encode_frame(
+            profile_id=3,
+            frame_type=FrameType.READY,
+            seq=1,
+            timestamp_tick=249999,
+            payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
+        )
+        corrupt_ready = bytearray(old_ready)
+        corrupt_ready[-1] ^= 1
+        matching_ready = b"".join(
+            encode_frame(
+                profile_id=3,
+                frame_type=FrameType.READY,
+                seq=1,
+                timestamp_tick=250000 + announcement,
+                payload=bytes([3]) + int("1234ABCD", 16).to_bytes(4, "little") + bytes([1, announcement]),
+            )
+            for announcement in (0, 1, 2)
+        )
+        pre_ready = bytes(corrupt_ready) + old_ready
+
+        class FakeSerial:
+            def __init__(self, payload: bytes) -> None:
+                self.payload = payload
+                self.closed = False
+
+            def read(self, _size: int) -> bytes:
+                payload, self.payload = self.payload, b""
+                return payload
+
+            def write(self, payload: bytes) -> int:
+                return len(payload)
+
+            def flush(self) -> None:
+                return None
+
+            def close(self) -> None:
+                self.closed = True
+
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            endpoint = FakeSerial(pre_ready + matching_ready)
+            args = SimpleNamespace(
+                output_dir=str(root),
+                profile="prod2u-bmc-replay-binary921",
+                transport="combined-single-com",
+                combined_port="COM5",
+                host_port="",
+                expected_build_id="1234ABCD",
+                expected_epoch=1,
+                ready_timeout_sec=0.05,
+                ack_window_sec=0.0,
+                duration_sec=0.0,
+                bmc_replay_receipt="",
+            )
+
+            with mock.patch.object(collector, "_open_serial", return_value=endpoint):
+                manifest = collector.collect_live(args)
+
+            self.assertTrue(endpoint.closed)
+            self.assertEqual((root / "pre-ready-uart.raw").read_bytes(), pre_ready)
+            self.assertEqual((root / "combined-rx.raw").read_bytes(), matching_ready)
+            self.assertEqual((root / "combined-uart-binary921.raw").read_bytes(), pre_ready + matching_ready)
+            preflight = json.loads((root / "startup-preflight.json").read_text(encoding="utf-8"))
+            self.assertEqual(preflight["epoch_start_offset"], len(pre_ready))
+            self.assertEqual(manifest["startup_ready"]["matching_ready_count"], 3)
+            self.assertEqual(
+                manifest["artifact_hashes"]["combined-rx.raw"],
+                hashlib.sha256(matching_ready).hexdigest(),
+            )
+            self.assertEqual(
+                manifest["artifact_hashes"]["pre-ready-uart.raw"],
+                hashlib.sha256(pre_ready).hexdigest(),
+            )
+
+    def test_ready_timeout_preserves_diagnostics_without_creating_a_formal_epoch(self) -> None:
+        import prod2u_collector as collector
+        from binary921 import FrameType, encode_frame
+
+        old_ready = encode_frame(
+            profile_id=3,
+            frame_type=FrameType.READY,
+            seq=1,
+            timestamp_tick=249999,
+            payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
+        )
+        corrupt_ready = bytearray(old_ready)
+        corrupt_ready[-1] ^= 1
+        observed = bytes(corrupt_ready) + old_ready
+
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            manifest = collector.write_blocked_manifest(
+                root,
+                profile="prod2u-bmc-replay-binary921",
+                status="blocked_waiting_for_binary921_ready",
+                startup_raw=observed,
+                startup_frames=[],
+                error="build_mismatch",
+                timeout_evidence={"status": "blocked_waiting_for_binary921_ready"},
+            )
+
+            self.assertEqual((root / "pre-ready-uart.raw").read_bytes(), observed)
+            self.assertEqual((root / "combined-uart-binary921.raw").read_bytes(), observed)
+            self.assertEqual((root / "combined-rx.raw").read_bytes(), b"")
+            preflight = json.loads((root / "startup-preflight.json").read_text(encoding="utf-8"))
+            self.assertIsNone(preflight["epoch_start_offset"])
+            self.assertEqual(
+                manifest["artifact_hashes"]["pre-ready-uart.raw"],
+                hashlib.sha256(observed).hexdigest(),
+            )
+
+    def test_validator_rejects_formal_combined_rx_that_starts_before_matching_ready_epoch(self) -> None:
+        validator = load_validator()
+        from binary921 import FrameType, encode_frame
+
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            collector, source, bmc = self.build_fixture(root)
+            combined = (root / "combined-rx.raw").read_bytes()
+            old_ready = encode_frame(
+                profile_id=3,
+                frame_type=FrameType.READY,
+                seq=1,
+                timestamp_tick=249999,
+                payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
+            )
+            contaminated = old_ready + combined
+            (root / "combined-rx.raw").write_bytes(contaminated)
+            collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(contaminated).hexdigest()
+
+            evidence = validator.validate_evidence_directory(
+                collector_dir=root,
+                collector=collector,
+                program=program_receipt(),
+                source_manifest=source,
+                programmer_receipt_path="programmer/program-sram-receipt.json",
+                programmer_receipt_sha256="c" * 64,
+                bmc_replay_receipt_path=bmc,
+            )
+
+            self.assertEqual(evidence["status"], "fail")
+            self.assertIn("formal_epoch_does_not_start_at_matching_ready", evidence["blockers"])
+
+    def test_validator_strictly_decodes_post_epoch_artifact_and_ignores_pre_ready_diagnostics(self) -> None:
+        validator = load_validator()
+        from binary921 import FrameType, decode_stream, encode_frame
+
+        with tempfile.TemporaryDirectory() as tmp:
+            root = Path(tmp)
+            collector, source, bmc = self.build_fixture(root)
+            original = (root / "combined-rx.raw").read_bytes()
+            frames, remainder = decode_stream(original)
+            self.assertEqual(remainder, b"")
+            ready_length = len(frames[0].raw)
+            formal_tail = original[ready_length:]
+            old_ready = encode_frame(
+                profile_id=3,
+                frame_type=FrameType.READY,
+                seq=1,
+                timestamp_tick=249999,
+                payload=bytes([3]) + int("DEADBEEF", 16).to_bytes(4, "little") + bytes([1, 0]),
+            )
+            corrupt_ready = bytearray(old_ready)
+            corrupt_ready[-1] ^= 1
+            pre_ready = bytes(corrupt_ready) + old_ready
+            matching_ready = b"".join(
+                encode_frame(
+                    profile_id=3,
+                    frame_type=FrameType.READY,
+                    seq=1,
+                    timestamp_tick=250000 + announcement,
+                    payload=bytes([3])
+                    + int("1234ABCD", 16).to_bytes(4, "little")
+                    + bytes([1, announcement]),
+                )
+                for announcement in (0, 1, 2)
+            )
+            formal = matching_ready + formal_tail
+            (root / "pre-ready-uart.raw").write_bytes(pre_ready)
+            (root / "combined-rx.raw").write_bytes(formal)
+            collector["artifact_hashes"]["pre-ready-uart.raw"] = hashlib.sha256(pre_ready).hexdigest()
+            collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(formal).hexdigest()
+            collector["startup_ready"] = {"epoch_start_offset": len(pre_ready)}
+
+            evidence = validator.validate_evidence_directory(
+                collector_dir=root,
+                collector=collector,
+                program=program_receipt(),
+                source_manifest=source,
+                programmer_receipt_path="programmer/program-sram-receipt.json",
+                programmer_receipt_sha256="c" * 64,
+                bmc_replay_receipt_path=bmc,
+            )
+
+            self.assertEqual(evidence["status"], "pass", evidence["blockers"])
+            self.assertEqual(evidence["startup_ready"]["matching_ready_count"], 3)
+            self.assertEqual(evidence["startup_ready"]["announcement_seq"], 2)
+            self.assertEqual(evidence["startup_ready"]["epoch_start_offset"], len(pre_ready))
+            self.assertEqual(evidence["raw_validation"]["combined"]["status"], "pass")
+
+    def test_raw_corruption_sequence_gap_and_manifest_hash_mismatch_fail_closed(self) -> None:
+        validator = load_validator()
+        cases = (
+            "corrupt_crc",
+            "command_seq",
+            "manifest_hash",
+            "pre_ready_acks",
+            "bmc_provenance",
+            "malformed_bmc_counts",
+            "stale_bmc_session",
+        )
+        for name in cases:
+            with self.subTest(name=name), tempfile.TemporaryDirectory() as tmp:
+                root = Path(tmp)
+                collector, source, bmc = self.build_fixture(root)
+                if name == "corrupt_crc":
+                    raw = bytearray((root / "combined-rx.raw").read_bytes())
+                    raw[-1] ^= 1
+                    (root / "combined-rx.raw").write_bytes(raw)
+                elif name == "command_seq":
+                    from binary921 import CommandId, build_host_command
+
+                    wire = (root / "host-command-wire.bin").read_bytes()
+                    first_len = 19
+                    replacement = build_host_command(seq=2, command=CommandId.SET_PTC, channel=1, percent=10, profile_id=3)
+                    (root / "host-command-wire.bin").write_bytes(replacement + wire[first_len:])
+                elif name == "pre_ready_acks":
+                    from binary921 import FrameType, decode_stream
+
+                    raw = (root / "combined-rx.raw").read_bytes()
+                    frames, remainder = decode_stream(raw)
+                    self.assertEqual(remainder, b"")
+                    ready_len = len(frames[0].raw)
+                    ack_len = sum(len(frame.raw) for frame in frames[1:13])
+                    ready = raw[:ready_len]
+                    acks = raw[ready_len : ready_len + ack_len]
+                    tail = raw[ready_len + ack_len :]
+                    (root / "combined-rx.raw").write_bytes(acks + ready + tail)
+                    collector["artifact_hashes"]["combined-rx.raw"] = hashlib.sha256(acks + ready + tail).hexdigest()
+                elif name == "bmc_provenance":
+                    receipt = json.loads(bmc.read_text(encoding="utf-8"))
+                    receipt["payload_hex"][0] = "20"
+                    bmc.write_text(json.dumps(receipt), encoding="utf-8")
+                elif name == "stale_bmc_session":
+                    receipt = json.loads(bmc.read_text(encoding="utf-8"))
+                    receipt["last_reply_at"] = "2026-07-10T09:59:58Z"
+                    bmc.write_text(json.dumps(receipt), encoding="utf-8")
+                elif name == "malformed_bmc_counts":
+                    receipt = json.loads(bmc.read_text(encoding="utf-8"))
+                    receipt["matched_poll_count"] = "not-a-number"
+                    receipt["reply_count"] = {"truncated": True}
+                    bmc.write_text(json.dumps(receipt), encoding="utf-8")
+                else:
+                    collector["artifact_hashes"]["combined-rx.raw"] = "0" * 64
+
+                evidence = validator.validate_evidence_directory(
+                    collector_dir=root,
+                    collector=collector,
+                    program=program_receipt(),
+                    source_manifest=source,
+                    programmer_receipt_path="programmer/program-sram-receipt.json",
+                    programmer_receipt_sha256="c" * 64,
+                    bmc_replay_receipt_path=bmc,
+                )
+                self.assertEqual(evidence["status"], "fail")
+                self.assertTrue(evidence["blockers"])
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 4 - 0
tests/verilator_prod2u_build_id_guard_stub.v

@@ -0,0 +1,4 @@
+/* verilator lint_off DECLFILENAME */
+module prod2u_build_id_must_be_nonzero();
+endmodule
+/* verilator lint_on DECLFILENAME */

+ 42 - 3
tools/binary921.py

@@ -9,6 +9,7 @@ from __future__ import annotations
 
 import argparse
 import json
+import re
 import sys
 from dataclasses import dataclass
 from enum import IntEnum
@@ -25,8 +26,14 @@ PROFILE_NAME_TO_ID = {
     "debug-photo-bmc-replay-binary921": 1,
     "formal-uart1-bmc-replay-binary921": 2,
     "production-two-uart-bmc-replay-binary921": 3,
+    "prod2u-bmc-replay-binary921": 3,
 }
-PROFILE_ID_TO_NAME = {value: key for key, value in PROFILE_NAME_TO_ID.items()}
+PROFILE_ID_TO_NAME = {
+    1: "debug-photo-bmc-replay-binary921",
+    2: "formal-uart1-bmc-replay-binary921",
+    3: "production-two-uart-bmc-replay-binary921",
+}
+BUILD_ID_RE = re.compile(r"^[0-9A-Fa-f]{8}$")
 
 
 class Binary921FrameError(ValueError):
@@ -72,6 +79,21 @@ def profile_name_for_id(profile_id: int) -> str:
         raise ValueError(f"unknown binary921 profile id: {profile_id}") from exc
 
 
+def format_build_id(build_id: int | str) -> str:
+    """Return a binary921 32-bit build ID as canonical uppercase JSON text."""
+    if isinstance(build_id, bool):
+        raise ValueError("build_id must be a 32-bit integer or eight hex digits")
+    if isinstance(build_id, int):
+        if build_id < 0 or build_id > 0xFFFFFFFF:
+            raise ValueError("build_id must fit in 32 bits")
+        return f"{build_id:08X}"
+    if isinstance(build_id, str):
+        value = build_id.strip()
+        if BUILD_ID_RE.fullmatch(value):
+            return value.upper()
+    raise ValueError("build_id must be a 32-bit integer or eight hex digits")
+
+
 @dataclass(frozen=True)
 class Binary921Frame:
     version: int
@@ -208,9 +230,9 @@ def build_host_command(
             raise ValueError("percent must be 0..100")
         payload = bytes([command_id, channel, percent])
     elif command_id == CommandId.SET_PID_REQUESTED:
-        if percent is None:
+        if percent not in (0, 1):
             raise ValueError("SET_PID_REQUESTED uses percent as enabled flag 0/1")
-        payload = bytes([command_id, 1 if percent else 0])
+        payload = bytes([command_id, percent])
     else:
         payload = bytes([command_id])
     return encode_frame(
@@ -235,12 +257,29 @@ def decode_payload(frame: Binary921Frame) -> dict[str, object]:
         decoded: dict[str, object] = {"kind": "ready"}
         if len(payload) >= 1:
             decoded["profile_id_payload"] = payload[0]
+        if len(payload) >= 5:
+            decoded["build_id"] = format_build_id(int.from_bytes(payload[1:5], "little"))
+            decoded["startup_epoch"] = frame.seq
+            decoded["startup_tick"] = frame.timestamp_tick
+        if len(payload) >= 6:
+            decoded["por_reason"] = payload[5]
+        if len(payload) >= 7:
+            decoded["announcement_seq"] = payload[6]
         return decoded
     if frame.frame_type == FrameType.HOST_CMD:
         if len(payload) < 1:
             return {"kind": "host_cmd", "error": "missing_cmd_id"}
         command_id = payload[0]
         decoded = {"kind": "host_cmd", "cmd": _enum_name(CommandId, command_id), "cmd_id": command_id}
+        if command_id == int(CommandId.SET_PID_REQUESTED):
+            if len(payload) < 2:
+                decoded["error"] = "missing_enabled_flag"
+            elif payload[1] not in (0, 1):
+                decoded["error"] = "invalid_enabled_flag"
+                decoded["enabled_raw"] = payload[1]
+            else:
+                decoded["enabled"] = payload[1] == 1
+            return decoded
         if len(payload) >= 2:
             decoded["channel"] = payload[1]
         if len(payload) >= 3:

+ 273 - 0
tools/package_prod2u.ps1

@@ -0,0 +1,273 @@
+param(
+    [string]$OutputDir = "C:\Users\Administrator\Downloads\CPLD-deliverables",
+    [Parameter(Mandatory = $true)][string]$Bitstream,
+    [Parameter(Mandatory = $true)][string]$TdReceipt,
+    [Parameter(Mandatory = $true)][string]$SourceManifest,
+    [Parameter(Mandatory = $true)][string]$BmcReplayPayload,
+    [switch]$ForceOverwrite
+)
+
+$ErrorActionPreference = "Stop"
+$repo = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
+
+function Get-Sha256([string]$Path) {
+    return (Get-FileHash -Algorithm SHA256 -LiteralPath $Path).Hash.ToLowerInvariant()
+}
+
+function Read-Json([string]$Path, [string]$Label) {
+    if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "$Label file is missing: $Path" }
+    try { return Get-Content -Raw -LiteralPath $Path | ConvertFrom-Json }
+    catch { throw "$Label is not valid JSON: $Path" }
+}
+
+function Assert-Hex([string]$Value, [int]$Length, [string]$Label) {
+    if ($Value -notmatch ("^[0-9A-Fa-f]{{{0}}}$" -f $Length)) { throw "$Label is invalid" }
+}
+
+function Copy-Required([string]$Source, [string]$Destination) {
+    if (-not (Test-Path -LiteralPath $Source -PathType Leaf)) { throw "Required package source is missing: $Source" }
+    $parent = Split-Path -Parent $Destination
+    if ($parent) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }
+    Copy-Item -LiteralPath $Source -Destination $Destination -Force
+}
+
+function Resolve-Python3 {
+    $venvPython = Join-Path $repo ".codex\venv\Scripts\python.exe"
+    if (Test-Path -LiteralPath $venvPython -PathType Leaf) {
+        return [ordered]@{ exe = $venvPython; prefix = @() }
+    }
+    $python = Get-Command python.exe -ErrorAction SilentlyContinue
+    if ($python) { return [ordered]@{ exe = $python.Source; prefix = @() } }
+    $py = Get-Command py.exe -ErrorAction SilentlyContinue
+    if ($py) { return [ordered]@{ exe = $py.Source; prefix = @("-3") } }
+    throw "Python 3 is required to validate the source manifest before packaging"
+}
+
+$python3 = Resolve-Python3
+$replayTool = Join-Path $repo "tools\prod2u_bmc_replay.py"
+$payloadValidationArgs = @($python3.prefix) + @(
+    $replayTool,
+    "replay",
+    "--port", "COM1",
+    "--payload", $BmcReplayPayload,
+    "--iterations", "1",
+    "--timeout-sec", "0.1",
+    "--dry-run",
+    "--json"
+)
+$payloadValidationOutput = & $python3.exe @payloadValidationArgs 2>&1
+if ($LASTEXITCODE -ne 0) {
+    throw "BMC replay payload validation failed: $($payloadValidationOutput -join [Environment]::NewLine)"
+}
+
+$identityTool = Join-Path $repo "tools\prod2u_build_identity.py"
+$validationArgs = @($python3.prefix) + @($identityTool, "--validate-manifest", $SourceManifest)
+$validationOutput = & $python3.exe @validationArgs 2>&1
+if ($LASTEXITCODE -ne 0) {
+    throw "Source manifest validation failed: $($validationOutput -join [Environment]::NewLine)"
+}
+
+$source = Read-Json $SourceManifest "source manifest"
+if ($source.schema -ne "prod2u-source-manifest-v1") { throw "Unexpected source manifest schema" }
+if ($source.profile -ne "prod2u-bmc-replay-binary921") { throw "Unexpected source manifest profile" }
+$buildId = ([string]$source.build_id).ToUpperInvariant()
+$sourceSha = ([string]$source.source_manifest_sha256).ToLowerInvariant()
+Assert-Hex $buildId 8 "build_id"
+Assert-Hex $sourceSha 64 "source_manifest_sha256"
+if ($buildId -ne $sourceSha.Substring(0, 8).ToUpperInvariant()) { throw "build_id does not match source manifest hash prefix" }
+
+$td = Read-Json $TdReceipt "TD receipt"
+if ($td.schema -ne "prod2u-td-build-receipt-v1") { throw "Unexpected TD receipt schema" }
+if ($td.status -ne "pass") { throw "TD receipt status is not pass" }
+if ($td.pin_profile -ne "prod2u-bmc-replay-binary921") { throw "TD receipt pin profile mismatch" }
+if ($td.top_module -ne "prod2u_bmc_replay_binary921_top") { throw "TD receipt top module mismatch" }
+if (([string]$td.build_id).ToUpperInvariant() -ne $buildId) { throw "TD receipt build_id mismatch" }
+if (([string]$td.source_manifest_sha256).ToLowerInvariant() -ne $sourceSha) { throw "TD receipt source manifest hash mismatch" }
+$por = $td.por_initialization
+if ($null -eq $por -or $por.status -ne "pass") { throw "TD receipt POR initialization is not pass" }
+if (
+    [int]$por.por_cycles -ne 1024 -or
+    [int]$por.counter_width -ne 10 -or
+    [string]$por.expected_init -ne "0" -or
+    [int]$por.register_count -ne 11 -or
+    @($por.failures).Count -ne 0
+) { throw "TD receipt POR initialization contract mismatch" }
+
+if (-not (Test-Path -LiteralPath $Bitstream -PathType Leaf)) { throw "Bitstream is missing: $Bitstream" }
+$bitSha = Get-Sha256 $Bitstream
+if (([string]$td.bitstream.sha256).ToLowerInvariant() -ne $bitSha) { throw "TD receipt bitstream hash mismatch" }
+
+$tdSchemaArgs = @($python3.prefix) + @(
+    (Join-Path $repo "tools\prod2u_cli.py"),
+    "validate-td-receipt",
+    "--td-receipt",
+    $TdReceipt
+)
+$tdSchemaOutput = & $python3.exe @tdSchemaArgs 2>&1
+if ($LASTEXITCODE -ne 0) {
+    throw "TD receipt schema validation failed: $($tdSchemaOutput -join [Environment]::NewLine)"
+}
+
+$bmc = Read-Json $BmcReplayPayload "BMC replay payload"
+if ($bmc.source -ne "real_bmc_capture") { throw "BMC replay payload source must be real_bmc_capture" }
+Assert-Hex ([string]$bmc.reply_sha256) 64 "BMC reply_sha256"
+
+$outFull = [System.IO.Path]::GetFullPath($OutputDir)
+New-Item -ItemType Directory -Force -Path $outFull | Out-Null
+$packageName = "prod2u-$buildId"
+$stage = [System.IO.Path]::GetFullPath((Join-Path $outFull $packageName))
+if (-not $stage.StartsWith($outFull, [System.StringComparison]::OrdinalIgnoreCase)) { throw "Package path escaped OutputDir" }
+if (Test-Path -LiteralPath $stage) {
+    if (-not $ForceOverwrite) { throw "Package directory already exists: $stage" }
+    Remove-Item -LiteralPath $stage -Recurse -Force
+}
+New-Item -ItemType Directory -Force -Path $stage | Out-Null
+
+Copy-Required $Bitstream (Join-Path $stage "fw.bit")
+Copy-Required $TdReceipt (Join-Path $stage "td.json")
+Copy-Required $SourceManifest (Join-Path $stage "source-manifest.json")
+Copy-Required $BmcReplayPayload (Join-Path $stage "bmc-replay-payload.json")
+
+foreach ($name in @(
+    "prod2u.ps1",
+    "prod2u_cli.py",
+    "prod2u_build_identity.py",
+    "prod2u_receipts.py",
+    "prod2u_programmer.py",
+    "prod2u_collector.py",
+    "prod2u_validate.py",
+    "prod2u_bmc_replay.py",
+    "binary921.py"
+)) {
+    $candidate = Join-Path $repo "tools\$name"
+    Copy-Required $candidate (Join-Path $stage $name)
+}
+
+$schemaDir = Join-Path $stage "schemas"
+New-Item -ItemType Directory -Force -Path $schemaDir | Out-Null
+foreach ($name in @(
+    "prod2u_program_sram_receipt.schema.json",
+    "prod2u_evidence_manifest.schema.json",
+    "prod2u_final_gate.schema.json",
+    "prod2u_td_build_receipt.schema.json"
+)) {
+    $candidate = Join-Path $repo "schemas\$name"
+    Copy-Required $candidate (Join-Path $schemaDir $name)
+}
+
+$startHereTemplate = Join-Path $repo "docs\prod2u-start-here.zh-CN.md"
+if (-not (Test-Path -LiteralPath $startHereTemplate -PathType Leaf)) { throw "Prod2U START-HERE template is missing: $startHereTemplate" }
+$startHere = (Get-Content -LiteralPath $startHereTemplate -Raw -Encoding UTF8).Replace("{{BUILD_ID}}", $buildId)
+Set-Content -LiteralPath (Join-Path $stage "START-HERE.zh-CN.md") -Encoding UTF8 -Value $startHere
+Copy-Required (Join-Path $repo "docs\prod2u-program-sram-runbook.zh-CN.md") (Join-Path $stage "prod2u-program-sram-runbook.zh-CN.md")
+Copy-Required (Join-Path $repo "docs\images\prod2u-con77-con78-rs232-schematic.png") (Join-Path $stage "images\prod2u-con77-con78-rs232-schematic.png")
+$schematicSource = Join-Path $repo "reference\original\schematics\FCB_FPGA+MCU0611.pdf"
+if (-not (Test-Path -LiteralPath $schematicSource -PathType Leaf)) { throw "Authoritative schematic is missing: $schematicSource" }
+
+$manifest = [ordered]@{
+    schema = "prod2u-package-manifest-v1"
+    status = "pass"
+    package_name = $packageName
+    profile = "prod2u-bmc-replay-binary921"
+    profile_id = 3
+    protocol = "binary921"
+    build_identity = [ordered]@{
+        build_id = $buildId
+        source_manifest_sha256 = $sourceSha
+        source_manifest_path = "source-manifest.json"
+    }
+    bitstream = [ordered]@{ path = "fw.bit"; sha256 = $bitSha }
+    td_receipt = [ordered]@{ path = "td.json"; sha256 = Get-Sha256 (Join-Path $stage "td.json") }
+    bmc_replay_payload = [ordered]@{
+        path = "bmc-replay-payload.json"
+        sha256 = Get-Sha256 (Join-Path $stage "bmc-replay-payload.json")
+        reply_sha256 = ([string]$bmc.reply_sha256).ToLowerInvariant()
+        source = "real_bmc_capture"
+    }
+    jtag_programming = [ordered]@{
+        operation = "PROGRAM_SRAM"
+        cable_index = 0
+        speed_code = 2
+        speed_hz = 200000
+        attempt_limit = 1
+        automatic_retry = $false
+        power_cycle_required = $false
+        board_power_required = $true
+    }
+    startup_chain = [ordered]@{
+        automatic_program_sram = $true
+        ready_payload_bytes = 7
+        preflight_opens_al_link = $false
+        evidence_order = "raw-first"
+    }
+    repository_gate = [ordered]@{
+        name = "final-gate-v2"
+        role = "prod2u_subgate_input"
+    }
+    ports = [ordered]@{
+        combined_host_debug = [ordered]@{
+            default = "COM5"
+            baud = 921600
+            fpga_tx = "M10"
+            fpga_rx = "N11"
+            board_connector = "CON78"
+            external_level = "RS232"
+            connector_pins = [ordered]@{ tx = 1; rx = 2; ground = @(3, 4) }
+        }
+        bmc_replay = [ordered]@{
+            baud = 115200
+            fpga_tx = "L10"
+            fpga_rx = "M9"
+            board_connector = "CON77"
+            external_level = "RS232"
+            connector_pins = [ordered]@{ tx = 1; rx = 2; ground = @(3, 4) }
+        }
+    }
+    documentation = [ordered]@{
+        schematic_source = "reference/original/schematics/FCB_FPGA+MCU0611.pdf"
+        schematic_source_sha256 = Get-Sha256 $schematicSource
+        uart_connector_image = "images/prod2u-con77-con78-rs232-schematic.png"
+        uart_connector_image_sha256 = Get-Sha256 (Join-Path $stage "images\prod2u-con77-con78-rs232-schematic.png")
+        physical_pin1_orientation_status = "blocked_waiting_for_board_marker_or_continuity"
+    }
+    real_fan_ptc_hardware_status = "not_run"
+    authority_boundary = "SRAM programming, build identity, binary921 control, and optional BMC replay evidence only; no thermal or real load qualification."
+}
+$manifest | ConvertTo-Json -Depth 32 | Set-Content -LiteralPath (Join-Path $stage "manifest.json") -Encoding UTF8
+
+$inventory = @()
+Get-ChildItem -LiteralPath $stage -Recurse -File | Sort-Object FullName | ForEach-Object {
+    if ($_.Name -ne "sha256-inventory.json") {
+        $inventory += [ordered]@{
+            path = $_.FullName.Substring($stage.Length).TrimStart('\').Replace('\', '/')
+            size = $_.Length
+            sha256 = Get-Sha256 $_.FullName
+        }
+    }
+}
+[ordered]@{
+    schema = "prod2u-package-sha256-inventory-v1"
+    package_name = $packageName
+    build_id = $buildId
+    inventory = $inventory
+} | ConvertTo-Json -Depth 16 | Set-Content -LiteralPath (Join-Path $stage "sha256-inventory.json") -Encoding UTF8
+
+$zipPath = Join-Path $outFull ($packageName + ".zip")
+$sidecar = $zipPath + ".sha256.txt"
+foreach ($path in @($zipPath, $sidecar)) {
+    if (Test-Path -LiteralPath $path) {
+        if (-not $ForceOverwrite) { throw "Package artifact already exists: $path" }
+        Remove-Item -LiteralPath $path -Force
+    }
+}
+Compress-Archive -Path (Join-Path $stage "*") -DestinationPath $zipPath -Force
+$zipSha = Get-Sha256 $zipPath
+Set-Content -LiteralPath $sidecar -Encoding ASCII -Value ("{0}  {1}" -f $zipSha, (Split-Path -Leaf $zipPath))
+
+[ordered]@{
+    status = "pass"
+    package_folder = $stage
+    package_zip = $zipPath
+    package_zip_sha256 = $zipSha
+    start_here = Join-Path $stage "START-HERE.zh-CN.md"
+} | ConvertTo-Json -Depth 8

+ 323 - 19
tools/pid_harness.py

@@ -1,4 +1,4 @@
-#!/usr/bin/env python3
+#!/usr/bin/env python3
 """Layered offline verification harness for pid_study_01."""
 
 from __future__ import annotations
@@ -21,6 +21,8 @@ from typing import Any
 
 sys.dont_write_bytecode = True
 
+from prod2u_build_identity import build_source_manifest, source_file_identity, validate_source_manifest
+
 from pid_contract_model import (
     ACTUATOR_REASON_FAN_FALLBACK,
     ACTUATOR_REASON_HOST_TIMEOUT,
@@ -160,6 +162,7 @@ TD_TOP_PROFILES = {
         "bmc_uart_baud": 115200,
         "debug_uart_baud": 921600,
         "debug_uart_clks_per_bit": 27,
+        "por_cycles": 1024,
         "live_bmc_link_status": "not_used",
         "requires_verified_real_fan_ptc_pin_map": True,
         "authority_boundary": "SRAM-only debug-photo-uart-bmc-replay diagnostic evidence. photo-visible UART wiring is retained while the BMC UART stream is driven by PC replay from a real BMC capture; it does not claim a live BMC link, real thermal performance, production PTC/FAN qualification, flash, or PID closed-loop pass.",
@@ -247,18 +250,18 @@ TD_TOP_PROFILES = {
         "requires_verified_real_fan_ptc_pin_map": True,
         "authority_boundary": "SRAM-only formal-uart1-bmc-replay-binary921 diagnostic evidence. BMC replay uses UART1 pins, host control uses UART2 pins, DebugPort uses M14/M15 spare GPIO, and real HEAT/FAN/FG/INSTALL pinout is retained. It does not claim a live BMC link, UART1/2 hardware access, real thermal performance, production PTC/FAN qualification, flash, or PID closed-loop pass until TD and board evidence pass.",
     },
-    "uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921": {
+    "prod2u_bmc_replay_binary921": {
         "mode": "implementation",
         "display_name": "Production temperature board two-UART binary921 diagnostic with PC replay from a real BMC capture",
-        "top_module": "uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top",
-        "source_prj": "td/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.prj",
-        "build_subdir": "uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921",
-        "syn_script": "uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.tcl",
-        "phy_script": "uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.tcl",
-        "bitstream": "uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921.bit",
-        "area_report": "uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_phy.area",
-        "timing_report": "uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_pr.timing",
-        "pin_profile": "production-two-uart-bmc-replay-binary921",
+        "top_module": "prod2u_bmc_replay_binary921_top",
+        "source_prj": "td/prod2u_bmc_replay_binary921.prj",
+        "build_subdir": "prod2u_bmc_replay_binary921",
+        "syn_script": "prod2u_bmc_replay_binary921.tcl",
+        "phy_script": "prod2u_bmc_replay_binary921.tcl",
+        "bitstream": "prod2u_bmc_replay_binary921.bit",
+        "area_report": "prod2u_bmc_replay_binary921_phy.area",
+        "timing_report": "prod2u_bmc_replay_binary921_pr.timing",
+        "pin_profile": "prod2u-bmc-replay-binary921",
         "protocol": "binary921",
         "transport": "combined_host_debug_uart",
         "bmc_source": "pc_replay_from_real_bmc_capture",
@@ -272,6 +275,28 @@ TD_TOP_PROFILES = {
         "debug_uart_clks_per_bit": 27,
         "live_bmc_link_status": "not_used",
         "requires_verified_real_fan_ptc_pin_map": True,
+        "runtime_profile": "prod2u-bmc-replay-binary921",
+        "source_manifest_inputs": [
+            "src/rtl/uart_rx_8n1.v",
+            "src/rtl/uart_tx_8n1.v",
+            "src/rtl/bmc_uart_raw48_poll_lite.v",
+            "src/rtl/binary921_crc16.v",
+            "src/rtl/binary921_frame_tx.v",
+            "src/rtl/binary921_host_rx.v",
+            "src/rtl/prod2u_por.v",
+            "src/rtl/binary921_diag_core.v",
+            "src/top/prod2u_bmc_replay_binary921_top.v",
+            "constraints/prod2u_bmc_replay_binary921.adc",
+            "constraints/pid_study_01.sdc",
+            "td/prod2u_bmc_replay_binary921.prj",
+            "td/syn/prod2u_bmc_replay_binary921.tcl",
+            "td/phy/prod2u_bmc_replay_binary921.tcl",
+            "config/pin_inventory.fcb_fpga_mcu0611.json",
+            "docs/j6-bmc-replay-binary921-protocol-v1.zh-CN.md",
+            "tools/prod2u_build_identity.py",
+            "tools/pid_harness.py",
+            "tools/pin_inventory.py",
+        ],
         "authority_boundary": "SRAM-only production-two-uart-bmc-replay-binary921 evidence. BMC replay uses UART1 L10/M9, combined Host+Debug binary921 uses UART2 M10/N11 at 921600, and real HEAT/FAN/FG/INSTALL pinout is retained. JTAG uses J3 and PROGRAM_SRAM only. It does not claim live BMC, flash, real thermal performance, production PTC/FAN qualification, or PID closed-loop pass.",
     },
 }
@@ -305,6 +330,7 @@ VERILATOR_LINT_WAIVERS = [
     "VARHIDDEN",       # Verilog task ports reuse contract field names locally.
     "CASEINCOMPLETE",  # Source mux defaults to fake source for unknown selections.
     "SYNCASYNCNET",    # Top-level reset is used by async-reset IP and sync debug wrapper logic.
+    "PINCONNECTEMPTY", # Optional debug/status outputs are intentionally left unconnected.
 ]
 
 
@@ -368,8 +394,20 @@ def is_td_generated_output(path: Path) -> bool:
     return False
 
 
-def clean_td_outputs(project_root: Path = ROOT) -> dict[str, Any]:
-    td_dirs = [project_root / "td" / "build" / "syn", project_root / "td" / "build" / "phy"]
+def clean_td_outputs(project_root: Path = ROOT, *, top: str | None = None) -> dict[str, Any]:
+    td_dirs: list[Path] = []
+    if top is None:
+        td_dirs.extend([project_root / "td" / "build" / "syn", project_root / "td" / "build" / "phy"])
+    else:
+        if top not in TD_TOP_PROFILES:
+            raise ValueError(f"unsupported TD top profile: {top}")
+        build_subdir = TD_TOP_PROFILES[top].get("build_subdir")
+        if build_subdir:
+            profile_root = project_root / "td" / "build" / str(build_subdir)
+            td_dirs.extend([profile_root / "syn", profile_root / "phy"])
+        else:
+            td_dirs.extend([project_root / "td" / "build" / "syn", project_root / "td" / "build" / "phy"])
+    td_dirs = list(dict.fromkeys(td_dirs))
     td_root_generated = project_root / "td"
     project_root_generated_patterns = ["td_*.log", "td_*.logw", "minidump-*.dmp"]
     project_log_generated_patterns = ["log/bw_*.log", "log/bw_*.logw"]
@@ -698,6 +736,134 @@ def _copy_td_project_payload(prj: Path, build_dir: Path, top: str) -> None:
     prj.write_text(text, encoding="utf-8")
 
 
+def _prepare_prod2u_build_identity(top: str, build_dirs: tuple[Path, Path]) -> dict[str, Any] | None:
+    profile = TD_TOP_PROFILES[top]
+    manifest_inputs = profile.get("source_manifest_inputs")
+    if not isinstance(manifest_inputs, list):
+        return None
+    top_relative = f"src/top/{profile['top_module']}.v"
+    manifest = build_source_manifest(
+        root=ROOT,
+        inputs=[ROOT / str(relative) for relative in manifest_inputs],
+        profile=str(profile["runtime_profile"]),
+        td_version="6.2.2.198412",
+        normalizations={
+            top_relative: "prod2u_build_id_zero",
+            str(profile["source_prj"]): "prod2u_td_staged_paths",
+        },
+    )
+    build_id = str(manifest["build_id"])
+    top_name = str(profile["top_module"]) + ".v"
+    pattern = re.compile(r"parameter \[31:0\] BUILD_ID = 32'h[0-9A-Fa-f]{8}")
+    replacement = f"parameter [31:0] BUILD_ID = 32'h{build_id}"
+    for build_dir in build_dirs:
+        (build_dir / "source-manifest.json").write_text(
+            json.dumps(manifest, indent=2) + "\n",
+            encoding="utf-8",
+            newline="\n",
+        )
+        staged_top = build_dir / "src" / "top" / top_name
+        source = staged_top.read_text(encoding="ascii")
+        patched, count = pattern.subn(replacement, source, count=1)
+        if count != 1:
+            raise RuntimeError(f"unable to embed Prod2U build ID in staged top: {staged_top}")
+        staged_top.write_text(patched, encoding="ascii", newline="\n")
+    return manifest
+
+
+def read_prod2u_staged_identity(top: str, syn_build: Path, phy_build: Path) -> dict[str, Any]:
+    profile = TD_TOP_PROFILES[top]
+    if not isinstance(profile.get("source_manifest_inputs"), list):
+        return {"status": "not_applicable"}
+    manifests: list[dict[str, Any]] = []
+    for build_dir in (syn_build, phy_build):
+        path = build_dir / "source-manifest.json"
+        try:
+            payload = json.loads(path.read_text(encoding="utf-8"))
+        except (OSError, json.JSONDecodeError) as exc:
+            return {"status": "fail", "reason": f"unreadable source manifest: {path}: {exc}"}
+        if not isinstance(payload, dict):
+            return {"status": "fail", "reason": f"invalid source manifest object: {path}"}
+        manifests.append(payload)
+    if manifests[0] != manifests[1]:
+        return {"status": "fail", "reason": "syn/phy source manifests differ"}
+    manifest = manifests[0]
+    manifest_validation = validate_source_manifest(manifest, root=ROOT)
+    if manifest_validation["status"] != "pass":
+        return {
+            "status": "fail",
+            "reason": f"source manifest validation failed: {manifest_validation['failures']}",
+        }
+    source_hash = str(manifest.get("source_manifest_sha256", ""))
+    build_id = str(manifest.get("build_id", ""))
+    if (
+        manifest.get("schema") != "prod2u-source-manifest-v1"
+        or manifest.get("profile") != profile.get("runtime_profile")
+        or not re.fullmatch(r"[0-9a-f]{64}", source_hash)
+        or not re.fullmatch(r"[0-9A-F]{8}", build_id)
+        or build_id != source_hash[:8].upper()
+    ):
+        return {"status": "fail", "reason": "source manifest identity contract mismatch"}
+    literal = f"parameter [31:0] BUILD_ID = 32'h{build_id}"
+    top_name = str(profile["top_module"]) + ".v"
+    observed_manifests: list[list[dict[str, Any]]] = []
+    for build_dir, script_key in ((syn_build, "syn_script"), (phy_build, "phy_script")):
+        staged_top = build_dir / "src" / "top" / top_name
+        if literal not in staged_top.read_text(encoding="ascii"):
+            return {"status": "fail", "reason": f"staged top does not embed build ID: {staged_top}"}
+        observed_rows: list[dict[str, Any]] = []
+        for row in manifest["files"]:
+            relative = str(row["path"])
+            staged_path = build_dir / relative
+            if relative == str(profile.get("source_prj")):
+                staged_path = build_dir / str(profile[script_key]).replace(".tcl", ".prj")
+            elif relative == f"td/{script_key.split('_', 1)[0]}/{profile[script_key]}":
+                staged_path = build_dir / str(profile[script_key])
+            elif not staged_path.is_file():
+                if relative.startswith(("src/", "constraints/")):
+                    return {"status": "fail", "reason": f"staged source file is missing: {build_dir / relative}"}
+                continue
+            identity = source_file_identity(
+                staged_path,
+                str(row["normalization"]) if row.get("normalization") is not None else None,
+            )
+            if (
+                (row.get("normalization") is None and identity["size"] != row["size"])
+                or identity["normalized_sha256"] != row["sha256"]
+            ):
+                return {"status": "fail", "reason": f"staged source identity mismatch: {staged_path}"}
+            observed_rows.append({"path": relative, **identity})
+        observed_manifests.append(observed_rows)
+    merged_rows: dict[str, dict[str, Any]] = {}
+    for observed_rows in observed_manifests:
+        for row in observed_rows:
+            previous = merged_rows.get(str(row["path"]))
+            if previous is not None and previous != row:
+                return {"status": "fail", "reason": f"syn/phy staged source identities differ: {row['path']}"}
+            merged_rows[str(row["path"])] = row
+    staged_files = [merged_rows[path] for path in sorted(merged_rows)]
+    staged_payload = {
+        "source_manifest_sha256": source_hash,
+        "build_id": build_id,
+        "files": staged_files,
+    }
+    staged_manifest_sha256 = hashlib.sha256(
+        json.dumps(staged_payload, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode("ascii")
+    ).hexdigest()
+    return {
+        "status": "pass",
+        "schema": manifest["schema"],
+        "profile": manifest["profile"],
+        "source_manifest_sha256": source_hash,
+        "build_id": build_id,
+        "files": manifest.get("files", []),
+        "staged_files": staged_files,
+        "staged_manifest_sha256": staged_manifest_sha256,
+        "syn_manifest": str(syn_build / "source-manifest.json"),
+        "phy_manifest": str(phy_build / "source-manifest.json"),
+    }
+
+
 def write_td_gui_project_from_prj(prj: Path, al_path: Path, project_root: Path) -> None:
     """Write a TD GUI .al project from the batch .prj source list."""
     tree = ET.parse(prj)
@@ -739,6 +905,7 @@ def prepare_td_build_dirs(top: str = DEFAULT_TD_TOP) -> tuple[Path, Path]:
     for build_dir, script_key in [(syn_build, "syn_script"), (phy_build, "phy_script")]:
         prj = build_dir / str(profile[script_key]).replace(".tcl", ".prj")
         _copy_td_project_payload(prj, build_dir, top)
+    _prepare_prod2u_build_identity(top, (syn_build, phy_build))
     return syn_build, phy_build
 
 
@@ -1008,7 +1175,7 @@ def hdl_testbenches() -> list[dict[str, Any]]:
             ],
         },
         {
-            "name": "uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top_tb",
+            "name": "prod2u_bmc_replay_binary921_top_tb",
             "sources": [
                 "src/rtl/uart_tx_8n1.v",
                 "src/rtl/uart_rx_8n1.v",
@@ -1016,11 +1183,16 @@ def hdl_testbenches() -> list[dict[str, Any]]:
                 "src/rtl/binary921_crc16.v",
                 "src/rtl/binary921_frame_tx.v",
                 "src/rtl/binary921_host_rx.v",
+                "src/rtl/prod2u_por.v",
                 "src/rtl/binary921_diag_core.v",
-                "src/top/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top.v",
-                "tests/sim/uart_rs232_j6_host_sensor_real_fan_ptc_production_two_uart_bmc_replay_binary921_top_tb.v",
+                "src/top/prod2u_bmc_replay_binary921_top.v",
+                "tests/sim/prod2u_bmc_replay_binary921_top_tb.v",
             ],
         },
+        {
+            "name": "prod2u_por_tb",
+            "sources": ["src/rtl/prod2u_por.v", "tests/sim/prod2u_por_tb.v"],
+        },
         {"name": "bmc_uart_phy_bridge_tb", "sources": ["src/rtl/bmc_uart_phy_bridge.v", "tests/sim/bmc_uart_phy_bridge_tb.v"]},
         {"name": "bmc_uart_ascii_poll_tb", "sources": ["src/rtl/bmc_uart_ascii_poll.v", "tests/sim/bmc_uart_ascii_poll_tb.v"]},
         {"name": "bmc_dimm_frame_parser_tb", "sources": ["src/rtl/bmc_dimm_frame_parser.v", "tests/sim/bmc_dimm_frame_parser_tb.v"]},
@@ -1097,6 +1269,11 @@ def verilator_lint_targets() -> list[dict[str, Any]]:
         for source in testbench["sources"]:
             if source.startswith(("src/rtl/", "src/top/")) and source not in sources:
                 sources.append(source)
+    # The active Prod2U source deliberately instantiates an undefined module
+    # when BUILD_ID is left at zero so direct TD builds fail closed. Verilator
+    # sees the default branch during repository-wide lint, so provide a
+    # lint-only definition without adding it to any TD project or bitstream.
+    sources.append("tests/verilator_prod2u_build_id_guard_stub.v")
     return [
         {
             "name": "pid_contract_rtl_and_tops",
@@ -3162,11 +3339,88 @@ def cmd_analyze_bundle(args: argparse.Namespace) -> int:
     return 0 if payload["status"] == "pass" else 1
 
 
+POR_INIT_MARKER_RE = re.compile(r"^PROD2U_POR_INIT\|([^|]+)\|([^|\r\n]+)$", re.MULTILINE)
+
+
+def parse_prod2u_por_init_probe(stdout: str, *, por_cycles: int) -> dict[str, Any]:
+    counter_width = max(1, (max(1, por_cycles) - 1).bit_length())
+    expected_names = ["u_por/por_reset_n_reg"] + [
+        f"u_por/por_count_reg[{index}]" for index in range(counter_width)
+    ]
+    observed: dict[str, str] = {}
+    failures: list[str] = []
+    for name, init_value in POR_INIT_MARKER_RE.findall(stdout):
+        if name not in expected_names:
+            continue
+        if name in observed:
+            failures.append(f"duplicate_register:{name}")
+            continue
+        observed[name] = init_value.strip()
+
+    for name in expected_names:
+        if name not in observed:
+            failures.append(f"missing_register:{name}")
+        elif observed[name] != "0":
+            failures.append(f"nonzero_init:{name}:{observed[name]}")
+    return {
+        "status": "pass" if not failures else "fail",
+        "por_cycles": por_cycles,
+        "counter_width": counter_width,
+        "expected_init": "0",
+        "register_count": len(observed),
+        "registers": [{"name": name, "init": observed[name]} for name in sorted(observed)],
+        "failures": failures,
+    }
+
+
+def run_prod2u_por_init_probe(syn_build: Path, *, por_cycles: int) -> dict[str, Any]:
+    syn_build = syn_build.resolve()
+    gate_db = syn_build / "prod2u_bmc_replay_binary921_gate.db"
+    script = syn_build / "prod2u_por_init_probe.tcl"
+    gate_db_tcl = gate_db.as_posix()
+    script.write_text(
+        "\n".join(
+            [
+                "import_device ef2_4.db -package EF2L45BG256B",
+                f"import_db {{{gate_db_tcl}}}",
+                "set por_cells [get_cells -hier -full_hier {*u_por/por*_reg*}]",
+                "foreach cell $por_cells {",
+                '    puts "PROD2U_POR_INIT|$cell|[get_property INIT $cell]"',
+                "}",
+                "",
+            ]
+        ),
+        encoding="ascii",
+        newline="\n",
+    )
+    result = run_td_script(syn_build, script.name)
+    parsed = parse_prod2u_por_init_probe(result.stdout, por_cycles=por_cycles)
+    parsed.update(
+        {
+            "script": str(script),
+            "gate_db": str(gate_db),
+            "returncode": result.returncode,
+            "log_has_error": td_log_has_error(result.stdout, result.stderr),
+            "stdout_tail": result.stdout[-4000:],
+            "stderr_tail": result.stderr[-4000:],
+        }
+    )
+    if result.returncode != 0 or parsed["log_has_error"]:
+        parsed["status"] = "fail"
+        parsed["failures"].append("td_por_probe_execution_failed")
+    return parsed
+
+
 def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
     if top not in TD_TOP_PROFILES:
         return {"status": "fail", "reason": f"unsupported TD top profile: {top}", "top": top}
 
     profile = TD_TOP_PROFILES[top]
+    receipt_metadata = (
+        {"schema": "prod2u-td-build-receipt-v1"}
+        if top == "prod2u_bmc_replay_binary921"
+        else {}
+    )
 
     pin_profile_payload: dict[str, Any] | None = None
     if profile.get("requires_verified_real_fan_ptc_pin_map"):
@@ -3177,6 +3431,7 @@ def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
             )
         except OSError as exc:
             return {
+                **receipt_metadata,
                 "status": "blocked_missing_real_fan_ptc_pin_inventory",
                 "top": top,
                 "top_module": profile["top_module"],
@@ -3190,6 +3445,7 @@ def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
             }
         if pin_profile_payload.get("status") != "pass":
             return {
+                **receipt_metadata,
                 "status": "blocked_pin_profile_invalid",
                 "td_executable": str(TD_EXE),
                 "top": top,
@@ -3218,6 +3474,7 @@ def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
 
     if not run:
         return {
+            **receipt_metadata,
             "status": "skipped",
             "reason": "TD build probe not requested. Use td-build --run or td --run.",
             "top": top,
@@ -3228,11 +3485,12 @@ def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
         }
 
     if not TD_EXE.is_file():
-        return {"status": "blocked", "reason": f"missing TD executable: {TD_EXE}"}
+        return {**receipt_metadata, "status": "blocked", "reason": f"missing TD executable: {TD_EXE}"}
 
     if profile["mode"] == "elaboration":
         elaboration = run_td_elaboration(str(profile["top_module"]))
         return {
+            **receipt_metadata,
             "status": elaboration["status"],
             "td_executable": str(TD_EXE),
             "top": top,
@@ -3252,6 +3510,7 @@ def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
             script_text = script_path.read_text(encoding="utf-8")
         except OSError as exc:
             return {
+                **receipt_metadata,
                 "status": "fail",
                 "td_executable": str(TD_EXE),
                 "top": top,
@@ -3266,6 +3525,7 @@ def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
         forbidden = td_forbidden_script_markers(script_text)
         if forbidden:
             return {
+                **receipt_metadata,
                 "status": "fail",
                 "td_executable": str(TD_EXE),
                 "top": top,
@@ -3280,9 +3540,10 @@ def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
                 "timing": None,
             }
 
-    clean = clean_td_outputs(ROOT)
+    clean = clean_td_outputs(ROOT, top=top)
     if clean["status"] != "pass":
         return {
+            **receipt_metadata,
             "status": "fail",
             "td_executable": str(TD_EXE),
             "top": top,
@@ -3302,10 +3563,46 @@ def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
         }
 
     syn_build, phy_build = prepare_td_build_dirs(top)
+    build_identity = read_prod2u_staged_identity(top, syn_build, phy_build)
+    if build_identity.get("status") not in ("pass", "not_applicable"):
+        return {
+            **receipt_metadata,
+            "status": "fail_build_identity",
+            "td_executable": str(TD_EXE),
+            "top": top,
+            "top_module": profile["top_module"],
+            "display_name": profile["display_name"],
+            "mode": profile["mode"],
+            "pin_profile": profile.get("pin_profile"),
+            "build_identity": build_identity,
+            "clean": clean,
+            "syn": None,
+            "phy": None,
+            "bitstream": None,
+            "resources": None,
+            "timing": None,
+            "authority_boundary": profile.get(
+                "authority_boundary",
+                "TD implementation build evidence only. It does not download, program flash, open cables, or certify hardware.",
+            ),
+        }
     syn = run_td_script(syn_build, str(profile["syn_script"]))
     syn_has_error = td_log_has_error(syn.stdout, syn.stderr)
+    por_initialization = {
+        "status": "not_applicable",
+        "reason": f"POR initialization probe is not required for TD top profile {top}",
+    }
+    if top == "prod2u_bmc_replay_binary921" and syn.returncode == 0 and not syn_has_error:
+        por_initialization = run_prod2u_por_init_probe(
+            syn_build,
+            por_cycles=int(profile.get("por_cycles", 1024)),
+        )
     phy = None
-    if syn.returncode == 0 and not syn_has_error:
+    if (
+        syn.returncode == 0
+        and not syn_has_error
+        and por_initialization.get("status") in ("pass", "not_applicable")
+    ):
         phy = run_td_script(phy_build, str(profile["phy_script"]))
 
     bit = phy_build / str(profile["bitstream"])
@@ -3330,10 +3627,13 @@ def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
         and timing_gate["status"] == "pass"
         and not syn_has_error
         and not phy_has_error
+        and build_identity.get("status") in ("pass", "not_applicable")
+        and por_initialization.get("status") in ("pass", "not_applicable")
     )
     td_version = parse_td_version(syn.stdout, syn.stderr, "" if phy is None else phy.stdout, "" if phy is None else phy.stderr)
 
     result = {
+        **receipt_metadata,
         "status": "pass" if td_ok else "fail",
         "td_executable": str(TD_EXE),
         "td_version": td_version,
@@ -3351,6 +3651,10 @@ def td_build_payload(run: bool, top: str = DEFAULT_TD_TOP) -> dict[str, Any]:
         "syn_build_dir": str(syn_build),
         "phy_build_dir": str(phy_build),
         "td_invocation": "script_argument",
+        "build_identity": build_identity,
+        "por_initialization": por_initialization,
+        "source_manifest_sha256": build_identity.get("source_manifest_sha256"),
+        "build_id": build_identity.get("build_id"),
         "clean": clean,
         "syn": {
             "returncode": syn.returncode,

+ 10 - 5
tools/pin_inventory.py

@@ -280,6 +280,7 @@ def diagnostic_profile_assignments(inventory: dict[str, Any], profile: str) -> d
         "debug-photo-bmc-replay-binary921",
         "formal-uart1-bmc-replay-binary921",
         "production-two-uart-bmc-replay-binary921",
+        "prod2u-bmc-replay-binary921",
     }
     if profile not in supported_profiles:
         return {
@@ -299,6 +300,10 @@ def diagnostic_profile_assignments(inventory: dict[str, Any], profile: str) -> d
     reserved_uart_use_policy = "reserved_unused"
     uart_aliases: dict[str, str] = {}
     allowed_reserved_balls: set[str] = set()
+    production_profile = profile in {
+        "production-two-uart-bmc-replay-binary921",
+        "prod2u-bmc-replay-binary921",
+    }
     if profile in {"temp-uart-ptc-remap", "debug-photo-uart-bmc-replay", "debug-photo-bmc-replay-binary921"}:
         uart_assignments = dict(LOCKED_DEBUG_UART_ASSIGNMENTS)
         for item in TEMP_UART_PTC_REMAP_SUBSTITUTIONS.values():
@@ -346,7 +351,7 @@ def diagnostic_profile_assignments(inventory: dict[str, Any], profile: str) -> d
             "and all three diagnostic UARTs move to verified spare GPIO; schematic UART1/2 are reserved unused."
         )
     else:
-        if profile == "production-two-uart-bmc-replay-binary921":
+        if production_profile:
             uart_assignments = dict(PRODUCTION_TWO_UART_BMC_REPLAY_BINARY921_ASSIGNMENTS)
         elif profile == "formal-uart1-bmc-replay-binary921":
             uart_assignments = dict(FORMAL_UART1_BMC_REPLAY_BINARY921_ASSIGNMENTS)
@@ -358,7 +363,7 @@ def diagnostic_profile_assignments(inventory: dict[str, Any], profile: str) -> d
         live_bmc_link_status = "not_used"
         hardware_access_status = (
             "production_uart1_uart2_access_confirmed_by_user"
-            if profile == "production-two-uart-bmc-replay-binary921"
+            if production_profile
             else "blocked_waiting_for_uart1_uart2_access"
         )
         reserved_uart_use_policy = "intentional_uart1_uart2_bmc_replay_host"
@@ -366,7 +371,7 @@ def diagnostic_profile_assignments(inventory: dict[str, Any], profile: str) -> d
             "bmc_replay_uart_tx": "bmc_uart_tx",
             "bmc_replay_uart_rx": "bmc_uart_rx",
         }
-        if profile == "production-two-uart-bmc-replay-binary921":
+        if production_profile:
             uart_aliases.update(
                 {
                     "combined_debug_host_uart_tx": "host_uart_tx",
@@ -374,7 +379,7 @@ def diagnostic_profile_assignments(inventory: dict[str, Any], profile: str) -> d
                 }
             )
         allowed_reserved_balls = {"L10", "M9", "M10", "N11"}
-        if profile == "production-two-uart-bmc-replay-binary921":
+        if production_profile:
             boundary = (
                 "Production two-UART BMC-replay binary921 profile for J3 SRAM-only bring-up: HEAT/FAN/FG/INSTALL stay on PDF/inventory pins, "
                 "BMC replay uses UART1 L10/M9 at 115200, and a combined Host+Debug binary921 port uses UART2 M10/N11 at 921600. "
@@ -423,7 +428,7 @@ def diagnostic_profile_assignments(inventory: dict[str, Any], profile: str) -> d
         "reserved_uart_use_policy": reserved_uart_use_policy,
         "bmc_source": bmc_source,
         "live_bmc_link_status": live_bmc_link_status,
-        "transport": "combined_host_debug_uart" if profile == "production-two-uart-bmc-replay-binary921" else "separate_host_debug_uart",
+        "transport": "combined_host_debug_uart" if production_profile else "separate_host_debug_uart",
         "hardware_access_status": hardware_access_status,
         "real_fan_ptc_hardware_status": hardware_status,
         "conflict_check": conflict,

+ 53 - 0
tools/prod2u.ps1

@@ -0,0 +1,53 @@
+param(
+    [Parameter(Position = 0)]
+    [ValidateSet("selftest", "preflight", "program-only", "collect-only", "all")]
+    [string]$Command = "selftest",
+    [string]$CombinedPort = "COM5",
+    [string]$Bitstream = ".\fw.bit",
+    [string]$TdReceipt = ".\td.json",
+    [string]$SourceManifest = ".\source-manifest.json",
+    [string]$BmcReplayReceipt = ".\bmc-replay-session.json",
+    [string]$OutputDir = ".\evidence-prod2u",
+    [string]$TdRoot = "",
+    [double]$DurationSeconds = 5.0,
+    [double]$ReadyTimeoutSeconds = 30.0,
+    [double]$PreProgramObserveSeconds = 0.1
+)
+
+$ErrorActionPreference = "Stop"
+$root = Split-Path -Parent $MyInvocation.MyCommand.Path
+$cli = Join-Path $root "prod2u_cli.py"
+$pythonCandidates = @(
+    (Join-Path $root ".codex\venv\Scripts\python.exe"),
+    (Join-Path (Split-Path -Parent $root) ".codex\venv\Scripts\python.exe"),
+    "python.exe",
+    "python"
+)
+$python = $null
+foreach ($candidate in $pythonCandidates) {
+    if ([System.IO.Path]::IsPathRooted($candidate)) {
+        if (Test-Path -LiteralPath $candidate) { $python = $candidate; break }
+    } elseif (Get-Command $candidate -ErrorAction SilentlyContinue) {
+        $python = $candidate
+        break
+    }
+}
+if (-not $python) { throw "Python 3 is required for the Prod2U harness" }
+
+$arguments = @($cli, $Command)
+if ($Command -ne "selftest") {
+    $arguments += @(
+        "--combined-port", $CombinedPort,
+        "--bitstream", $Bitstream,
+        "--td-receipt", $TdReceipt,
+        "--source-manifest", $SourceManifest,
+        "--bmc-replay-receipt", $BmcReplayReceipt,
+        "--output-dir", $OutputDir,
+        "--duration-sec", $DurationSeconds.ToString([System.Globalization.CultureInfo]::InvariantCulture),
+        "--ready-timeout-sec", $ReadyTimeoutSeconds.ToString([System.Globalization.CultureInfo]::InvariantCulture),
+        "--pre-program-observe-sec", $PreProgramObserveSeconds.ToString([System.Globalization.CultureInfo]::InvariantCulture)
+    )
+    if ($TdRoot) { $arguments += @("--td-root", $TdRoot) }
+}
+& $python -B @arguments
+exit $LASTEXITCODE

+ 474 - 0
tools/prod2u_bmc_replay.py

@@ -0,0 +1,474 @@
+#!/usr/bin/env python3
+"""Normalize and replay Prod2U BMC UART poll responses.
+
+The helper is dependency-free. It normalizes loose real-BMC serial text into
+the 48-byte DIMM payload expected by the CPLD poller, and the replay routine
+only writes a reply after the CPLD poll text has been observed.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import re
+import sys
+import time
+import uuid
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable, Protocol
+
+sys.dont_write_bytecode = True
+
+POLL_COMMAND_TEXT = "ipmitool raw 0x36 0x6c 0xdf 0xdd 0x00 0x03\n"
+POLL_COMMAND_BYTES = [0x36, 0x6C, 0xDF, 0xDD, 0x00, 0x03]
+EXPECTED_DIMM_COUNT = 24
+EXPECTED_PAYLOAD_BYTES = EXPECTED_DIMM_COUNT * 2
+
+
+class ReplayEndpoint(Protocol):
+    def read(self, size: int = 1) -> bytes: ...
+
+    def write(self, data: bytes) -> int: ...
+
+
+@dataclass
+class FakeSerialEndpoint:
+    initial_rx: bytes = b""
+
+    def __post_init__(self) -> None:
+        self._rx = bytearray(self.initial_rx)
+        self.written = b""
+
+    def read(self, size: int = 1) -> bytes:
+        if not self._rx:
+            return b""
+        count = min(size, len(self._rx))
+        chunk = bytes(self._rx[:count])
+        del self._rx[:count]
+        return chunk
+
+    def write(self, data: bytes) -> int:
+        self.written += data
+        return len(data)
+
+
+def utc_now() -> str:
+    return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
+
+
+def _extract_hex_bytes(text: str) -> list[int]:
+    values: list[int] = []
+    for match in re.finditer(r"(?<![0-9A-Za-z])(?:0x)?([0-9A-Fa-f]{2})(?![0-9A-Za-z])", text):
+        values.append(int(match.group(1), 16))
+    return values
+
+
+def _echo_ranges(values: list[int]) -> list[range]:
+    ranges: list[range] = []
+    width = len(POLL_COMMAND_BYTES)
+    if len(values) < width:
+        return ranges
+    for index in range(0, len(values) - width + 1):
+        if values[index : index + width] == POLL_COMMAND_BYTES:
+            ranges.append(range(index, index + width))
+    return ranges
+
+
+def _overlaps_echo(start: int, width: int, ranges: list[range]) -> bool:
+    end = start + width
+    return any(start < echo.stop and end > echo.start for echo in ranges)
+
+
+def _validate_temperature_window(window: list[int]) -> list[dict[str, Any]]:
+    temperatures: list[dict[str, Any]] = []
+    valid_count = 0
+    for index in range(EXPECTED_DIMM_COUNT):
+        integer = window[index * 2]
+        fraction = window[index * 2 + 1]
+        if integer == 0xFF and fraction == 0xFF:
+            temperatures.append(
+                {
+                    "id": index,
+                    "dimm": index + 1,
+                    "temperature_c": None,
+                    "integer_c": None,
+                    "fraction": None,
+                    "valid": False,
+                    "status": "missing",
+                    "raw_pair": [integer, fraction],
+                    "reason": "missing",
+                }
+            )
+            continue
+        if fraction > 99:
+            raise ValueError(f"DIMM {index:02d} fraction byte out of 0..99 range: 0x{fraction:02x}")
+        valid_count += 1
+        temperatures.append(
+            {
+                "id": index,
+                "dimm": index + 1,
+                "temperature_c": integer,
+                "integer_c": integer,
+                "fraction": fraction,
+                "valid": True,
+                "status": "valid",
+                "raw_pair": [integer, fraction],
+            }
+        )
+    if valid_count == 0:
+        raise ValueError("no present DIMM temperatures in BMC payload")
+    return temperatures
+
+
+def _find_payload_bytes(text: str) -> tuple[list[int], list[dict[str, Any]], int]:
+    values = _extract_hex_bytes(text)
+    if len(values) < EXPECTED_PAYLOAD_BYTES:
+        raise ValueError(f"BMC capture has {len(values)} data byte(s), expected at least 48")
+
+    echo_ranges = _echo_ranges(values)
+    rejected_echo_windows = 0
+    last_error: ValueError | None = None
+    for start in range(0, len(values) - EXPECTED_PAYLOAD_BYTES + 1):
+        if _overlaps_echo(start, EXPECTED_PAYLOAD_BYTES, echo_ranges):
+            rejected_echo_windows += 1
+            continue
+        window = values[start : start + EXPECTED_PAYLOAD_BYTES]
+        try:
+            return window, _validate_temperature_window(window), rejected_echo_windows
+        except ValueError as exc:
+            last_error = exc
+    if last_error is not None:
+        raise last_error
+    raise ValueError("no non-echo 48-byte DIMM payload candidate found")
+
+
+def normalize_bmc_capture_text(text: str, *, seq: int) -> dict[str, Any]:
+    values, temperatures, rejected_echo_windows = _find_payload_bytes(text)
+    reply_text = " ".join(f"{value:02x}" for value in values) + "\r\n"
+    valid_count = sum(1 for item in temperatures if item["valid"])
+    missing_count = len(temperatures) - valid_count
+    return {
+        "schema": "prod2u-bmc-replay-payload-v1",
+        "status": "pass",
+        "generated_at": utc_now(),
+        "source": "real_bmc_capture",
+        "bmc_source": "pc_replay_from_real_bmc_capture",
+        "live_bmc_link_status": "not_used",
+        "replay_mode": "poll_response",
+        "seq": seq,
+        "poll_text": POLL_COMMAND_TEXT.strip(),
+        "poll_command_text": POLL_COMMAND_TEXT,
+        "reply_text": reply_text,
+        "reply_sha256": hashlib.sha256(reply_text.encode("ascii")).hexdigest(),
+        "capture_text_sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(),
+        "byte_count": len(values),
+        "valid_count": valid_count,
+        "missing_count": missing_count,
+        "rejected_echo_windows": rejected_echo_windows,
+        "payload_hex": [f"{value:02x}" for value in values],
+        "temperatures": temperatures,
+        "safety": {
+            "unsolicited_reply_attempted": False,
+            "driver_install_attempted": False,
+            "programs_nonvolatile": False,
+        },
+        "authority_boundary": (
+            "PC replay replies only after observing the CPLD BMC poll text. "
+            "The payload comes from a prior real BMC capture and is not live BMC evidence."
+        ),
+    }
+
+
+def build_replay_payload(text: str, *, seq: int) -> dict[str, Any]:
+    return normalize_bmc_capture_text(text, seq=seq)
+
+
+def _validated_payload_reply(payload: dict[str, Any]) -> bytes:
+    if payload.get("schema") != "prod2u-bmc-replay-payload-v1":
+        raise ValueError("payload schema must be prod2u-bmc-replay-payload-v1")
+    if payload.get("status") != "pass":
+        raise ValueError("payload status must be pass")
+    if payload.get("source") != "real_bmc_capture":
+        raise ValueError("payload source must be real_bmc_capture")
+    if payload.get("bmc_source") != "pc_replay_from_real_bmc_capture":
+        raise ValueError("payload bmc_source is invalid")
+    if payload.get("live_bmc_link_status") != "not_used":
+        raise ValueError("payload live_bmc_link_status must be not_used")
+    if payload.get("replay_mode") != "poll_response":
+        raise ValueError("payload replay_mode must be poll_response")
+    if not isinstance(payload.get("seq"), int) or isinstance(payload["seq"], bool) or payload["seq"] < 1:
+        raise ValueError("payload seq must be a positive integer")
+    if payload.get("poll_command_text") != POLL_COMMAND_TEXT or payload.get("poll_text") != POLL_COMMAND_TEXT.strip():
+        raise ValueError("payload poll command does not match the replay contract")
+    if payload.get("byte_count") != EXPECTED_PAYLOAD_BYTES:
+        raise ValueError(f"payload byte_count must be {EXPECTED_PAYLOAD_BYTES}")
+    if not isinstance(payload.get("valid_count"), int) or not isinstance(payload.get("missing_count"), int):
+        raise ValueError("payload DIMM counts must be integers")
+    if payload["valid_count"] + payload["missing_count"] != EXPECTED_DIMM_COUNT:
+        raise ValueError(f"payload DIMM counts must total {EXPECTED_DIMM_COUNT}")
+
+    payload_hex = payload.get("payload_hex")
+    if not isinstance(payload_hex, list) or len(payload_hex) != EXPECTED_PAYLOAD_BYTES:
+        raise ValueError(f"payload_hex must contain exactly {EXPECTED_PAYLOAD_BYTES} bytes")
+    try:
+        values = [int(str(value), 16) for value in payload_hex]
+    except (TypeError, ValueError) as exc:
+        raise ValueError("payload_hex contains an invalid byte") from exc
+    if any(value < 0 or value > 0xFF for value in values):
+        raise ValueError("payload_hex contains an out-of-range byte")
+
+    canonical_reply = " ".join(f"{value:02x}" for value in values) + "\r\n"
+    if payload.get("reply_text") != canonical_reply:
+        raise ValueError("payload reply_text does not match payload_hex")
+    reply_sha256 = str(payload.get("reply_sha256") or "")
+    if not re.fullmatch(r"[0-9a-fA-F]{64}", reply_sha256):
+        raise ValueError("payload reply_sha256 missing or invalid")
+    if hashlib.sha256(canonical_reply.encode("ascii")).hexdigest() != reply_sha256.lower():
+        raise ValueError("payload reply_sha256 does not match reply_text")
+    capture_sha256 = str(payload.get("capture_text_sha256") or "")
+    if not re.fullmatch(r"[0-9a-fA-F]{64}", capture_sha256):
+        raise ValueError("payload capture_text_sha256 missing or invalid")
+    return canonical_reply.encode("ascii")
+
+
+def run_poll_response_session(
+    endpoint: ReplayEndpoint,
+    payload: dict[str, Any],
+    *,
+    iterations: int,
+    timeout_sec: float,
+    receipt_callback: Callable[[dict[str, Any]], None] | None = None,
+) -> dict[str, Any]:
+    poll_text = str(payload.get("poll_command_text") or payload.get("poll_text") or POLL_COMMAND_TEXT)
+    poll = poll_text.encode("ascii")
+    reply = _validated_payload_reply(payload)
+    window = bytearray()
+    matched = 0
+    replies = 0
+    serial_write_count: int | None = None
+    serial_write_failed = False
+    session_id = uuid.uuid4().hex
+    started_at = utc_now()
+    last_reply_at: str | None = None
+    started = time.monotonic()
+    deadline = started + timeout_sec
+
+    def build_receipt(status: str) -> dict[str, Any]:
+        values = [int(str(value), 16) for value in payload.get("payload_hex", [])]
+        return {
+            "schema": "prod2u-bmc-replay-session-v1",
+            "status": status,
+            "session_id": session_id,
+            "generated_at": utc_now(),
+            "started_at": started_at,
+            "last_reply_at": last_reply_at,
+            "replay_mode": "poll_response",
+            "source": payload.get("source"),
+            "bmc_source": "pc_replay_from_real_bmc_capture",
+            "live_bmc_link_status": "not_used",
+            "matched_poll_count": matched,
+            "reply_count": replies,
+            "payload_reply_sha256": payload.get("reply_sha256"),
+            "reply_sha256": payload.get("reply_sha256"),
+            "capture_text_sha256": payload.get("capture_text_sha256"),
+            "byte_count": payload.get("byte_count"),
+            "valid_count": payload.get("valid_count"),
+            "missing_count": payload.get("missing_count"),
+            "payload_hex": payload.get("payload_hex"),
+            "payload_first": values[0] if values else None,
+            "payload_last": values[-1] if values else None,
+            "payload_checksum": sum(values) & 0xFFFF if values else None,
+            "rejected_echo_windows": payload.get("rejected_echo_windows"),
+            "unsolicited_reply_attempted": False,
+            "serial_write_expected_bytes": len(reply),
+            "serial_write_count": serial_write_count,
+            "elapsed_sec": round(time.monotonic() - started, 6),
+            "safety": {
+                "unsolicited_reply_attempted": False,
+                "driver_install_attempted": False,
+                "programs_nonvolatile": False,
+            },
+        }
+
+    if receipt_callback is not None:
+        receipt_callback(build_receipt("running"))
+
+    while matched < iterations and time.monotonic() < deadline:
+        chunk = endpoint.read(1)
+        if not chunk:
+            time.sleep(min(0.001, max(0.0, deadline - time.monotonic())))
+            continue
+        window += chunk
+        if len(window) > max(4096, len(poll) * 2):
+            del window[: len(window) - max(4096, len(poll) * 2)]
+        if poll in window:
+            written = endpoint.write(reply)
+            serial_write_count = written if isinstance(written, int) and not isinstance(written, bool) else None
+            if serial_write_count != len(reply):
+                serial_write_failed = True
+                break
+            matched += 1
+            replies += 1
+            last_reply_at = utc_now()
+            window.clear()
+            if receipt_callback is not None:
+                receipt_callback(build_receipt("pass"))
+
+    status = (
+        "blocked_serial_write_short"
+        if serial_write_failed
+        else "pass"
+        if matched == iterations
+        else "blocked_waiting_for_cpld_poll"
+    )
+    receipt = build_receipt(status)
+    if serial_write_failed and receipt_callback is not None:
+        receipt_callback(receipt)
+    return receipt
+
+
+def write_receipt_atomic(path: Path, payload: dict[str, Any]) -> None:
+    path = Path(path)
+    path.parent.mkdir(parents=True, exist_ok=True)
+    temporary = path.with_name(path.name + ".tmp")
+    temporary.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8", newline="\n")
+    temporary.replace(path)
+
+
+def cmd_normalize_capture(args: argparse.Namespace) -> int:
+    payload = normalize_bmc_capture_text(Path(args.input).read_text(encoding="utf-8", errors="replace"), seq=args.seq)
+    Path(args.payload).parent.mkdir(parents=True, exist_ok=True)
+    Path(args.payload).write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
+    if args.json:
+        print(json.dumps(payload, indent=2))
+    return 0
+
+
+def cmd_selftest(args: argparse.Namespace) -> int:
+    del args
+    sample = "\n".join(
+        [
+            "root@bmc:~# " + POLL_COMMAND_TEXT.strip(),
+            " ".join(f"{40 + index:02x} 00" for index in range(EXPECTED_DIMM_COUNT)),
+        ]
+    )
+    payload = build_replay_payload(sample, seq=1)
+    endpoint = FakeSerialEndpoint(initial_rx=b"\r\r" + POLL_COMMAND_TEXT.encode("ascii"))
+    receipt = run_poll_response_session(endpoint, payload, iterations=1, timeout_sec=0.1)
+    if receipt["status"] != "pass":
+        raise RuntimeError("poll-response selftest failed")
+    print("selftest=pass")
+    return 0
+
+
+def _load_payload(path: Path) -> dict[str, Any]:
+    payload = json.loads(path.read_text(encoding="utf-8"))
+    if not isinstance(payload, dict):
+        raise ValueError("payload must be a JSON object")
+    _validated_payload_reply(payload)
+    return payload
+
+
+def _open_serial_endpoint(port: str) -> ReplayEndpoint:
+    if not re.fullmatch(r"COM[0-9]+", port.upper()):
+        raise ValueError("port must be an explicit COM port such as COM9")
+    try:
+        import serial  # type: ignore
+    except ImportError as exc:
+        raise RuntimeError("pyserial is required for live replay; install it manually in the isolated lab.") from exc
+    endpoint = serial.Serial()
+    endpoint.port = port
+    endpoint.baudrate = 115200
+    endpoint.bytesize = 8
+    endpoint.parity = "N"
+    endpoint.stopbits = 1
+    endpoint.timeout = 0.02
+    endpoint.write_timeout = 1
+    endpoint.rtscts = False
+    endpoint.dsrdtr = False
+    endpoint.dtr = False
+    endpoint.rts = False
+    endpoint.open()
+    return endpoint
+
+
+def cmd_replay(args: argparse.Namespace) -> int:
+    receipt_path = Path(args.receipt) if args.receipt else None
+    try:
+        payload = _load_payload(Path(args.payload))
+    except (OSError, json.JSONDecodeError, UnicodeEncodeError, ValueError) as exc:
+        receipt = {
+            "schema": "prod2u-bmc-replay-session-v1",
+            "status": "blocked_invalid_payload",
+            "generated_at": utc_now(),
+            "error": str(exc),
+        }
+        if receipt_path is not None:
+            write_receipt_atomic(receipt_path, receipt)
+        if args.json:
+            print(json.dumps(receipt, indent=2))
+        else:
+            print(f"replay={receipt['status']} error={receipt['error']}")
+        return 1
+    if args.dry_run:
+        endpoint: ReplayEndpoint = FakeSerialEndpoint(initial_rx=POLL_COMMAND_TEXT.encode("ascii"))
+    else:
+        endpoint = _open_serial_endpoint(args.port)
+    try:
+        iterations = args.iterations if args.iterations > 0 else 1 if args.dry_run else 2**31 - 1
+        timeout_sec = args.timeout_sec if args.timeout_sec > 0 else 0.1 if args.dry_run else 86400.0
+        receipt = run_poll_response_session(
+            endpoint,
+            payload,
+            iterations=iterations,
+            timeout_sec=timeout_sec,
+            receipt_callback=(lambda value: write_receipt_atomic(receipt_path, value)) if receipt_path else None,
+        )
+    finally:
+        close = getattr(endpoint, "close", None)
+        if callable(close):
+            close()
+    if receipt_path is not None:
+        write_receipt_atomic(receipt_path, receipt)
+    if args.json:
+        print(json.dumps(receipt, indent=2))
+    else:
+        print(f"replay={receipt['status']} matched={receipt['matched_poll_count']} replies={receipt['reply_count']}")
+    return 0 if receipt["status"] == "pass" else 1
+
+
+def build_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(description=__doc__)
+    sub = parser.add_subparsers(dest="command", required=True)
+
+    normalize = sub.add_parser("normalize-capture")
+    normalize.add_argument("--input", required=True)
+    normalize.add_argument("--payload", required=True)
+    normalize.add_argument("--seq", type=int, default=1)
+    normalize.add_argument("--json", action="store_true")
+    normalize.set_defaults(func=cmd_normalize_capture)
+
+    selftest = sub.add_parser("selftest")
+    selftest.set_defaults(func=cmd_selftest)
+    replay = sub.add_parser("replay")
+    replay.add_argument("--port", required=True)
+    replay.add_argument("--payload", required=True)
+    replay.add_argument("--iterations", type=int, default=0)
+    replay.add_argument("--timeout-sec", type=float, default=0.0)
+    replay.add_argument("--dry-run", action="store_true")
+    replay.add_argument("--receipt")
+    replay.add_argument("--json", action="store_true")
+    replay.set_defaults(func=cmd_replay)
+    return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = build_parser().parse_args(argv)
+    return args.func(args)
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 277 - 0
tools/prod2u_build_identity.py

@@ -0,0 +1,277 @@
+#!/usr/bin/env python3
+"""Deterministic source manifest and 32-bit build identity helpers."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import re
+from pathlib import Path
+from typing import Any, Iterable, Mapping
+
+
+BUILD_ID_RE = re.compile(r"^[0-9A-F]{8}$")
+SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
+BUILD_ID_LITERAL_RE = re.compile(r"parameter \[31:0\] BUILD_ID = 32'h[0-9A-Fa-f]{8}")
+NORMALIZATION_BUILD_ID_ZERO = "prod2u_build_id_zero"
+NORMALIZATION_TD_STAGED_PATHS = "prod2u_td_staged_paths"
+KNOWN_NORMALIZATIONS = {NORMALIZATION_BUILD_ID_ZERO, NORMALIZATION_TD_STAGED_PATHS}
+
+
+def _sha256(path: Path) -> str:
+    digest = hashlib.sha256()
+    with path.open("rb") as handle:
+        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+            digest.update(chunk)
+    return digest.hexdigest()
+
+
+def _sha256_bytes(payload: bytes) -> str:
+    return hashlib.sha256(payload).hexdigest()
+
+
+def _normalize_bytes(payload: bytes, normalization: str | None, *, label: str) -> bytes:
+    if normalization is None:
+        return payload
+    if normalization == NORMALIZATION_TD_STAGED_PATHS:
+        return payload.replace(b"\r\n", b"\n").replace(b'Path="../', b'Path="')
+    if normalization != NORMALIZATION_BUILD_ID_ZERO:
+        raise ValueError(f"unknown source normalization for {label}: {normalization}")
+    try:
+        source = payload.decode("ascii")
+    except UnicodeDecodeError as exc:
+        raise ValueError(f"BUILD_ID normalization requires ASCII source: {label}") from exc
+    normalized, count = BUILD_ID_LITERAL_RE.subn(
+        "parameter [31:0] BUILD_ID = 32'h00000000",
+        source,
+        count=1,
+    )
+    if count != 1:
+        raise ValueError(f"BUILD_ID normalization marker missing or ambiguous: {label}")
+    return normalized.encode("ascii")
+
+
+def source_file_identity(path: Path, normalization: str | None = None) -> dict[str, Any]:
+    path = Path(path)
+    payload = path.read_bytes()
+    normalized = _normalize_bytes(payload, normalization, label=str(path))
+    return {
+        "size": len(payload),
+        "sha256": _sha256_bytes(payload),
+        "normalized_sha256": _sha256_bytes(normalized),
+    }
+
+
+def _canonical_payload(manifest: Mapping[str, Any]) -> dict[str, Any]:
+    return {
+        "schema": manifest.get("schema"),
+        "profile": manifest.get("profile"),
+        "td_version": manifest.get("td_version"),
+        "files": manifest.get("files"),
+    }
+
+
+def source_manifest_sha256(manifest: Mapping[str, Any]) -> str:
+    canonical = json.dumps(
+        _canonical_payload(manifest),
+        sort_keys=True,
+        separators=(",", ":"),
+        ensure_ascii=True,
+    ).encode("ascii")
+    return _sha256_bytes(canonical)
+
+
+def validate_source_manifest(manifest: Mapping[str, Any], *, root: Path | None = None) -> dict[str, Any]:
+    failures: list[str] = []
+    if manifest.get("schema") != "prod2u-source-manifest-v1":
+        failures.append("source_manifest_schema_mismatch")
+    if not isinstance(manifest.get("profile"), str) or not manifest.get("profile"):
+        failures.append("source_manifest_profile_invalid")
+    if not isinstance(manifest.get("td_version"), str) or not manifest.get("td_version"):
+        failures.append("source_manifest_td_version_invalid")
+
+    rows = manifest.get("files")
+    if not isinstance(rows, list) or not rows:
+        failures.append("source_manifest_files_invalid")
+        rows = []
+    observed_paths: list[str] = []
+    normalized_root = None if root is None else Path(root).resolve()
+    for index, value in enumerate(rows):
+        if not isinstance(value, Mapping):
+            failures.append(f"source_manifest_file_row_invalid:{index}")
+            continue
+        relative = value.get("path")
+        size = value.get("size")
+        digest = value.get("sha256")
+        normalization = value.get("normalization")
+        if not isinstance(relative, str) or not relative or Path(relative).is_absolute() or ".." in Path(relative).parts:
+            failures.append(f"source_manifest_path_invalid:{index}")
+            continue
+        observed_paths.append(relative)
+        if not isinstance(size, int) or size < 0:
+            failures.append(f"source_manifest_size_invalid:{relative}")
+        if not isinstance(digest, str) or not SHA256_RE.fullmatch(digest):
+            failures.append(f"source_manifest_file_sha256_invalid:{relative}")
+        if normalization is not None and normalization not in KNOWN_NORMALIZATIONS:
+            failures.append(f"source_manifest_normalization_invalid:{relative}")
+        if normalized_root is not None:
+            path = (normalized_root / relative).resolve()
+            try:
+                path.relative_to(normalized_root)
+            except ValueError:
+                failures.append(f"source_manifest_path_escaped_root:{relative}")
+                continue
+            if not path.is_file():
+                failures.append(f"source_manifest_file_missing:{relative}")
+                continue
+            payload = path.read_bytes()
+            if isinstance(size, int) and len(payload) != size:
+                failures.append(f"source_manifest_file_size_mismatch:{relative}")
+            try:
+                normalized = _normalize_bytes(payload, normalization if isinstance(normalization, str) else None, label=relative)
+            except ValueError:
+                failures.append(f"source_manifest_normalization_failed:{relative}")
+            else:
+                if isinstance(digest, str) and _sha256_bytes(normalized) != digest:
+                    failures.append(f"source_manifest_file_hash_mismatch:{relative}")
+
+    if observed_paths != sorted(observed_paths) or len(observed_paths) != len(set(observed_paths)):
+        failures.append("source_manifest_file_order_or_duplicate_invalid")
+    expected_hash = source_manifest_sha256(manifest)
+    actual_hash = manifest.get("source_manifest_sha256")
+    if not isinstance(actual_hash, str) or not SHA256_RE.fullmatch(actual_hash) or actual_hash != expected_hash:
+        failures.append("source_manifest_sha256_mismatch")
+    build_id = manifest.get("build_id")
+    if not isinstance(build_id, str) or not BUILD_ID_RE.fullmatch(build_id) or build_id != expected_hash[:8].upper():
+        failures.append("source_manifest_build_id_mismatch")
+    return {
+        "status": "pass" if not failures else "fail",
+        "failures": failures,
+        "source_manifest_sha256": expected_hash,
+        "build_id": expected_hash[:8].upper(),
+    }
+
+
+def build_source_manifest(
+    *,
+    root: Path,
+    inputs: Iterable[Path],
+    profile: str,
+    td_version: str,
+    normalizations: Mapping[str, str] | None = None,
+) -> dict[str, object]:
+    root = root.resolve()
+    normalizations = dict(normalizations or {})
+    rows: list[dict[str, object]] = []
+    seen: set[str] = set()
+    for candidate in inputs:
+        path = Path(candidate).resolve()
+        if not path.is_file():
+            raise FileNotFoundError(path)
+        try:
+            relative = path.relative_to(root).as_posix()
+        except ValueError as exc:
+            raise ValueError(f"source input is outside root: {path}") from exc
+        if relative in seen:
+            continue
+        seen.add(relative)
+        normalization = normalizations.get(relative)
+        payload = path.read_bytes()
+        normalized = _normalize_bytes(payload, normalization, label=relative)
+        row: dict[str, object] = {"path": relative, "size": len(payload), "sha256": _sha256_bytes(normalized)}
+        if normalization is not None:
+            row["normalization"] = normalization
+        rows.append(row)
+    rows.sort(key=lambda row: str(row["path"]))
+
+    canonical_payload: dict[str, object] = {
+        "schema": "prod2u-source-manifest-v1",
+        "profile": profile,
+        "td_version": td_version,
+        "files": rows,
+    }
+    source_hash = source_manifest_sha256(canonical_payload)
+    manifest = {
+        **canonical_payload,
+        "source_manifest_sha256": source_hash,
+        "build_id": source_hash[:8].upper(),
+    }
+    validation = validate_source_manifest(manifest, root=root)
+    if validation["status"] != "pass":
+        raise ValueError(f"generated source manifest failed validation: {validation['failures']}")
+    return manifest
+
+
+def write_verilog_header(manifest: dict[str, object], target: Path) -> None:
+    build_id = str(manifest.get("build_id", ""))
+    if not BUILD_ID_RE.fullmatch(build_id):
+        raise ValueError("build_id must be eight uppercase hexadecimal characters")
+    target = Path(target)
+    target.parent.mkdir(parents=True, exist_ok=True)
+    target.write_text(
+        "`ifndef PROD2U_BUILD_ID\n"
+        f"`define PROD2U_BUILD_ID 32'h{build_id}\n"
+        "`endif\n",
+        encoding="ascii",
+        newline="\n",
+    )
+
+
+def build_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("--validate-manifest", type=Path)
+    parser.add_argument("--root", type=Path)
+    parser.add_argument("--profile")
+    parser.add_argument("--td-version")
+    parser.add_argument("--input", action="append", type=Path, dest="inputs")
+    parser.add_argument("--output", type=Path)
+    parser.add_argument("--header", type=Path)
+    return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+    parser = build_parser()
+    args = parser.parse_args(argv)
+    if args.validate_manifest is not None:
+        try:
+            payload = json.loads(args.validate_manifest.read_text(encoding="utf-8-sig"))
+        except (OSError, json.JSONDecodeError) as exc:
+            result = {"status": "fail", "failures": [f"source_manifest_unreadable:{exc}"]}
+        else:
+            result = validate_source_manifest(payload if isinstance(payload, Mapping) else {})
+        print(json.dumps(result, indent=2))
+        return 0 if result["status"] == "pass" else 1
+    missing = [
+        name
+        for name in ("root", "profile", "td_version", "inputs", "output", "header")
+        if getattr(args, name) in (None, [])
+    ]
+    if missing:
+        parser.error("missing required build arguments: " + ", ".join(f"--{name.replace('_', '-')}" for name in missing))
+    manifest = build_source_manifest(
+        root=args.root,
+        inputs=args.inputs,
+        profile=args.profile,
+        td_version=args.td_version,
+    )
+    args.output.parent.mkdir(parents=True, exist_ok=True)
+    args.output.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8", newline="\n")
+    write_verilog_header(manifest, args.header)
+    print(
+        json.dumps(
+            {
+                "status": "pass",
+                "manifest": str(args.output.resolve()),
+                "header": str(args.header.resolve()),
+                "source_manifest_sha256": manifest["source_manifest_sha256"],
+                "build_id": manifest["build_id"],
+            },
+            indent=2,
+        )
+    )
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 745 - 0
tools/prod2u_cli.py

@@ -0,0 +1,745 @@
+#!/usr/bin/env python3
+"""Unified Prod2U SRAM-only programmer and evidence entrypoint."""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import re
+import sys
+import tempfile
+from datetime import datetime, timezone
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import jsonschema
+
+
+ROOT = Path(__file__).resolve().parents[1]
+REMOTE_DIR = ROOT / "tools" / "remote"
+for candidate in (ROOT / "tools", REMOTE_DIR):
+    if str(candidate) not in sys.path:
+        sys.path.insert(0, str(candidate))
+
+
+PROFILE = "prod2u-bmc-replay-binary921"
+PROFILE_ID = 3
+TOP_MODULE = "prod2u_bmc_replay_binary921_top"
+TD_RECEIPT_SCHEMA = "prod2u-td-build-receipt-v1"
+DEFAULT_STAGE_ROOT = Path("C:\\P2U")
+DEFAULT_TD_ROOT = Path(r"C:\Anlogic\TD_Release_2026.1_SP1.198.412")
+BUILD_ID_RE = re.compile(r"^[0-9A-F]{8}$")
+COM_RE = re.compile(r"^COM[1-9][0-9]*$", re.IGNORECASE)
+SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
+PACKAGE_ROOT = Path(__file__).resolve().parent
+
+
+def utc_now_compact() -> str:
+    return datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
+
+
+def sha256_file(path: Path) -> str:
+    digest = hashlib.sha256()
+    with path.open("rb") as stream:
+        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
+            digest.update(chunk)
+    return digest.hexdigest()
+
+
+def _validate_package_integrity(package_root: Path) -> list[str]:
+    manifest_path = package_root / "manifest.json"
+    inventory_path = package_root / "sha256-inventory.json"
+    manifest_exists = manifest_path.is_file()
+    inventory_exists = inventory_path.is_file()
+    if not manifest_exists and not inventory_exists:
+        return []
+
+    failures: list[str] = []
+    if not manifest_exists:
+        failures.append("package_manifest_missing")
+    if not inventory_exists:
+        failures.append("package_inventory_missing")
+        return failures
+
+    inventory_payload = _load_json(inventory_path, "package_inventory", failures)
+    if inventory_payload.get("schema") != "prod2u-package-sha256-inventory-v1":
+        failures.append("package_inventory_schema_mismatch")
+    rows = inventory_payload.get("inventory")
+    if not isinstance(rows, list):
+        failures.append("package_inventory_entries_invalid")
+        return list(dict.fromkeys(failures))
+    if not rows:
+        failures.append("package_inventory_empty")
+
+    resolved_root = package_root.resolve()
+    seen_paths: set[str] = set()
+    for index, row in enumerate(rows):
+        if not isinstance(row, dict):
+            failures.append(f"package_inventory_entry_invalid:{index}")
+            continue
+        relative = row.get("path")
+        size = row.get("size")
+        expected_sha256 = row.get("sha256")
+        if (
+            not isinstance(relative, str)
+            or not relative
+            or "\\" in relative
+            or Path(relative).is_absolute()
+            or any(part in ("", ".", "..") for part in relative.split("/"))
+        ):
+            failures.append(f"package_inventory_path_invalid:{index}")
+            continue
+        if relative in seen_paths:
+            failures.append(f"package_inventory_path_duplicate:{relative}")
+            continue
+        seen_paths.add(relative)
+        if not isinstance(size, int) or isinstance(size, bool) or size < 0:
+            failures.append(f"package_inventory_size_invalid:{relative}")
+            continue
+        if not isinstance(expected_sha256, str) or not SHA256_RE.fullmatch(expected_sha256):
+            failures.append(f"package_inventory_sha256_invalid:{relative}")
+            continue
+
+        artifact = package_root.joinpath(*relative.split("/"))
+        try:
+            artifact.resolve().relative_to(resolved_root)
+        except ValueError:
+            failures.append(f"package_inventory_path_invalid:{relative}")
+            continue
+        if not artifact.is_file():
+            failures.append(f"package_inventory_file_missing:{relative}")
+            continue
+        if artifact.stat().st_size != size:
+            failures.append(f"package_inventory_size_mismatch:{relative}")
+        if sha256_file(artifact) != expected_sha256:
+            failures.append(f"package_inventory_sha256_mismatch:{relative}")
+
+    actual_paths = {
+        path.relative_to(package_root).as_posix()
+        for path in package_root.rglob("*")
+        if path.is_file() and path != inventory_path
+    }
+    for relative in sorted(actual_paths - seen_paths):
+        failures.append(f"package_inventory_unlisted_file:{relative}")
+
+    return list(dict.fromkeys(failures))
+
+
+def _load_json(path: Path, label: str, failures: list[str]) -> dict[str, Any]:
+    if not path.is_file():
+        failures.append(f"missing_{label}")
+        return {}
+    try:
+        value = json.loads(path.read_text(encoding="utf-8-sig"))
+    except (OSError, json.JSONDecodeError):
+        failures.append(f"invalid_{label}")
+        return {}
+    if not isinstance(value, dict):
+        failures.append(f"invalid_{label}")
+        return {}
+    return value
+
+
+def _td_receipt_schema_path() -> Path:
+    candidates = (
+        PACKAGE_ROOT / "schemas" / "prod2u_td_build_receipt.schema.json",
+        ROOT / "schemas" / "prod2u_td_build_receipt.schema.json",
+    )
+    for candidate in candidates:
+        if candidate.is_file():
+            return candidate
+    return candidates[0]
+
+
+def validate_td_receipt_schema_document(receipt: dict[str, Any]) -> list[str]:
+    schema_path = _td_receipt_schema_path()
+    if not schema_path.is_file():
+        return ["td_receipt_schema_file_missing"]
+    try:
+        schema = json.loads(schema_path.read_text(encoding="utf-8-sig"))
+        jsonschema.validate(receipt, schema)
+    except (OSError, json.JSONDecodeError, jsonschema.SchemaError):
+        return ["td_receipt_schema_file_invalid"]
+    except jsonschema.ValidationError:
+        return ["td_receipt_schema_invalid"]
+    return []
+
+
+_PACKAGE_STARTUP_FAILURES = _validate_package_integrity(PACKAGE_ROOT)
+if not _PACKAGE_STARTUP_FAILURES:
+    from binary921 import FrameType, decode_frame, encode_frame  # noqa: E402
+    from prod2u_collector import collect_live  # noqa: E402
+    from prod2u_build_identity import build_source_manifest, validate_source_manifest, write_verilog_header  # noqa: E402
+    from prod2u_programmer import execute_program_sram  # noqa: E402
+    from prod2u_receipts import EXPECTED_PROGRAM_MARKERS, build_final_gate, validate_evidence_manifest  # noqa: E402
+    from prod2u_validate import validate_evidence_directory  # noqa: E402
+else:
+    def _blocked_package_dependency(*_args: Any, **_kwargs: Any) -> Any:
+        raise RuntimeError("Prod2U package integrity validation failed")
+
+    FrameType = SimpleNamespace(COMMAND=2, ACK=3)
+    decode_frame = _blocked_package_dependency
+    encode_frame = _blocked_package_dependency
+    collect_live = _blocked_package_dependency
+    build_source_manifest = _blocked_package_dependency
+    validate_source_manifest = _blocked_package_dependency
+    write_verilog_header = _blocked_package_dependency
+    execute_program_sram = _blocked_package_dependency
+    EXPECTED_PROGRAM_MARKERS = ()
+    build_final_gate = _blocked_package_dependency
+    validate_evidence_manifest = _blocked_package_dependency
+    validate_evidence_directory = _blocked_package_dependency
+
+
+def _json_values_match_exactly(left: dict[str, Any], right: dict[str, Any]) -> bool:
+    return json.dumps(left, sort_keys=True, separators=(",", ":")) == json.dumps(
+        right,
+        sort_keys=True,
+        separators=(",", ":"),
+    )
+
+
+def _resolve_td_root(args: argparse.Namespace, td_receipt: dict[str, Any]) -> Path:
+    explicit = str(getattr(args, "td_root", "") or "").strip()
+    if explicit:
+        return Path(explicit)
+    receipt_root = str(td_receipt.get("td_root", "") or "").strip()
+    if receipt_root:
+        return Path(receipt_root)
+    td_executable = str(td_receipt.get("td_executable", "") or "").strip()
+    if td_executable:
+        return Path(td_executable).parent.parent
+    return DEFAULT_TD_ROOT
+
+
+def _validate_inputs(args: argparse.Namespace) -> dict[str, Any]:
+    failures = _validate_package_integrity(PACKAGE_ROOT)
+    if failures:
+        combined_port = str(getattr(args, "combined_port", "") or "")
+        td_root = Path(str(getattr(args, "td_root", "") or DEFAULT_TD_ROOT))
+        return {
+            "failures": failures,
+            "combined_port": combined_port.upper(),
+            "bitstream_path": Path(args.bitstream),
+            "bitstream_sha256": "",
+            "source_manifest_path": Path(args.source_manifest),
+            "source_manifest": {},
+            "source_manifest_sha256": "",
+            "build_id": "",
+            "td_receipt_path": Path(args.td_receipt),
+            "td_receipt": {},
+            "td_root": td_root,
+            "bw_executable": td_root / "bin" / "bw_commands_prompt.exe",
+            "bmc_replay_receipt": Path(args.bmc_replay_receipt),
+            "output_dir": Path(args.output_dir),
+        }
+    combined_port = str(getattr(args, "combined_port", "") or "")
+    if not COM_RE.fullmatch(combined_port):
+        failures.append("combined_port_not_explicit_com")
+
+    bitstream_path = Path(args.bitstream)
+    if not bitstream_path.is_file():
+        failures.append("missing_bitstream")
+        bitstream_sha256 = ""
+    else:
+        bitstream_sha256 = sha256_file(bitstream_path)
+
+    source_manifest_path = Path(args.source_manifest)
+    source_manifest = _load_json(source_manifest_path, "source_manifest", failures)
+    source_validation = validate_source_manifest(source_manifest)
+    failures.extend(source_validation["failures"])
+    source_hash = str(source_manifest.get("source_manifest_sha256", ""))
+    build_id = str(source_manifest.get("build_id", ""))
+    if source_manifest.get("schema") != "prod2u-source-manifest-v1":
+        failures.append("source_manifest_schema_mismatch")
+    if source_manifest.get("profile") != PROFILE:
+        failures.append("source_manifest_profile_mismatch")
+    if not re.fullmatch(r"[0-9a-f]{64}", source_hash):
+        failures.append("source_manifest_sha256_invalid")
+    if not BUILD_ID_RE.fullmatch(build_id):
+        failures.append("source_manifest_build_id_invalid")
+    elif source_hash and source_hash[:8].upper() != build_id:
+        failures.append("source_manifest_build_id_mismatch")
+
+    td_receipt_path = Path(args.td_receipt)
+    td_receipt = _load_json(td_receipt_path, "td_receipt", failures)
+    failures.extend(validate_td_receipt_schema_document(td_receipt))
+    if td_receipt.get("schema") != TD_RECEIPT_SCHEMA:
+        failures.append("td_receipt_schema_mismatch")
+    if td_receipt.get("top_module") != TOP_MODULE:
+        failures.append("td_top_module_mismatch")
+    if td_receipt.get("pin_profile") != PROFILE:
+        failures.append("td_pin_profile_mismatch")
+    if td_receipt.get("status") != "pass":
+        failures.append("td_receipt_not_pass")
+    por_initialization = (
+        td_receipt.get("por_initialization")
+        if isinstance(td_receipt.get("por_initialization"), dict)
+        else {}
+    )
+    if por_initialization.get("status") != "pass":
+        failures.append("td_por_initialization_not_pass")
+    if (
+        por_initialization.get("por_cycles") != 1024
+        or por_initialization.get("counter_width") != 10
+        or por_initialization.get("expected_init") != "0"
+        or por_initialization.get("register_count") != 11
+        or por_initialization.get("failures") != []
+    ):
+        failures.append("td_por_initialization_contract_mismatch")
+    td_bitstream = td_receipt.get("bitstream") if isinstance(td_receipt.get("bitstream"), dict) else {}
+    if bitstream_sha256 and str(td_bitstream.get("sha256", "")).casefold() != bitstream_sha256.casefold():
+        failures.append("td_bitstream_sha256_mismatch")
+    td_source_hash = td_receipt.get("source_manifest_sha256")
+    if not isinstance(td_source_hash, str) or not td_source_hash:
+        failures.append("td_source_manifest_sha256_missing")
+    elif td_source_hash != source_hash:
+        failures.append("td_source_manifest_sha256_mismatch")
+    td_build_id = td_receipt.get("build_id")
+    if not isinstance(td_build_id, str) or not td_build_id:
+        failures.append("td_build_id_missing")
+    elif td_build_id != build_id:
+        failures.append("td_build_id_mismatch")
+
+    td_root = _resolve_td_root(args, td_receipt)
+    bw_executable = td_root / "bin" / "bw_commands_prompt.exe"
+    if not bw_executable.is_file():
+        failures.append("missing_bw_commands_prompt")
+
+    return {
+        "failures": list(dict.fromkeys(failures)),
+        "combined_port": combined_port.upper(),
+        "bitstream_path": bitstream_path,
+        "bitstream_sha256": bitstream_sha256,
+        "source_manifest_path": source_manifest_path,
+        "source_manifest": source_manifest,
+        "source_manifest_sha256": source_hash,
+        "build_id": build_id,
+        "td_receipt_path": td_receipt_path,
+        "td_receipt": td_receipt,
+        "td_root": td_root,
+        "bw_executable": bw_executable,
+        "bmc_replay_receipt": Path(args.bmc_replay_receipt),
+        "output_dir": Path(args.output_dir),
+    }
+
+
+def run_preflight(args: argparse.Namespace) -> dict[str, Any]:
+    context = _validate_inputs(args)
+    return {
+        "schema": "prod2u-preflight-v1",
+        "status": "pass" if not context["failures"] else "fail_preflight",
+        "profile": PROFILE,
+        "profile_id": PROFILE_ID,
+        "combined_port": context["combined_port"],
+        "build_id": context["build_id"],
+        "bitstream_sha256": context["bitstream_sha256"],
+        "source_manifest_sha256": context["source_manifest_sha256"],
+        "td_root": str(context["td_root"]),
+        "hardware_opened": False,
+        "program_sram_attempted": False,
+        "enumerates_com_ports": False,
+        "failures": context["failures"],
+    }
+
+
+def _collector_args(args: argparse.Namespace, context: dict[str, Any], output_dir: Path) -> SimpleNamespace:
+    return SimpleNamespace(
+        profile=PROFILE,
+        transport="combined-single-com",
+        combined_port=context["combined_port"],
+        host_port="",
+        debug_port="",
+        output_dir=str(output_dir),
+        duration_sec=float(getattr(args, "duration_sec", 5.0)),
+        ready_timeout_sec=float(getattr(args, "ready_timeout_sec", 30.0)),
+        pre_program_observe_sec=float(getattr(args, "pre_program_observe_sec", 0.1)),
+        ack_window_sec=0.25,
+        bitstream=str(context["bitstream_path"]),
+        td_receipt=str(context["td_receipt_path"]),
+        bmc_replay_receipt=str(context["bmc_replay_receipt"]),
+        expected_build_id=context["build_id"],
+        expected_epoch=1,
+    )
+
+
+def _programmer_exception_result(exc: Exception) -> dict[str, Any]:
+    return {
+        "schema": "prod2u-programmer-error-v1",
+        "status": "fail_programmer_exception",
+        "error_type": type(exc).__name__,
+        "error": str(exc),
+        "attempt_count": 0,
+        "retry_count": 0,
+        "power_cycle_count": 0,
+        "safety": {
+            "flash_attempted": False,
+            "programs_nonvolatile": False,
+            "power_cycle_attempted": False,
+            "driver_install_attempted": False,
+            "toggles_dtr_rts": False,
+        },
+    }
+
+
+def run_program_only(
+    args: argparse.Namespace,
+    *,
+    program_executor=execute_program_sram,
+) -> dict[str, Any]:
+    context = _validate_inputs(args)
+    if context["failures"]:
+        return run_preflight(args)
+    program_dir = context["output_dir"] / "programmer"
+    try:
+        return program_executor(
+            source_bitstream=context["bitstream_path"],
+            expected_bitstream_sha256=context["bitstream_sha256"],
+            build_id=context["build_id"],
+            output_dir=program_dir,
+            td_root=context["td_root"],
+            run_id=f"prod2u-program-{utc_now_compact()}",
+        )
+    except Exception as exc:
+        payload = _programmer_exception_result(exc)
+        program_dir.mkdir(parents=True, exist_ok=True)
+        (program_dir / "programmer-error.json").write_text(
+            json.dumps(payload, indent=2) + "\n",
+            encoding="utf-8",
+        )
+        return payload
+
+
+def run_collect_only(
+    args: argparse.Namespace,
+    *,
+    collector_runner=collect_live,
+) -> dict[str, Any]:
+    context = _validate_inputs(args)
+    if context["failures"]:
+        return run_preflight(args)
+    collector_dir = context["output_dir"] / "collector-diagnostic"
+    collector = collector_runner(_collector_args(args, context, collector_dir))
+    payload = {
+        "schema": "prod2u-collect-only-result-v1",
+        "status": "diagnostic_complete" if collector.get("status") == "pass" else collector.get("status", "fail"),
+        "strict_pass_eligible": False,
+        "fresh_program_epoch_proven": False,
+        "collector": collector,
+    }
+    context["output_dir"].mkdir(parents=True, exist_ok=True)
+    (context["output_dir"] / "collect-only-result.json").write_text(
+        json.dumps(payload, indent=2) + "\n",
+        encoding="utf-8",
+    )
+    return payload
+
+
+def run_all(
+    args: argparse.Namespace,
+    *,
+    program_executor=execute_program_sram,
+    collector_runner=collect_live,
+    evidence_validator=validate_evidence_directory,
+) -> dict[str, Any]:
+    context = _validate_inputs(args)
+    if context["failures"]:
+        return run_preflight(args)
+    output_dir = context["output_dir"]
+    program_dir = output_dir / "programmer"
+    collector_dir = output_dir / "collector"
+    program_receipt: dict[str, Any] | None = None
+    program_callback_invoked = False
+    program_callback_reused = False
+
+    def before_ready() -> dict[str, Any]:
+        nonlocal program_callback_invoked, program_callback_reused, program_receipt
+        if program_callback_invoked:
+            program_callback_reused = True
+            return {
+                "schema": "prod2u-command-result-v1",
+                "status": "fail_programmer_callback_reused",
+            }
+        program_callback_invoked = True
+        try:
+            program_receipt = program_executor(
+                source_bitstream=context["bitstream_path"],
+                expected_bitstream_sha256=context["bitstream_sha256"],
+                build_id=context["build_id"],
+                output_dir=program_dir,
+                td_root=context["td_root"],
+                run_id=f"prod2u-all-{utc_now_compact()}",
+            )
+        except Exception as exc:
+            program_receipt = _programmer_exception_result(exc)
+        return program_receipt
+
+    collector = collector_runner(
+        _collector_args(args, context, collector_dir),
+        before_ready=before_ready,
+    )
+    if program_callback_reused:
+        return {
+            "schema": "prod2u-command-result-v1",
+            "status": "fail_programmer_callback_reused",
+            "collector": collector,
+            "program": program_receipt,
+        }
+    if program_receipt is None:
+        return {
+            "schema": "prod2u-command-result-v1",
+            "status": "fail_programmer_not_invoked",
+            "collector": collector,
+        }
+    receipt_path = program_dir / "program-sram-receipt.json"
+    receipt_failures: list[str] = []
+    persisted_program_receipt = _load_json(receipt_path, "programmer_receipt", receipt_failures)
+    if receipt_failures:
+        return {
+            "schema": "prod2u-command-result-v1",
+            "status": "fail_programmer_receipt_missing" if "missing_programmer_receipt" in receipt_failures else "fail_programmer_receipt_invalid",
+            "collector": collector,
+            "program": program_receipt,
+            "failures": receipt_failures,
+        }
+    if not _json_values_match_exactly(persisted_program_receipt, program_receipt):
+        return {
+            "schema": "prod2u-command-result-v1",
+            "status": "fail_programmer_receipt_mismatch",
+            "collector": collector,
+            "program": program_receipt,
+        }
+    evidence = evidence_validator(
+        collector_dir=collector_dir,
+        collector=collector,
+        program=persisted_program_receipt,
+        source_manifest=context["source_manifest"],
+        programmer_receipt_path=str(receipt_path.relative_to(output_dir)),
+        programmer_receipt_sha256=sha256_file(receipt_path),
+        bmc_replay_receipt_path=context["bmc_replay_receipt"],
+    )
+    output_dir.mkdir(parents=True, exist_ok=True)
+    (output_dir / "prod2u-evidence-manifest.json").write_text(
+        json.dumps(evidence, indent=2) + "\n",
+        encoding="utf-8",
+    )
+    return evidence
+
+
+def _selftest_program_receipt() -> dict[str, Any]:
+    return {
+        "schema": "prod2u-program-sram-receipt-v1",
+        "status": "pass",
+        "run_id": "selftest",
+        "request": {
+            "operation": "PROGRAM_SRAM",
+            "target_chip": "EF2L45",
+            "cable_index": 0,
+            "speed_code": 2,
+            "speed_hz": 200000,
+            "attempt_limit": 1,
+            "power_cycle_allowed": False,
+        },
+        "bitstream": {"path": "C:/P2U/1234ABCD/fw.bit", "sha256": "a" * 64, "build_id": "1234ABCD"},
+        "staging": {
+            "expected_path": "C:/P2U/1234ABCD/fw.bit",
+            "observed_path": "C:/P2U/1234ABCD/fw.bit",
+            "matches_expected_path": True,
+        },
+        "execution": {
+            "exit_code": 0,
+            "timed_out": False,
+            "attempt_count": 1,
+            "retry_count": 0,
+            "power_cycle_count": 0,
+            "command_execution_attempted": True,
+            "timeout_seconds": 60,
+        },
+        "parser": {
+            "status": "pass",
+            "exit_code_trusted": False,
+            "ordered_markers": list(EXPECTED_PROGRAM_MARKERS),
+            "ordered_markers_complete": True,
+            "observed_markers": list(EXPECTED_PROGRAM_MARKERS),
+            "observed_marker_lines": list(range(1, len(EXPECTED_PROGRAM_MARKERS) + 1)),
+            "error_markers": [],
+            "failures": [],
+            "transcript_sha256": "9" * 64,
+        },
+        "tool": {
+            "path": "C:/Anlogic/TD/bin/bw_commands_prompt.exe",
+            "td_root": "C:/Anlogic/TD",
+            "td_bin": "C:/Anlogic/TD/bin",
+        },
+        "mutex": {"name": "Global\\Prod2UProgramSram", "acquired": True},
+        "process_cleanup": {
+            "status": "pass",
+            "td_root": "C:/Anlogic/TD",
+            "graceful_close_requested": [],
+            "forced_terminated": [],
+            "wait_seconds": 5.0,
+            "remaining": [],
+        },
+        "artifacts": {
+            "tcl": {"path": "program-sram.tcl", "size": 1, "sha256": "1" * 64},
+            "stdout": {"path": "bitwriter-stdout.log", "size": 1, "sha256": "2" * 64},
+            "stderr": {"path": "bitwriter-stderr.log", "size": 1, "sha256": "3" * 64},
+            "log_delta": {"path": "bitwriter-log-delta.log", "size": 1, "sha256": "4" * 64},
+            "log_delta_sources": [
+                {
+                    "path": "C:/Anlogic/TD/log/bw_selftest.log",
+                    "start_offset": 0,
+                    "byte_count": 1,
+                    "sha256": "8" * 64,
+                }
+            ],
+        },
+        "safety": {
+            "flash_attempted": False,
+            "programs_nonvolatile": False,
+            "power_cycle_attempted": False,
+            "driver_install_attempted": False,
+            "toggles_dtr_rts": False,
+            "real_ptc_fan_action_attempted": False,
+            "external_programming_command_executed": True,
+        },
+    }
+
+
+def _selftest_evidence() -> dict[str, Any]:
+    return {
+        "schema": "prod2u-evidence-manifest-v1",
+        "status": "pass",
+        "protocol": "binary921",
+        "profile": PROFILE,
+        "profile_id": PROFILE_ID,
+        "build_identity": {"build_id": "1234ABCD", "source_manifest_sha256": "1234abcd" + "b" * 56},
+        "programmer_receipt": {"path": "program-sram-receipt.json", "sha256": "c" * 64, "status": "pass"},
+        "startup_ready": {
+            "frame_type": 1,
+            "seq": 1,
+            "profile_id": PROFILE_ID,
+            "build_id": "1234ABCD",
+            "post_program_epoch": True,
+            "por_reason": 1,
+            "announcement_seq": 0,
+            "matching_ready_count": 1,
+            "selection_policy": "last_matching_ready",
+        },
+        "host_command_count": 12,
+        "host_ack_count": 12,
+        "host_ack_matched_count": 12,
+        "bmc_replay": {"status": "pass", "bmc_source": "pc_replay_from_real_bmc_capture", "payload_sha256": "d" * 64},
+        "artifact_hashes": {"combined-rx.raw": "e" * 64, "host-command-wire.bin": "f" * 64},
+        "real_fan_ptc_hardware_status": "not_run",
+        "safety": {
+            "flash_attempted": False,
+            "programs_nonvolatile": False,
+            "driver_install_attempted": False,
+            "power_cycle_attempted": False,
+            "toggles_dtr_rts": False,
+        },
+    }
+
+
+def run_selftest() -> dict[str, Any]:
+    with tempfile.TemporaryDirectory() as tmp:
+        temp = Path(tmp)
+        source = temp / "source.v"
+        source.write_text("module source; endmodule\n", encoding="ascii")
+        identity = build_source_manifest(
+            root=temp,
+            inputs=[source],
+            profile=PROFILE,
+            td_version="6.2.2.198412",
+        )
+        header = temp / "prod2u_build_id.vh"
+        write_verilog_header(identity, header)
+
+    ready_wire = encode_frame(
+        profile_id=PROFILE_ID,
+        frame_type=FrameType.READY,
+        seq=1,
+        timestamp_tick=250000,
+        payload=bytes([PROFILE_ID, 0xCD, 0xAB, 0x34, 0x12, 1, 0]),
+    )
+    ready = decode_frame(ready_wire)
+    program = _selftest_program_receipt()
+    evidence = _selftest_evidence()
+    evidence_result = validate_evidence_manifest(evidence, program)
+    layers = {name: "pass" for name in ("static", "rtl_sim", "formal", "td_build", "program_sram", "fresh_epoch", "host_uart", "bmc_replay")}
+    final = build_final_gate(program, evidence, layers)
+    passed = (
+        identity["build_id"] == str(identity["source_manifest_sha256"])[:8].upper()
+        and ready.profile_id == PROFILE_ID
+        and evidence_result["status"] == "pass"
+        and final["status"] == "pass"
+    )
+    return {
+        "schema": "prod2u-selftest-v1",
+        "status": "pass" if passed else "fail",
+        "profile": PROFILE,
+        "profile_id": PROFILE_ID,
+        "hardware_opened": False,
+        "program_sram_attempted": False,
+        "checks": {
+            "build_identity": identity["build_id"],
+            "binary921_ready_roundtrip": ready.profile_id == PROFILE_ID,
+            "evidence_validation": evidence_result["status"],
+            "final_gate": final["status"],
+        },
+    }
+
+
+def build_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(description=__doc__)
+    sub = parser.add_subparsers(dest="command", required=True)
+    sub.add_parser("selftest")
+    schema_check = sub.add_parser("validate-td-receipt")
+    schema_check.add_argument("--td-receipt", required=True)
+    for name in ("preflight", "program-only", "collect-only", "all"):
+        command = sub.add_parser(name)
+        command.add_argument("--combined-port", default="COM5")
+        command.add_argument("--bitstream", default="fw.bit")
+        command.add_argument("--td-receipt", default="td.json")
+        command.add_argument("--source-manifest", default="source-manifest.json")
+        command.add_argument("--bmc-replay-receipt", default="bmc-replay-session.json")
+        command.add_argument("--output-dir", default="evidence-prod2u")
+        command.add_argument("--td-root", default="")
+        command.add_argument("--duration-sec", type=float, default=5.0)
+        command.add_argument("--ready-timeout-sec", type=float, default=30.0)
+        command.add_argument("--pre-program-observe-sec", type=float, default=0.1)
+    return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = build_parser().parse_args(argv)
+    if args.command == "selftest":
+        payload = run_selftest()
+    elif args.command == "validate-td-receipt":
+        failures: list[str] = []
+        receipt = _load_json(Path(args.td_receipt), "td_receipt", failures)
+        failures.extend(validate_td_receipt_schema_document(receipt))
+        payload = {
+            "schema": "prod2u-td-receipt-schema-validation-v1",
+            "status": "pass" if not failures else "fail",
+            "failures": list(dict.fromkeys(failures)),
+        }
+    elif args.command == "preflight":
+        payload = run_preflight(args)
+    elif args.command == "program-only":
+        payload = run_program_only(args)
+    elif args.command == "collect-only":
+        payload = run_collect_only(args)
+    elif args.command == "all":
+        payload = run_all(args)
+    else:
+        raise AssertionError(f"unhandled command: {args.command}")
+    print(json.dumps(payload, indent=2))
+    return 0 if payload["status"] in {"pass", "diagnostic_complete"} else 1
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 1172 - 0
tools/prod2u_collector.py


+ 948 - 0
tools/prod2u_programmer.py

@@ -0,0 +1,948 @@
+#!/usr/bin/env python3
+"""Strict Prod2U PROGRAM_SRAM transaction parser and Tcl generator."""
+
+from __future__ import annotations
+
+import argparse
+import ctypes
+import hashlib
+import json
+import ntpath
+import os
+import re
+import shutil
+import subprocess
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Callable
+
+
+SCHEMA_NAME = "prod2u-program-sram-receipt-v1"
+TARGET_CHIP = "EF2L45"
+JTAG_SPEED_CODE = 2
+JTAG_SPEED_HZ = 200000
+BIT_TO_VEC_FREQUENCY = "0.200000"
+EXPECTED_MARKERS = (
+    "download_start",
+    "chip_validation",
+    "bit_to_vec_start",
+    "bit_to_vec_finish",
+    "program_start",
+    "program_finish",
+    "download_finish",
+)
+SETUP_MARKERS = ("connect_cable_start", "connect_cable_finish")
+BUILD_ID_RE = re.compile(r"^[0-9A-F]{8}$")
+SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
+ERROR_RE = re.compile(
+    r"\b(?:PRG-8\d{3}|ERROR|FATAL|failed|couldn't read file|invalid command name)\b",
+    re.IGNORECASE,
+)
+FORBIDDEN_RE = re.compile(
+    r"(?<![A-Za-z0-9])(?:flash|erase|spi(?:bin)?|nonvolatile)(?![A-Za-z0-9])",
+    re.IGNORECASE,
+)
+START_COMMAND_RE = re.compile(r'^RUN-1002\s*:\s*start command "(?P<command>.+)"\s*$')
+FINISH_COMMAND_RE = re.compile(r'^RUN-1003\s*:\s*finish command "(?P<command>.+)"(?:\s+in\s+.+)?$')
+CHIP_RE = re.compile(r"^PRG-2014\s*:\s*Chip validation success:\s*(?P<chip>\S+)\s*$")
+DOWNLOAD_RE = re.compile(
+    r"^download\s+-bit\s+(?P<path>\{[^}]+\}|\"[^\"]+\"|\S+)\s+"
+    r"-mode\s+(?P<mode>\S+)\s+-spd\s+(?P<speed>\d+)\s+-cable\s+(?P<cable>\d+)\s*$"
+)
+BIT_TO_VEC_RE = re.compile(
+    r"^bit_to_vec\s+-chip\s+(?P<chip>\S+)\s+-m\s+(?P<mode>\S+)\s+"
+    r"-freq\s+(?P<freq>\S+)\s+-bit\s+(?P<path>\{[^}]+\}|\"[^\"]+\"|\S+)\s*$"
+)
+PROGRAM_RE = re.compile(
+    r"^program\s+-cable\s+(?P<cable>\d+)\s+-mode\s+(?P<mode>\S+)\s+"
+    r"-spd\s+(?P<speed>\d+)\s+-p\s*$"
+)
+PROGRAM_TIMEOUT_SECONDS = 60
+PROCESS_CLEANUP_WAIT_SECONDS = 5.0
+MUTEX_NAME = r"Global\Prod2UProgramSram"
+
+
+def utc_now() -> str:
+    return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
+
+
+def sha256_bytes(data: bytes) -> str:
+    return hashlib.sha256(data).hexdigest()
+
+
+def sha256_file(path: Path) -> str:
+    digest = hashlib.sha256()
+    with path.open("rb") as stream:
+        for chunk in iter(lambda: stream.read(1024 * 1024), b""):
+            digest.update(chunk)
+    return digest.hexdigest()
+
+
+def staged_bitstream_path(build_id: str) -> str:
+    """Return the only accepted Windows staging path for a build identity."""
+    if not BUILD_ID_RE.fullmatch(build_id):
+        raise ValueError("build_id must be eight uppercase hexadecimal characters")
+    return f"C:\\P2U\\{build_id}\\fw.bit"
+
+
+def _strip_path_token(value: str) -> str:
+    if value.startswith("{") and value.endswith("}"):
+        return value[1:-1]
+    if value.startswith('"') and value.endswith('"'):
+        return value[1:-1]
+    return value
+
+
+def _canonical_windows_path(value: str, *, td_bin: str) -> str:
+    normalized = _strip_path_token(value).replace("/", "\\")
+    if not ntpath.isabs(normalized):
+        normalized = ntpath.join(td_bin, normalized)
+    return ntpath.normcase(ntpath.normpath(normalized))
+
+
+def build_program_tcl(bitstream_path: str) -> str:
+    """Generate the fixed one-attempt SRAM-only BitWriter Tcl program."""
+    canonical = ntpath.normpath(bitstream_path)
+    match = re.fullmatch(r"C:\\P2U\\([0-9A-F]{8})\\fw\.bit", canonical, re.IGNORECASE)
+    if match is None:
+        raise ValueError("bitstream_path must be C:\\P2U\\<BUILD_ID>\\fw.bit")
+    build_id = match.group(1).upper()
+    expected = staged_bitstream_path(build_id).replace("\\", "/")
+    return (
+        "connect_cable -allink\n"
+        f"download -bit {{{expected}}} -mode jtag -spd 2 -cable 0\n"
+        "exit\n"
+    )
+
+
+class WindowsNamedMutex:
+    """Non-waiting process-wide PROGRAM_SRAM lock backed by a Windows mutex."""
+
+    def __init__(self, name: str = MUTEX_NAME) -> None:
+        self.name = name
+        self.handle: int | None = None
+
+    def __enter__(self) -> "WindowsNamedMutex":
+        if os.name != "nt":
+            raise RuntimeError("Prod2U PROGRAM_SRAM is supported only on Windows")
+        kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+        kernel32.CreateMutexW.argtypes = [ctypes.c_void_p, ctypes.c_bool, ctypes.c_wchar_p]
+        kernel32.CreateMutexW.restype = ctypes.c_void_p
+        kernel32.WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
+        kernel32.WaitForSingleObject.restype = ctypes.c_uint32
+        kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
+        kernel32.CloseHandle.restype = ctypes.c_bool
+        handle = kernel32.CreateMutexW(None, False, self.name)
+        if not handle:
+            raise OSError(ctypes.get_last_error(), "CreateMutexW failed")
+        result = kernel32.WaitForSingleObject(handle, 0)
+        if result not in (0x00000000, 0x00000080):
+            kernel32.CloseHandle(handle)
+            raise TimeoutError("Prod2U PROGRAM_SRAM mutex busy")
+        self.handle = int(handle)
+        return self
+
+    def __exit__(self, exc_type, exc, tb) -> bool:
+        if self.handle is not None:
+            kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+            kernel32.ReleaseMutex.argtypes = [ctypes.c_void_p]
+            kernel32.ReleaseMutex.restype = ctypes.c_bool
+            kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
+            kernel32.CloseHandle.restype = ctypes.c_bool
+            kernel32.ReleaseMutex(ctypes.c_void_p(self.handle))
+            kernel32.CloseHandle(ctypes.c_void_p(self.handle))
+            self.handle = None
+        return False
+
+
+def close_td_processes(td_root: Path) -> dict[str, Any]:
+    """Gracefully close, then bound-force-close, TD processes from one install root."""
+    root = str(td_root.resolve())
+    script = r'''
+$ErrorActionPreference = 'Stop'
+if ([string]::IsNullOrWhiteSpace($env:PROD2U_TD_ROOT)) { throw 'PROD2U_TD_ROOT is required' }
+$root = [System.IO.Path]::GetFullPath($env:PROD2U_TD_ROOT).TrimEnd('\')
+$rootWithSeparator = $root + [System.IO.Path]::DirectorySeparatorChar
+$allowed = @('td','bw','bitwriter','chipwatcher','bw_commands_prompt')
+function Find-TdProcesses {
+    @(Get-Process -ErrorAction SilentlyContinue | Where-Object {
+        try {
+            $path = $_.Path
+            $fullPath = [System.IO.Path]::GetFullPath($path)
+            $path -and
+                ($fullPath.Equals($root, [System.StringComparison]::OrdinalIgnoreCase) -or
+                    $fullPath.StartsWith($rootWithSeparator, [System.StringComparison]::OrdinalIgnoreCase)) -and
+                ($allowed -contains $_.ProcessName.ToLowerInvariant())
+        } catch { $false }
+    })
+}
+$initial = Find-TdProcesses
+$graceful = @()
+foreach ($process in $initial) {
+    $null = $process.CloseMainWindow()
+    $graceful += ('{0}:{1}' -f $process.ProcessName, $process.Id)
+}
+Start-Sleep -Seconds 5
+$survivors = Find-TdProcesses
+$forced = @()
+foreach ($process in $survivors) {
+    Stop-Process -Id $process.Id -Force -ErrorAction Stop
+    $forced += ('{0}:{1}' -f $process.ProcessName, $process.Id)
+}
+Start-Sleep -Milliseconds 250
+$remaining = @(Find-TdProcesses | ForEach-Object { '{0}:{1}' -f $_.ProcessName, $_.Id })
+[ordered]@{
+    status = $(if ($remaining.Count -eq 0) { 'pass' } else { 'fail' })
+    td_root = $root
+    graceful_close_requested = $graceful
+    forced_terminated = $forced
+    wait_seconds = 5.0
+    remaining = $remaining
+} | ConvertTo-Json -Compress
+'''
+    env = os.environ.copy()
+    env["PROD2U_TD_ROOT"] = root
+    result = subprocess.run(
+        ["powershell.exe", "-NoProfile", "-Command", script],
+        capture_output=True,
+        text=True,
+        check=False,
+        timeout=15,
+        env=env,
+    )
+    if result.returncode != 0:
+        return {
+            "status": "fail",
+            "td_root": root,
+            "graceful_close_requested": [],
+            "forced_terminated": [],
+            "wait_seconds": PROCESS_CLEANUP_WAIT_SECONDS,
+            "remaining": [],
+            "error": result.stderr.strip() or result.stdout.strip() or f"exit={result.returncode}",
+        }
+    try:
+        payload = json.loads(result.stdout)
+    except json.JSONDecodeError as exc:
+        return {
+            "status": "fail",
+            "td_root": root,
+            "graceful_close_requested": [],
+            "forced_terminated": [],
+            "wait_seconds": PROCESS_CLEANUP_WAIT_SECONDS,
+            "remaining": [],
+            "error": f"invalid process cleanup JSON: {exc}",
+        }
+    return payload
+
+
+def _snapshot_bitwriter_logs(log_dir: Path) -> dict[str, dict[str, int]]:
+    if not log_dir.is_dir():
+        return {}
+    snapshot: dict[str, dict[str, int]] = {}
+    for path in log_dir.glob("bw_*.log"):
+        if not path.is_file():
+            continue
+        stat = path.stat()
+        snapshot[str(path.resolve())] = {
+            "size": stat.st_size,
+            "file_id": stat.st_ino,
+            "created_ns": stat.st_ctime_ns,
+        }
+    return snapshot
+
+
+def _read_bitwriter_log_deltas(
+    log_dir: Path,
+    before: dict[str, dict[str, int]],
+) -> tuple[bytes, list[dict[str, Any]], list[str]]:
+    chunks: list[bytes] = []
+    sources: list[dict[str, Any]] = []
+    issues: list[str] = []
+    if not log_dir.is_dir():
+        return b"", sources, issues
+    for path in sorted(log_dir.glob("bw_*.log"), key=lambda candidate: candidate.name.casefold()):
+        if not path.is_file():
+            continue
+        resolved = str(path.resolve())
+        previous = before.get(resolved)
+        stat = path.stat()
+        size = stat.st_size
+        start = int(previous["size"]) if previous is not None else 0
+        if previous is not None and (
+            stat.st_ino != int(previous["file_id"])
+            or stat.st_ctime_ns != int(previous["created_ns"])
+            or size < start
+        ):
+            issues.append("bitwriter_log_replaced_or_truncated")
+            continue
+        if size == start:
+            continue
+        with path.open("rb") as stream:
+            stream.seek(start)
+            data = stream.read()
+        if not data:
+            continue
+        chunks.append(data)
+        sources.append(
+            {
+                "path": resolved,
+                "start_offset": start,
+                "byte_count": len(data),
+                "sha256": sha256_bytes(data),
+            }
+        )
+    return b"\n".join(chunks), sources, list(dict.fromkeys(issues))
+
+
+class _IoCounters(ctypes.Structure):
+    _fields_ = [
+        ("ReadOperationCount", ctypes.c_uint64),
+        ("WriteOperationCount", ctypes.c_uint64),
+        ("OtherOperationCount", ctypes.c_uint64),
+        ("ReadTransferCount", ctypes.c_uint64),
+        ("WriteTransferCount", ctypes.c_uint64),
+        ("OtherTransferCount", ctypes.c_uint64),
+    ]
+
+
+class _JobBasicLimitInformation(ctypes.Structure):
+    _fields_ = [
+        ("PerProcessUserTimeLimit", ctypes.c_int64),
+        ("PerJobUserTimeLimit", ctypes.c_int64),
+        ("LimitFlags", ctypes.c_uint32),
+        ("MinimumWorkingSetSize", ctypes.c_size_t),
+        ("MaximumWorkingSetSize", ctypes.c_size_t),
+        ("ActiveProcessLimit", ctypes.c_uint32),
+        ("Affinity", ctypes.c_size_t),
+        ("PriorityClass", ctypes.c_uint32),
+        ("SchedulingClass", ctypes.c_uint32),
+    ]
+
+
+class _JobExtendedLimitInformation(ctypes.Structure):
+    _fields_ = [
+        ("BasicLimitInformation", _JobBasicLimitInformation),
+        ("IoInfo", _IoCounters),
+        ("ProcessMemoryLimit", ctypes.c_size_t),
+        ("JobMemoryLimit", ctypes.c_size_t),
+        ("PeakProcessMemoryUsed", ctypes.c_size_t),
+        ("PeakJobMemoryUsed", ctypes.c_size_t),
+    ]
+
+
+def windows_process_is_running(pid: int) -> bool:
+    if os.name != "nt":
+        return False
+    kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+    kernel32.OpenProcess.argtypes = [ctypes.c_uint32, ctypes.c_bool, ctypes.c_uint32]
+    kernel32.OpenProcess.restype = ctypes.c_void_p
+    kernel32.WaitForSingleObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
+    kernel32.WaitForSingleObject.restype = ctypes.c_uint32
+    kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
+    kernel32.CloseHandle.restype = ctypes.c_bool
+    handle = kernel32.OpenProcess(0x00100000, False, int(pid))
+    if not handle:
+        return False
+    try:
+        return kernel32.WaitForSingleObject(handle, 0) == 0x00000102
+    finally:
+        kernel32.CloseHandle(handle)
+
+
+def run_process_in_job(
+    command: list[str],
+    *,
+    cwd: str,
+    timeout: float,
+    capture_output: bool,
+    text: bool,
+    check: bool,
+) -> subprocess.CompletedProcess[str]:
+    """Run one process in a kill-on-close Windows Job Object."""
+    if os.name != "nt":
+        return subprocess.run(
+            command,
+            cwd=cwd,
+            timeout=timeout,
+            capture_output=capture_output,
+            text=text,
+            check=check,
+        )
+    kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+    kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, ctypes.c_wchar_p]
+    kernel32.CreateJobObjectW.restype = ctypes.c_void_p
+    kernel32.SetInformationJobObject.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_uint32]
+    kernel32.SetInformationJobObject.restype = ctypes.c_bool
+    kernel32.AssignProcessToJobObject.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
+    kernel32.AssignProcessToJobObject.restype = ctypes.c_bool
+    kernel32.TerminateJobObject.argtypes = [ctypes.c_void_p, ctypes.c_uint32]
+    kernel32.TerminateJobObject.restype = ctypes.c_bool
+    kernel32.CloseHandle.argtypes = [ctypes.c_void_p]
+    kernel32.CloseHandle.restype = ctypes.c_bool
+    job = kernel32.CreateJobObjectW(None, None)
+    if not job:
+        raise OSError(ctypes.get_last_error(), "CreateJobObjectW failed")
+    info = _JobExtendedLimitInformation()
+    info.BasicLimitInformation.LimitFlags = 0x00002000
+    if not kernel32.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info)):
+        error = ctypes.get_last_error()
+        kernel32.CloseHandle(job)
+        raise OSError(error, "SetInformationJobObject failed")
+    stdout_pipe = subprocess.PIPE if capture_output else None
+    stderr_pipe = subprocess.PIPE if capture_output else None
+    process = subprocess.Popen(
+        command,
+        cwd=cwd,
+        stdout=stdout_pipe,
+        stderr=stderr_pipe,
+        text=text,
+    )
+    try:
+        if not kernel32.AssignProcessToJobObject(job, ctypes.c_void_p(int(process._handle))):
+            process.kill()
+            process.wait()
+            raise OSError(ctypes.get_last_error(), "AssignProcessToJobObject failed")
+        try:
+            stdout, stderr = process.communicate(timeout=timeout)
+        except subprocess.TimeoutExpired as exc:
+            kernel32.TerminateJobObject(job, 1)
+            stdout, stderr = process.communicate()
+            raise subprocess.TimeoutExpired(command, timeout, output=stdout, stderr=stderr) from exc
+        result = subprocess.CompletedProcess(command, process.returncode, stdout, stderr)
+        if check and result.returncode != 0:
+            raise subprocess.CalledProcessError(result.returncode, command, output=stdout, stderr=stderr)
+        return result
+    finally:
+        kernel32.CloseHandle(job)
+
+
+def _artifact(path: Path) -> dict[str, Any]:
+    return {"path": str(path), "size": path.stat().st_size, "sha256": sha256_file(path)}
+
+
+def _recompute_receipt_status(receipt: dict[str, Any]) -> None:
+    failures = list(dict.fromkeys(receipt["parser"]["failures"]))
+    receipt["parser"]["failures"] = failures
+    receipt["parser"]["status"] = "pass" if not failures else "fail"
+    if any(failure.startswith("forbidden_action:") for failure in failures):
+        receipt["status"] = "fail_forbidden_action"
+    else:
+        receipt["status"] = receipt["parser"]["status"]
+
+
+def execute_program_sram(
+    *,
+    source_bitstream: Path,
+    expected_bitstream_sha256: str,
+    build_id: str,
+    output_dir: Path,
+    td_root: Path,
+    run_id: str,
+    process_runner: Callable[..., subprocess.CompletedProcess[str]] = run_process_in_job,
+    cleanup_runner: Callable[[Path], dict[str, Any]] = close_td_processes,
+    mutex_factory: Callable[[], Any] = WindowsNamedMutex,
+) -> dict[str, Any]:
+    """Execute exactly one SRAM download and return a strict transaction receipt."""
+    source_bitstream = Path(source_bitstream)
+    output_dir = Path(output_dir)
+    td_root = Path(td_root)
+    if output_dir.exists() and any(output_dir.iterdir()):
+        raise FileExistsError(f"output directory is not empty: {output_dir}")
+    if not source_bitstream.is_file():
+        raise FileNotFoundError(source_bitstream)
+    if not SHA256_RE.fullmatch(expected_bitstream_sha256):
+        raise ValueError("expected bitstream SHA256 must be 64 hexadecimal characters")
+    source_sha256 = sha256_file(source_bitstream)
+    if source_sha256.casefold() != expected_bitstream_sha256.casefold():
+        raise ValueError("bitstream SHA256 mismatch before staging")
+    staged = Path(staged_bitstream_path(build_id))
+    bw_exe = td_root / "bin" / "bw_commands_prompt.exe"
+    if not bw_exe.is_file():
+        raise FileNotFoundError(bw_exe)
+
+    output_dir.mkdir(parents=True, exist_ok=True)
+    tcl_path = output_dir / "program-sram.tcl"
+    stdout_path = output_dir / "bitwriter-stdout.log"
+    stderr_path = output_dir / "bitwriter-stderr.log"
+    delta_path = output_dir / "bitwriter-log-delta.log"
+    started_at = utc_now()
+    start_monotonic = time.monotonic()
+
+    with mutex_factory():
+        cleanup = cleanup_runner(td_root)
+        if cleanup.get("status") != "pass":
+            raise RuntimeError(f"TD process cleanup failed: {cleanup}")
+
+        stage_root = staged.parent.parent
+        stage_root.mkdir(parents=True, exist_ok=True)
+        staged.parent.mkdir(parents=True, exist_ok=True)
+        if ntpath.normcase(str(staged.parent.resolve().parent)) != ntpath.normcase(str(stage_root.resolve())):
+            raise ValueError("staging build directory resolves outside C:\\P2U")
+        staged_temp = staged.parent / f".{staged.name}.{os.getpid()}.{time.time_ns()}.tmp"
+        try:
+            shutil.copy2(source_bitstream, staged_temp)
+            if sha256_file(staged_temp).casefold() != expected_bitstream_sha256.casefold():
+                raise ValueError("bitstream SHA256 mismatch in staging temporary file")
+            os.replace(staged_temp, staged)
+        finally:
+            if staged_temp.exists():
+                staged_temp.unlink()
+        staged_sha256 = sha256_file(staged)
+        if staged_sha256.casefold() != expected_bitstream_sha256.casefold():
+            raise ValueError("bitstream SHA256 mismatch after staging")
+        tcl_path.write_text(build_program_tcl(str(staged)), encoding="ascii", newline="\n")
+
+        log_dir = td_root / "bin" / "log"
+        before = _snapshot_bitwriter_logs(log_dir)
+        timed_out = False
+        try:
+            tcl_cli_path = tcl_path.absolute().as_posix()
+            completed = process_runner(
+                [str(bw_exe), tcl_cli_path],
+                cwd=str(td_root / "bin"),
+                timeout=PROGRAM_TIMEOUT_SECONDS,
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            exit_code = int(completed.returncode)
+            stdout = completed.stdout or ""
+            stderr = completed.stderr or ""
+        except subprocess.TimeoutExpired as exc:
+            timed_out = True
+            exit_code = -1
+            stdout = exc.stdout.decode(errors="replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
+            stderr = exc.stderr.decode(errors="replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "")
+        delta_bytes, delta_sources, delta_issues = _read_bitwriter_log_deltas(log_dir, before)
+
+    stdout_path.write_text(stdout, encoding="utf-8", newline="\n")
+    stderr_path.write_text(stderr, encoding="utf-8", newline="\n")
+    delta_path.write_bytes(delta_bytes)
+    parser_text = delta_bytes.decode("utf-8", errors="replace") if len(delta_sources) == 1 and not delta_issues else ""
+    receipt = build_program_sram_receipt(
+        transcript=parser_text,
+        build_id=build_id,
+        bitstream_path=str(staged),
+        bitstream_bytes=staged.read_bytes(),
+        expected_bitstream_sha256=expected_bitstream_sha256,
+        exit_code=exit_code,
+        run_id=run_id,
+        command_execution_attempted=True,
+        timed_out=timed_out,
+        td_bin=str(td_root / "bin"),
+    )
+    authoritative_marker_signature = _marker_signature(parser_text)
+    if not delta_bytes:
+        receipt["parser"]["failures"].append("missing_bitwriter_log_delta")
+        receipt["parser"]["ordered_markers_complete"] = False
+    if len(delta_sources) > 1:
+        receipt["parser"]["failures"].append("ambiguous_bitwriter_log_sources")
+        receipt["parser"]["ordered_markers_complete"] = False
+    receipt["parser"]["failures"].extend(delta_issues)
+    for stream_name, output in (("stdout", stdout), ("stderr", stderr)):
+        output_failures, output_error_markers, output_forbidden = _transcript_failures(output)
+        receipt["parser"]["failures"].extend(output_failures)
+        receipt["parser"]["error_markers"] = list(
+            dict.fromkeys(receipt["parser"]["error_markers"] + output_error_markers)
+        )
+        if _contains_transaction_marker(output):
+            output_signature = _marker_signature(output)
+            if (
+                stream_name == "stdout"
+                and authoritative_marker_signature
+                and output_signature == authoritative_marker_signature
+            ):
+                receipt["parser"]["stdout_transaction_mirror"] = True
+            else:
+                receipt["parser"]["failures"].append(f"transaction_marker_mismatch:{stream_name}")
+        if output_forbidden:
+            receipt["safety"]["flash_attempted"] = True
+            receipt["safety"]["programs_nonvolatile"] = True
+    receipt["execution"].update(
+        {
+            "timeout_seconds": PROGRAM_TIMEOUT_SECONDS,
+            "started_at": started_at,
+            "finished_at": utc_now(),
+            "duration_seconds": round(time.monotonic() - start_monotonic, 6),
+        }
+    )
+    receipt["tool"] = {
+        "path": str(bw_exe),
+        "td_root": str(td_root),
+        "td_bin": str(td_root / "bin"),
+    }
+    receipt["mutex"] = {"name": MUTEX_NAME, "acquired": True}
+    receipt["process_cleanup"] = cleanup
+    receipt["artifacts"] = {
+        "tcl": _artifact(tcl_path),
+        "stdout": _artifact(stdout_path),
+        "stderr": _artifact(stderr_path),
+        "log_delta": _artifact(delta_path),
+        "log_delta_sources": delta_sources,
+    }
+    _recompute_receipt_status(receipt)
+    receipt_path = output_dir / "program-sram-receipt.json"
+    receipt_temp = output_dir / ".program-sram-receipt.json.tmp"
+    receipt_temp.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8", newline="\n")
+    os.replace(receipt_temp, receipt_path)
+    return receipt
+
+
+def _contains_transaction_marker(transcript: str) -> bool:
+    return any(
+        START_COMMAND_RE.match(line.strip())
+        or FINISH_COMMAND_RE.match(line.strip())
+        or CHIP_RE.match(line.strip())
+        for line in transcript.splitlines()
+    )
+
+
+def _marker_records(transcript: str) -> list[dict[str, Any]]:
+    records: list[dict[str, Any]] = []
+    for line_number, raw_line in enumerate(transcript.splitlines(), start=1):
+        line = raw_line.strip()
+        start = START_COMMAND_RE.match(line)
+        finish = FINISH_COMMAND_RE.match(line)
+        chip = CHIP_RE.match(line)
+        if start:
+            command = start.group("command")
+            if command == "connect_cable -allink":
+                records.append({"marker": "connect_cable_start", "command": command, "line": line_number})
+            elif command.startswith("download "):
+                records.append({"marker": "download_start", "command": command, "line": line_number})
+            elif command.startswith("bit_to_vec "):
+                records.append({"marker": "bit_to_vec_start", "command": command, "line": line_number})
+            elif command.startswith("program "):
+                records.append({"marker": "program_start", "command": command, "line": line_number})
+            else:
+                records.append(
+                    {
+                        "marker": "unrecognized_run_operation",
+                        "operation": _operation_name(command),
+                        "line": line_number,
+                    }
+                )
+        elif finish:
+            command = finish.group("command")
+            if command == "connect_cable -allink":
+                records.append({"marker": "connect_cable_finish", "command": command, "line": line_number})
+            elif command.startswith("bit_to_vec "):
+                records.append({"marker": "bit_to_vec_finish", "command": command, "line": line_number})
+            elif command.startswith("program "):
+                records.append({"marker": "program_finish", "command": command, "line": line_number})
+            elif command.startswith("download "):
+                records.append({"marker": "download_finish", "command": command, "line": line_number})
+            else:
+                records.append(
+                    {
+                        "marker": "unrecognized_run_operation",
+                        "operation": _operation_name(command),
+                        "line": line_number,
+                    }
+                )
+        elif chip:
+            records.append(
+                {
+                    "marker": "chip_validation",
+                    "chip": chip.group("chip"),
+                    "line": line_number,
+                }
+            )
+    return records
+
+
+def _operation_name(command: str) -> str:
+    parts = command.split(maxsplit=1)
+    return parts[0].casefold() if parts else "<empty>"
+
+
+def _marker_failures(records: list[dict[str, Any]]) -> list[str]:
+    failures: list[str] = []
+    observed_all = [str(record["marker"]) for record in records]
+    observed = [marker for marker in observed_all if marker in EXPECTED_MARKERS]
+    setup_observed = [marker for marker in observed_all if marker in SETUP_MARKERS]
+    for record in records:
+        if record["marker"] == "unrecognized_run_operation":
+            failures.append(f"unrecognized_run_operation:{record['operation']}")
+    if setup_observed and (
+        setup_observed != list(SETUP_MARKERS)
+        or observed_all[: len(SETUP_MARKERS)] != list(SETUP_MARKERS)
+    ):
+        failures.append("connect_cable_marker_mismatch")
+    if any(observed.count(expected) != 1 for expected in EXPECTED_MARKERS) or any(
+        marker == "unrecognized_run_operation" for marker in observed_all
+    ):
+        failures.append("transaction_count_not_one")
+    for index, expected in enumerate(EXPECTED_MARKERS):
+        if expected not in observed:
+            failures.append(f"missing_marker:{expected}")
+        elif index >= len(observed) or observed[index] != expected:
+            failures.append(f"out_of_order_marker:{expected}")
+    if len(observed) != len(EXPECTED_MARKERS) and not any(
+        failure == "transaction_count_not_one" for failure in failures
+    ):
+        failures.append("marker_count_mismatch")
+    return failures
+
+
+def _marker_signature(transcript: str) -> list[tuple[str, str]]:
+    signature: list[tuple[str, str]] = []
+    for record in _marker_records(transcript):
+        detail = str(record.get("command") or record.get("chip") or record.get("operation") or "")
+        signature.append((str(record["marker"]), detail))
+    return signature
+
+
+def _record(records: list[dict[str, Any]], marker: str) -> dict[str, Any] | None:
+    matches = [record for record in records if record["marker"] == marker]
+    return matches[0] if len(matches) == 1 else None
+
+
+def _command_failures(
+    records: list[dict[str, Any]], *, expected_staging_path: str, td_bin: str
+) -> tuple[list[str], dict[str, Any]]:
+    failures: list[str] = []
+    details: dict[str, Any] = {}
+    expected_path = _canonical_windows_path(expected_staging_path, td_bin=td_bin)
+
+    chip = _record(records, "chip_validation")
+    if chip is not None and chip.get("chip") != TARGET_CHIP:
+        failures.append("chip_mismatch")
+
+    observed_paths: list[str] = []
+    for marker in ("download_start", "download_finish"):
+        record = _record(records, marker)
+        if record is None:
+            continue
+        command = str(record["command"])
+        parsed = DOWNLOAD_RE.match(command)
+        if parsed is None:
+            failures.append("download_command_mismatch")
+            continue
+        if parsed.group("mode") != "jtag" or parsed.group("cable") != "0":
+            failures.append("download_command_mismatch")
+        if parsed.group("speed") != str(JTAG_SPEED_CODE):
+            failures.append("jtag_speed_mismatch")
+        observed_paths.append(_canonical_windows_path(parsed.group("path"), td_bin=td_bin))
+
+    for marker in ("bit_to_vec_start", "bit_to_vec_finish"):
+        record = _record(records, marker)
+        if record is None:
+            continue
+        command = str(record["command"])
+        parsed = BIT_TO_VEC_RE.match(command)
+        if parsed is None:
+            failures.append("bit_to_vec_command_mismatch")
+            continue
+        if parsed.group("chip") != TARGET_CHIP:
+            failures.append("chip_mismatch")
+        if parsed.group("mode") != "jtag_burst":
+            failures.append("bit_to_vec_mode_mismatch")
+        if parsed.group("freq") != BIT_TO_VEC_FREQUENCY:
+            failures.append("bit_to_vec_frequency_mismatch")
+        observed_paths.append(_canonical_windows_path(parsed.group("path"), td_bin=td_bin))
+
+    for marker in ("program_start", "program_finish"):
+        record = _record(records, marker)
+        if record is None:
+            continue
+        command = str(record["command"])
+        parsed = PROGRAM_RE.match(command)
+        if parsed is None:
+            failures.append("program_command_mismatch")
+            continue
+        if parsed.group("cable") != "0" or parsed.group("mode") != "svf":
+            failures.append("program_command_mismatch")
+        if parsed.group("speed") != str(JTAG_SPEED_CODE):
+            failures.append("jtag_speed_mismatch")
+
+    if observed_paths and any(path != expected_path for path in observed_paths):
+        failures.append("staging_path_mismatch")
+    if len(set(observed_paths)) > 1:
+        failures.append("transaction_bitstream_path_mismatch")
+    details["expected_staging_path"] = expected_path
+    details["observed_bitstream_paths"] = sorted(set(observed_paths))
+    return failures, details
+
+
+def _transcript_failures(transcript: str) -> tuple[list[str], list[str], bool]:
+    failures: list[str] = []
+    error_markers: list[str] = []
+    forbidden = False
+    for raw_line in transcript.splitlines():
+        for match in ERROR_RE.finditer(raw_line):
+            marker = match.group(0)
+            if marker.casefold() not in {item.casefold() for item in error_markers}:
+                error_markers.append(marker)
+                failures.append(f"error_marker:{marker}")
+        for match in FORBIDDEN_RE.finditer(raw_line):
+            forbidden = True
+            action = match.group(0).lower()
+            failure = f"forbidden_action:{action}"
+            if failure not in failures:
+                failures.append(failure)
+    return failures, error_markers, forbidden
+
+
+def build_program_sram_receipt(
+    *,
+    transcript: str,
+    build_id: str,
+    bitstream_path: str,
+    bitstream_bytes: bytes,
+    expected_bitstream_sha256: str,
+    exit_code: int,
+    run_id: str,
+    command_execution_attempted: bool = False,
+    timed_out: bool = False,
+    td_bin: str = "",
+) -> dict[str, Any]:
+    """Build a strict receipt from the exact BitWriter log increment."""
+    failures: list[str] = []
+    try:
+        expected_staging_path = staged_bitstream_path(build_id)
+    except ValueError:
+        expected_staging_path = ""
+        failures.append("build_id_invalid")
+
+    records = _marker_records(transcript)
+    failures.extend(_marker_failures(records))
+    command_failures, command_details = _command_failures(
+        records,
+        expected_staging_path=expected_staging_path,
+        td_bin=td_bin,
+    )
+    failures.extend(command_failures)
+    transcript_failures, error_markers, forbidden = _transcript_failures(transcript)
+    failures.extend(transcript_failures)
+
+    actual_sha256 = hashlib.sha256(bitstream_bytes).hexdigest()
+    if not SHA256_RE.fullmatch(expected_bitstream_sha256):
+        failures.append("bitstream_sha256_invalid")
+    elif actual_sha256.casefold() != expected_bitstream_sha256.casefold():
+        failures.append("bitstream_sha256_mismatch")
+    staging_matches = (
+        bool(expected_staging_path)
+        and _canonical_windows_path(bitstream_path, td_bin=td_bin)
+        == _canonical_windows_path(expected_staging_path, td_bin=td_bin)
+    )
+    if not staging_matches:
+        failures.append("staging_path_mismatch")
+    if exit_code != 0:
+        failures.append("exit_code_nonzero")
+    if not command_execution_attempted:
+        failures.append("program_command_not_executed")
+    if timed_out:
+        failures.append("program_timeout")
+
+    failures = list(dict.fromkeys(failures))
+    transaction_records = [record for record in records if record["marker"] in EXPECTED_MARKERS]
+    setup_records = [record for record in records if record["marker"] in SETUP_MARKERS]
+    ordered_markers_complete = (
+        [record["marker"] for record in transaction_records] == list(EXPECTED_MARKERS)
+        and not any(failure.startswith(("missing_marker:", "out_of_order_marker:")) for failure in failures)
+        and "connect_cable_marker_mismatch" not in failures
+    )
+    parser_status = "pass" if not failures else "fail"
+    status = "fail_forbidden_action" if forbidden else parser_status
+
+    return {
+        "schema": SCHEMA_NAME,
+        "status": status,
+        "run_id": run_id,
+        "request": {
+            "operation": "PROGRAM_SRAM",
+            "target_chip": TARGET_CHIP,
+            "cable_index": 0,
+            "speed_code": JTAG_SPEED_CODE,
+            "speed_hz": JTAG_SPEED_HZ,
+            "attempt_limit": 1,
+            "power_cycle_allowed": False,
+        },
+        "bitstream": {
+            "path": bitstream_path,
+            "sha256": actual_sha256,
+            "build_id": build_id,
+        },
+        "staging": {
+            "expected_path": expected_staging_path,
+            "observed_path": bitstream_path,
+            "matches_expected_path": staging_matches,
+        },
+        "execution": {
+            "exit_code": exit_code,
+            "timed_out": timed_out,
+            "attempt_count": 1,
+            "retry_count": 0,
+            "power_cycle_count": 0,
+            "command_execution_attempted": command_execution_attempted,
+        },
+        "parser": {
+            "status": parser_status,
+            "exit_code_trusted": False,
+            "ordered_markers": list(EXPECTED_MARKERS),
+            "ordered_markers_complete": ordered_markers_complete,
+            "observed_markers": [record["marker"] for record in transaction_records],
+            "observed_marker_lines": [record["line"] for record in transaction_records],
+            "setup_markers": [record["marker"] for record in setup_records],
+            "setup_marker_lines": [record["line"] for record in setup_records],
+            "stdout_transaction_mirror": False,
+            "error_markers": error_markers,
+            "failures": failures,
+            "transcript_sha256": hashlib.sha256(transcript.encode("utf-8")).hexdigest(),
+            **command_details,
+        },
+        "safety": {
+            "flash_attempted": forbidden,
+            "programs_nonvolatile": forbidden,
+            "power_cycle_attempted": False,
+            "driver_install_attempted": False,
+            "toggles_dtr_rts": False,
+            "real_ptc_fan_action_attempted": False,
+            "external_programming_command_executed": command_execution_attempted,
+        },
+        "authority_boundary": (
+            "This receipt proves only one parsed PROGRAM_SRAM transaction against the staged bitstream. "
+            "It does not certify flash, thermal performance, real PTC/FAN load behavior, or PID closed-loop behavior."
+        ),
+    }
+
+
+def build_parser() -> argparse.ArgumentParser:
+    parser = argparse.ArgumentParser(description=__doc__)
+    parser.add_argument("--transcript", type=Path, required=True, help="captured BitWriter log increment")
+    parser.add_argument("--bitstream", type=Path, required=True, help="staged bitstream to hash")
+    parser.add_argument("--build-id", required=True)
+    parser.add_argument("--sha256", required=True, dest="expected_bitstream_sha256")
+    parser.add_argument("--exit-code", type=int, default=0, help="observed tool exit code")
+    parser.add_argument("--run-id", required=True)
+    parser.add_argument("--td-bin", default="")
+    parser.add_argument("--receipt", type=Path, help="optional JSON receipt output path")
+    return parser
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = build_parser().parse_args(argv)
+    receipt = build_program_sram_receipt(
+        transcript=args.transcript.read_text(encoding="utf-8", errors="replace"),
+        build_id=args.build_id,
+        bitstream_path=str(args.bitstream),
+        bitstream_bytes=args.bitstream.read_bytes(),
+        expected_bitstream_sha256=args.expected_bitstream_sha256,
+        exit_code=args.exit_code,
+        run_id=args.run_id,
+        command_execution_attempted=False,
+        timed_out=False,
+        td_bin=args.td_bin,
+    )
+    encoded = json.dumps(receipt, indent=2) + "\n"
+    if args.receipt is not None:
+        args.receipt.parent.mkdir(parents=True, exist_ok=True)
+        args.receipt.write_text(encoded, encoding="utf-8", newline="\n")
+    print(encoded, end="")
+    return 0 if receipt["status"] == "pass" else 1
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 423 - 0
tools/prod2u_receipts.py

@@ -0,0 +1,423 @@
+#!/usr/bin/env python3
+"""Strict receipt validation for the Prod2U SRAM-only workflow."""
+
+from __future__ import annotations
+
+import ntpath
+import re
+from typing import Any, Mapping
+
+
+PROFILE = "prod2u-bmc-replay-binary921"
+PROFILE_ID = 3
+PROGRAM_SCHEMA = "prod2u-program-sram-receipt-v1"
+EVIDENCE_SCHEMA = "prod2u-evidence-manifest-v1"
+FINAL_SCHEMA = "prod2u-final-gate-v1"
+SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
+BUILD_ID_RE = re.compile(r"^[0-9a-fA-F]{8}$")
+EMPTY_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
+EXPECTED_PROGRAM_MARKERS = (
+    "download_start",
+    "chip_validation",
+    "bit_to_vec_start",
+    "bit_to_vec_finish",
+    "program_start",
+    "program_finish",
+    "download_finish",
+)
+REQUIRED_FINAL_LAYERS = (
+    "static",
+    "rtl_sim",
+    "formal",
+    "td_build",
+    "program_sram",
+    "fresh_epoch",
+    "host_uart",
+    "bmc_replay",
+)
+
+
+def _mapping(value: Any) -> Mapping[str, Any]:
+    return value if isinstance(value, Mapping) else {}
+
+
+def _is_nonempty_sha256(value: Any) -> bool:
+    return (
+        isinstance(value, str)
+        and SHA256_RE.fullmatch(value) is not None
+        and value.casefold() != EMPTY_SHA256
+    )
+
+
+def _false_safety_flags(payload: Mapping[str, Any], names: tuple[str, ...]) -> list[str]:
+    failures: list[str] = []
+    safety = _mapping(payload.get("safety"))
+    for name in names:
+        if safety.get(name) is not False:
+            failures.append(f"safety_flag_not_false:{name}")
+    return failures
+
+
+def validate_program_receipt(payload: Mapping[str, Any]) -> dict[str, Any]:
+    failures: list[str] = []
+    forbidden = False
+    request = _mapping(payload.get("request"))
+    execution = _mapping(payload.get("execution"))
+    parser = _mapping(payload.get("parser"))
+    bitstream = _mapping(payload.get("bitstream"))
+    staging = _mapping(payload.get("staging"))
+    mutex = _mapping(payload.get("mutex"))
+    cleanup = _mapping(payload.get("process_cleanup"))
+    tool = _mapping(payload.get("tool"))
+    artifacts = _mapping(payload.get("artifacts"))
+    safety = _mapping(payload.get("safety"))
+
+    if payload.get("schema") != PROGRAM_SCHEMA:
+        failures.append("program_schema_mismatch")
+    if payload.get("status") != "pass":
+        failures.append("program_status_not_pass")
+    if request.get("operation") != "PROGRAM_SRAM":
+        failures.append("operation_not_program_sram")
+        forbidden = True
+    if request.get("target_chip") != "EF2L45":
+        failures.append("target_chip_not_ef2l45")
+    if request.get("cable_index") != 0:
+        failures.append("cable_index_not_zero")
+    if request.get("speed_code") != 2 or request.get("speed_hz") != 200000:
+        failures.append("jtag_speed_not_200khz")
+    if request.get("attempt_limit") != 1:
+        failures.append("attempt_limit_not_one")
+    if request.get("power_cycle_allowed") is not False:
+        failures.append("power_cycle_allowed_not_false")
+
+    if execution.get("attempt_count") != 1:
+        failures.append("attempt_count_not_one")
+    if execution.get("retry_count") != 0:
+        failures.append("retry_count_not_zero")
+    if execution.get("power_cycle_count") != 0:
+        failures.append("power_cycle_count_not_zero")
+    if execution.get("timed_out") is not False:
+        failures.append("program_timed_out")
+    if execution.get("exit_code") != 0:
+        failures.append("program_exit_code_nonzero")
+    if execution.get("command_execution_attempted") is not True:
+        failures.append("program_command_not_executed")
+    if execution.get("timeout_seconds") != 60:
+        failures.append("program_timeout_boundary_not_60")
+    if parser.get("status") != "pass" or parser.get("ordered_markers_complete") is not True:
+        failures.append("program_marker_transaction_not_pass")
+    if parser.get("observed_markers") != list(EXPECTED_PROGRAM_MARKERS):
+        failures.append("program_observed_markers_not_exact")
+    if parser.get("error_markers") not in ([], None):
+        failures.append("program_error_markers_present")
+    if parser.get("failures") not in ([], None):
+        failures.append("program_parser_failures_present")
+    if not _is_nonempty_sha256(parser.get("transcript_sha256")):
+        failures.append("program_transcript_sha256_invalid_or_empty")
+
+    build_id = bitstream.get("build_id")
+    if not isinstance(build_id, str) or not BUILD_ID_RE.fullmatch(build_id):
+        failures.append("program_build_id_invalid")
+    if not isinstance(bitstream.get("sha256"), str) or not SHA256_RE.fullmatch(str(bitstream.get("sha256"))):
+        failures.append("program_bitstream_sha256_invalid")
+    if isinstance(build_id, str) and BUILD_ID_RE.fullmatch(build_id):
+        expected_path = ntpath.normcase(ntpath.normpath(f"C:\\P2U\\{build_id.upper()}\\fw.bit"))
+        observed_paths = (
+            bitstream.get("path"),
+            staging.get("expected_path"),
+            staging.get("observed_path"),
+        )
+        if any(
+            not isinstance(path, str) or ntpath.normcase(ntpath.normpath(path)) != expected_path
+            for path in observed_paths
+        ):
+            failures.append("staging_path_not_verified")
+    if staging.get("matches_expected_path") is not True:
+        failures.append("staging_path_not_verified")
+
+    if mutex.get("name") != r"Global\Prod2UProgramSram" or mutex.get("acquired") is not True:
+        failures.append("program_mutex_not_acquired")
+    if cleanup.get("status") != "pass" or cleanup.get("remaining") not in ([], None):
+        failures.append("td_process_cleanup_not_pass")
+    if cleanup.get("wait_seconds") != 5.0:
+        failures.append("td_process_cleanup_wait_not_5s")
+    tool_td_root = tool.get("td_root")
+    cleanup_td_root = cleanup.get("td_root")
+    if (
+        not isinstance(tool_td_root, str)
+        or not tool_td_root.strip()
+        or not isinstance(cleanup_td_root, str)
+        or not cleanup_td_root.strip()
+        or ntpath.normcase(ntpath.normpath(cleanup_td_root))
+        != ntpath.normcase(ntpath.normpath(tool_td_root))
+    ):
+        failures.append("cleanup_td_root_mismatch")
+    tool_path = tool.get("path")
+    if not isinstance(tool_path, str) or ntpath.basename(tool_path).casefold() != "bw_commands_prompt.exe":
+        failures.append("programmer_tool_not_bw_commands_prompt")
+    for name in ("tcl", "stdout", "stderr", "log_delta"):
+        artifact = _mapping(artifacts.get(name))
+        if not isinstance(artifact.get("sha256"), str) or not SHA256_RE.fullmatch(str(artifact.get("sha256"))):
+            failures.append(f"program_artifact_hash_invalid:{name}")
+    log_delta = _mapping(artifacts.get("log_delta"))
+    log_delta_size = log_delta.get("size")
+    if (
+        not isinstance(log_delta_size, int)
+        or isinstance(log_delta_size, bool)
+        or log_delta_size <= 0
+        or not _is_nonempty_sha256(log_delta.get("sha256"))
+    ):
+        failures.append("program_log_delta_empty")
+    log_sources = artifacts.get("log_delta_sources")
+    valid_log_source = False
+    if isinstance(log_sources, list) and len(log_sources) == 1:
+        log_source = _mapping(log_sources[0])
+        log_source_path = log_source.get("path")
+        byte_count = log_source.get("byte_count")
+        start_offset = log_source.get("start_offset")
+        valid_log_source = (
+            isinstance(log_source_path, str)
+            and re.fullmatch(r"bw_.+\.log", ntpath.basename(log_source_path), re.IGNORECASE) is not None
+            and isinstance(start_offset, int)
+            and not isinstance(start_offset, bool)
+            and start_offset >= 0
+            and isinstance(byte_count, int)
+            and not isinstance(byte_count, bool)
+            and byte_count > 0
+            and _is_nonempty_sha256(log_source.get("sha256"))
+        )
+    if not valid_log_source:
+        failures.append("bitwriter_log_source_not_exactly_one_nonempty")
+    if safety.get("external_programming_command_executed") is not True:
+        failures.append("external_programming_command_not_recorded")
+
+    safety_failures = _false_safety_flags(
+        payload,
+        (
+            "flash_attempted",
+            "programs_nonvolatile",
+            "power_cycle_attempted",
+            "driver_install_attempted",
+            "toggles_dtr_rts",
+            "real_ptc_fan_action_attempted",
+        ),
+    )
+    failures.extend(safety_failures)
+    if any(name in {"safety_flag_not_false:flash_attempted", "safety_flag_not_false:programs_nonvolatile"} for name in safety_failures):
+        forbidden = True
+
+    status = "pass" if not failures else ("fail_forbidden_action" if forbidden else "fail")
+    return {"schema": "prod2u-program-sram-validation-v1", "status": status, "failures": failures}
+
+
+def validate_evidence_manifest(evidence: Mapping[str, Any], program: Mapping[str, Any]) -> dict[str, Any]:
+    failures: list[str] = []
+    program_result = validate_program_receipt(program)
+    if program_result["status"] != "pass":
+        failures.append(f"program_receipt_not_pass:{program_result['status']}")
+
+    if evidence.get("schema") != EVIDENCE_SCHEMA:
+        failures.append("evidence_schema_mismatch")
+    declared_status = evidence.get("status")
+    if declared_status not in ("pass", "blocked_bmc_replay_not_run"):
+        failures.append(f"evidence_declared_status_not_pass:{declared_status}")
+    blockers = evidence.get("blockers", [])
+    if declared_status == "blocked_bmc_replay_not_run":
+        if blockers not in (None, [], ["bmc_replay_not_pass"]):
+            failures.append("evidence_blockers_not_expected_bmc_only")
+    elif blockers not in (None, []):
+        failures.append("evidence_blockers_not_empty")
+    if evidence.get("protocol") != "binary921":
+        failures.append("protocol_not_binary921")
+    if evidence.get("profile") != PROFILE or evidence.get("profile_id") != PROFILE_ID:
+        failures.append("profile_mismatch")
+
+    identity = _mapping(evidence.get("build_identity"))
+    ready = _mapping(evidence.get("startup_ready"))
+    program_bitstream = _mapping(program.get("bitstream"))
+    evidence_build_id = identity.get("build_id")
+    source_manifest_sha256 = identity.get("source_manifest_sha256")
+    ready_build_id = ready.get("build_id")
+    program_build_id = program_bitstream.get("build_id")
+    if not isinstance(evidence_build_id, str) or not BUILD_ID_RE.fullmatch(evidence_build_id):
+        failures.append("evidence_build_id_invalid")
+    if not isinstance(source_manifest_sha256, str) or not SHA256_RE.fullmatch(source_manifest_sha256):
+        failures.append("source_manifest_sha256_invalid")
+    elif (
+        not isinstance(evidence_build_id, str)
+        or not BUILD_ID_RE.fullmatch(evidence_build_id)
+        or evidence_build_id.casefold() != source_manifest_sha256[:8].casefold()
+    ):
+        failures.append("source_manifest_build_id_mismatch")
+    if len({str(evidence_build_id), str(ready_build_id), str(program_build_id)}) != 1:
+        failures.append("program_ready_build_id_mismatch")
+
+    if ready.get("frame_type") != 1 or ready.get("seq") != 1:
+        failures.append("startup_ready_sequence_invalid")
+    if ready.get("profile_id") != PROFILE_ID:
+        failures.append("startup_ready_profile_mismatch")
+    if ready.get("post_program_epoch") is not True:
+        failures.append("startup_ready_not_post_program_epoch")
+    if ready.get("por_reason") != 1:
+        failures.append("startup_ready_por_reason_invalid")
+    announcement_seq = ready.get("announcement_seq")
+    if not isinstance(announcement_seq, int) or announcement_seq < 0 or announcement_seq > 2:
+        failures.append("startup_ready_announcement_seq_invalid")
+    if ready.get("selection_policy") != "last_matching_ready":
+        failures.append("startup_ready_selection_policy_invalid")
+    matching_ready_count = ready.get("matching_ready_count")
+    if not isinstance(matching_ready_count, int) or isinstance(matching_ready_count, bool) or matching_ready_count < 1:
+        failures.append("startup_ready_matching_count_invalid")
+
+    for name in ("host_command_count", "host_ack_count", "host_ack_matched_count"):
+        if evidence.get(name) != 12:
+            failures.append(f"{name}_not_12")
+
+    artifacts = _mapping(evidence.get("artifact_hashes"))
+    for name in ("combined-rx.raw", "host-command-wire.bin"):
+        value = artifacts.get(name)
+        if not isinstance(value, str) or not SHA256_RE.fullmatch(value):
+            failures.append(f"artifact_hash_missing_or_invalid:{name}")
+        elif value.casefold() == EMPTY_SHA256:
+            failures.append(f"artifact_hash_empty:{name}")
+
+    programmer_receipt = _mapping(evidence.get("programmer_receipt"))
+    programmer_receipt_sha256 = programmer_receipt.get("sha256")
+    if programmer_receipt.get("status") != "pass":
+        failures.append("programmer_receipt_status_not_pass")
+    if not isinstance(programmer_receipt.get("path"), str) or not str(programmer_receipt.get("path")).strip():
+        failures.append("programmer_receipt_path_missing")
+    if not isinstance(programmer_receipt_sha256, str) or not SHA256_RE.fullmatch(programmer_receipt_sha256):
+        failures.append("programmer_receipt_sha256_invalid")
+    elif programmer_receipt_sha256.casefold() == EMPTY_SHA256:
+        failures.append("programmer_receipt_sha256_empty")
+
+    bmc = _mapping(evidence.get("bmc_replay"))
+    bmc_pass = bmc.get("status") == "pass"
+    if not bmc_pass:
+        failures.append("bmc_replay_not_pass")
+    else:
+        if bmc.get("bmc_source") != "pc_replay_from_real_bmc_capture":
+            failures.append("bmc_source_not_pc_replay")
+        if not isinstance(bmc.get("payload_sha256"), str) or not SHA256_RE.fullmatch(str(bmc.get("payload_sha256"))):
+            failures.append("bmc_payload_sha256_invalid")
+        elif str(bmc.get("payload_sha256")).casefold() == EMPTY_SHA256:
+            failures.append("bmc_payload_sha256_empty")
+
+    if evidence.get("real_fan_ptc_hardware_status") != "not_run":
+        failures.append("real_fan_ptc_hardware_status_not_not_run")
+    failures.extend(
+        _false_safety_flags(
+            evidence,
+            ("flash_attempted", "programs_nonvolatile", "driver_install_attempted", "power_cycle_attempted", "toggles_dtr_rts"),
+        )
+    )
+
+    non_bmc_failures = [failure for failure in failures if failure != "bmc_replay_not_pass"]
+    if not failures:
+        status = "pass"
+    elif not bmc_pass and not non_bmc_failures:
+        status = "blocked_bmc_replay_not_run"
+    else:
+        status = "fail"
+    return {"schema": "prod2u-evidence-validation-v1", "status": status, "failures": failures}
+
+
+def assemble_evidence_manifest(
+    *,
+    collector: Mapping[str, Any],
+    program: Mapping[str, Any],
+    source_manifest: Mapping[str, Any],
+    programmer_receipt_path: str,
+    programmer_receipt_sha256: str,
+) -> dict[str, Any]:
+    ready = _mapping(collector.get("startup_ready"))
+    ready_decoded = _mapping(ready.get("decoded"))
+    build_id = str(source_manifest.get("build_id", "")).upper()
+    source_hash = str(source_manifest.get("source_manifest_sha256", "")).lower()
+    program_result = validate_program_receipt(program)
+    post_program_epoch = program_result["status"] == "pass" and collector.get("status") == "pass"
+    bmc = dict(_mapping(collector.get("bmc_replay")))
+    if "payload_sha256" not in bmc and isinstance(bmc.get("reply_sha256"), str):
+        bmc["payload_sha256"] = bmc["reply_sha256"]
+
+    manifest: dict[str, Any] = {
+        "schema": EVIDENCE_SCHEMA,
+        "status": "pass",
+        "protocol": "binary921",
+        "profile": PROFILE,
+        "profile_id": PROFILE_ID,
+        "build_identity": {"build_id": build_id, "source_manifest_sha256": source_hash},
+        "programmer_receipt": {
+            "path": programmer_receipt_path,
+            "sha256": programmer_receipt_sha256,
+            "status": program_result["status"],
+        },
+        "startup_ready": {
+            "frame_type": ready.get("frame_type"),
+            "seq": ready.get("seq"),
+            "profile_id": ready.get("profile_id"),
+            "build_id": ready_decoded.get("build_id"),
+            "post_program_epoch": post_program_epoch,
+            "timestamp_tick": ready.get("timestamp_tick"),
+            "por_reason": ready_decoded.get("por_reason"),
+            "announcement_seq": ready_decoded.get("announcement_seq"),
+            "matching_ready_count": ready.get("matching_ready_count"),
+            "selection_policy": ready.get("selection_policy"),
+        },
+        "host_command_count": collector.get("host_command_count"),
+        "host_ack_count": collector.get("host_ack_count"),
+        "host_ack_matched_count": collector.get("host_ack_matched_count"),
+        "bmc_replay": bmc,
+        "artifact_hashes": dict(_mapping(collector.get("artifact_hashes"))),
+        "real_fan_ptc_hardware_status": collector.get("real_fan_ptc_hardware_status", "not_run"),
+        "safety": {
+            "flash_attempted": _mapping(collector.get("safety")).get("flash_attempted", False),
+            "programs_nonvolatile": _mapping(collector.get("safety")).get("programs_nonvolatile", False),
+            "driver_install_attempted": _mapping(collector.get("safety")).get("driver_install_attempted", False),
+            "power_cycle_attempted": _mapping(program.get("safety")).get("power_cycle_attempted", False),
+            "toggles_dtr_rts": _mapping(collector.get("safety")).get("toggles_dtr_rts", False),
+        },
+        "collector": {
+            "schema": collector.get("schema"),
+            "status": collector.get("status"),
+            "blockers": collector.get("blockers", []),
+        },
+    }
+    result = validate_evidence_manifest(manifest, program)
+    manifest["status"] = result["status"]
+    manifest["blockers"] = result["failures"]
+    return manifest
+
+
+def build_final_gate(
+    program: Mapping[str, Any], evidence: Mapping[str, Any], layers: Mapping[str, Any]
+) -> dict[str, Any]:
+    failures: list[str] = []
+    program_result = validate_program_receipt(program)
+    evidence_result = validate_evidence_manifest(evidence, program)
+    if program_result["status"] != "pass":
+        failures.append(f"program_receipt_not_pass:{program_result['status']}")
+    if evidence_result["status"] != "pass":
+        failures.append(f"evidence_manifest_not_pass:{evidence_result['status']}")
+    for name in REQUIRED_FINAL_LAYERS:
+        value = layers.get(name)
+        if value != "pass":
+            failures.append(f"required_layer_not_pass:{name}:{value}")
+
+    if not failures:
+        status = "pass"
+    elif any(value in ("not_run", "blocked") or value is None for value in layers.values()):
+        status = "blocked"
+    else:
+        status = "fail"
+    return {
+        "schema": FINAL_SCHEMA,
+        "status": status,
+        "failures": failures,
+        "layers": dict(layers),
+        "authority_boundary": (
+            "Pass proves SRAM programming, build identity, binary921 control communication, and BMC replay evidence. "
+            "It does not certify flash, thermal performance, real PTC/FAN load qualification, or PID closed-loop behavior."
+        ),
+    }

+ 421 - 0
tools/prod2u_validate.py

@@ -0,0 +1,421 @@
+#!/usr/bin/env python3
+"""Raw-first validator for Prod2U PROGRAM_SRAM binary921 evidence."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Mapping
+
+
+TOOLS = Path(__file__).resolve().parent
+if str(TOOLS) not in sys.path:
+    sys.path.insert(0, str(TOOLS))
+
+from binary921 import MAGIC, CommandId, FrameType, decode_frame, decode_payload, frame_to_dict  # noqa: E402
+from prod2u_collector import COMMAND_SEQUENCE  # noqa: E402
+from prod2u_receipts import validate_evidence_manifest  # noqa: E402
+
+
+PROFILE = "prod2u-bmc-replay-binary921"
+PROFILE_ID = 3
+
+
+def sha256_bytes(data: bytes) -> str:
+    return hashlib.sha256(data).hexdigest()
+
+
+def _mapping(value: Any) -> Mapping[str, Any]:
+    return value if isinstance(value, Mapping) else {}
+
+
+def _receipt_int(value: Any) -> int | None:
+    if isinstance(value, bool) or not isinstance(value, int):
+        return None
+    return value
+
+
+def _parse_utc(value: Any) -> datetime | None:
+    if not isinstance(value, str) or not value:
+        return None
+    normalized = value[:-1] + "+00:00" if value.endswith("Z") else value
+    try:
+        parsed = datetime.fromisoformat(normalized)
+    except ValueError:
+        return None
+    if parsed.tzinfo is None:
+        parsed = parsed.replace(tzinfo=timezone.utc)
+    return parsed.astimezone(timezone.utc)
+
+
+def strict_decode_stream(data: bytes) -> dict[str, Any]:
+    failures: list[str] = []
+    frames: list[dict[str, Any]] = []
+    offset = 0
+    if not data:
+        failures.append("raw_empty")
+    while offset < len(data):
+        if data[offset : offset + 2] != MAGIC:
+            failures.append(f"unexpected_bytes_at_offset:{offset}")
+            break
+        if len(data) - offset < 16:
+            failures.append(f"incomplete_frame_header_at_offset:{offset}")
+            break
+        payload_len = data[offset + 13]
+        end = offset + 14 + payload_len + 2
+        if end > len(data):
+            failures.append(f"incomplete_frame_at_offset:{offset}")
+            break
+        candidate = data[offset:end]
+        try:
+            frame = decode_frame(candidate)
+        except Exception as exc:
+            failures.append(f"corrupt_frame_at_offset:{offset}:{exc}")
+            break
+        row = frame_to_dict(frame)
+        row["offset"] = offset
+        row["end_offset"] = end
+        frames.append(row)
+        offset = end
+    if offset != len(data) and not failures:
+        failures.append(f"unconsumed_bytes_at_offset:{offset}")
+    return {
+        "status": "pass" if frames and not failures and offset == len(data) else "fail",
+        "byte_count": len(data),
+        "frame_count": len(frames),
+        "consumed_bytes": offset,
+        "failures": failures,
+        "frames": frames,
+    }
+
+
+def _validate_commands(frames: list[dict[str, Any]]) -> dict[str, Any]:
+    failures: list[str] = []
+    commands = [frame for frame in frames if frame.get("frame_type") == int(FrameType.HOST_CMD)]
+    if len(commands) != len(COMMAND_SEQUENCE):
+        failures.append(f"host_command_count_not_12:{len(commands)}")
+    for index, expected in enumerate(COMMAND_SEQUENCE, start=1):
+        if index > len(commands):
+            break
+        _, command, channel, percent = expected
+        frame = commands[index - 1]
+        decoded = _mapping(frame.get("decoded"))
+        if frame.get("profile_id") != PROFILE_ID:
+            failures.append(f"host_command_profile_mismatch:{index}")
+        if frame.get("seq") != index:
+            failures.append(f"host_command_seq_mismatch:{index}:{frame.get('seq')}")
+        if decoded.get("cmd_id") != int(command):
+            failures.append(f"host_command_id_mismatch:{index}")
+        if channel is not None and decoded.get("channel") != channel:
+            failures.append(f"host_command_channel_mismatch:{index}")
+        if command == CommandId.SET_PID_REQUESTED:
+            if decoded.get("enabled") is not bool(percent):
+                failures.append(f"host_command_enabled_mismatch:{index}")
+        elif percent is not None and decoded.get("percent") != percent:
+            failures.append(f"host_command_percent_mismatch:{index}")
+    return {"status": "pass" if not failures else "fail", "count": len(commands), "failures": failures}
+
+
+def _validate_acks(frames: list[dict[str, Any]]) -> dict[str, Any]:
+    failures: list[str] = []
+    acks = [frame for frame in frames if frame.get("frame_type") == int(FrameType.HOST_ACK)]
+    matched = 0
+    if len(acks) != len(COMMAND_SEQUENCE):
+        failures.append(f"host_ack_count_not_12:{len(acks)}")
+    for index, expected in enumerate(COMMAND_SEQUENCE, start=1):
+        if index > len(acks):
+            break
+        _, command, _, _ = expected
+        frame = acks[index - 1]
+        decoded = _mapping(frame.get("decoded"))
+        accepted = (
+            frame.get("profile_id") == PROFILE_ID
+            and frame.get("seq") == index
+            and decoded.get("cmd_id") == int(command)
+            and decoded.get("ok") is True
+            and decoded.get("status_code") == 0
+        )
+        if accepted:
+            matched += 1
+        else:
+            failures.append(f"host_ack_mismatch:{index}")
+    return {
+        "status": "pass" if not failures and matched == len(COMMAND_SEQUENCE) else "fail",
+        "count": len(acks),
+        "matched_count": matched,
+        "failures": failures,
+    }
+
+
+def _load_bmc_receipt(path: Path) -> dict[str, Any]:
+    if not path.is_file():
+        return {"status": "not_run", "bmc_source": "not_run", "payload_sha256": None}
+    try:
+        payload = json.loads(path.read_text(encoding="utf-8-sig"))
+    except (OSError, json.JSONDecodeError) as exc:
+        return {
+            "status": "blocked_invalid_bmc_replay_receipt",
+            "bmc_source": "not_run",
+            "payload_sha256": None,
+            "error": str(exc),
+            "failures": ["bmc_receipt_unreadable"],
+        }
+    if not isinstance(payload, dict):
+        return {
+            "status": "blocked_invalid_bmc_replay_receipt",
+            "bmc_source": "not_run",
+            "payload_sha256": None,
+            "failures": ["bmc_receipt_not_object"],
+        }
+    failures: list[str] = []
+    reply_sha = str(payload.get("reply_sha256") or payload.get("payload_reply_sha256") or "").lower()
+    values: bytes | None = None
+    payload_hex = payload.get("payload_hex")
+    if not isinstance(payload_hex, list) or len(payload_hex) != 48:
+        failures.append("bmc_receipt_payload_hex_not_48")
+    else:
+        try:
+            values = bytes(int(str(value), 16) for value in payload_hex)
+        except (TypeError, ValueError, OverflowError):
+            failures.append("bmc_receipt_payload_hex_invalid")
+        else:
+            canonical_reply = " ".join(f"{value:02x}" for value in values) + "\r\n"
+            if sha256_bytes(canonical_reply.encode("ascii")) != reply_sha:
+                failures.append("bmc_receipt_reply_sha256_mismatch")
+    if payload.get("schema") != "prod2u-bmc-replay-session-v1":
+        failures.append("bmc_receipt_schema_mismatch")
+    if payload.get("status") != "pass":
+        failures.append("bmc_receipt_status_not_pass")
+    if payload.get("bmc_source") != "pc_replay_from_real_bmc_capture":
+        failures.append("bmc_receipt_source_mismatch")
+    matched_poll_count = _receipt_int(payload.get("matched_poll_count"))
+    reply_count = _receipt_int(payload.get("reply_count"))
+    if matched_poll_count is None or matched_poll_count <= 0 or reply_count is None or reply_count <= 0:
+        failures.append("bmc_receipt_no_poll_response")
+    byte_count = _receipt_int(payload.get("byte_count"))
+    if byte_count != 48:
+        failures.append("bmc_receipt_byte_count_not_48")
+    valid_count = _receipt_int(payload.get("valid_count"))
+    missing_count = _receipt_int(payload.get("missing_count"))
+    if (
+        valid_count is None
+        or missing_count is None
+        or valid_count < 0
+        or missing_count < 0
+        or valid_count + missing_count != 24
+    ):
+        failures.append("bmc_receipt_sensor_count_not_24")
+    passed = not failures
+    return {
+        "status": "pass" if passed else "blocked_bmc_replay_not_run",
+        "schema": payload.get("schema"),
+        "bmc_source": payload.get("bmc_source", "not_run"),
+        "payload_sha256": reply_sha or None,
+        "byte_count": byte_count,
+        "valid_count": valid_count,
+        "missing_count": missing_count,
+        "matched_poll_count": matched_poll_count,
+        "reply_count": reply_count,
+        "started_at": payload.get("started_at"),
+        "last_reply_at": payload.get("last_reply_at"),
+        "payload_hex": payload_hex if values is not None else None,
+        "payload_first": None if values is None else values[0],
+        "payload_last": None if values is None else values[-1],
+        "payload_checksum": None if values is None else sum(values) & 0xFFFF,
+        "failures": failures,
+    }
+
+
+def validate_evidence_directory(
+    *,
+    collector_dir: Path,
+    collector: Mapping[str, Any],
+    program: Mapping[str, Any],
+    source_manifest: Mapping[str, Any],
+    programmer_receipt_path: str,
+    programmer_receipt_sha256: str,
+    bmc_replay_receipt_path: Path,
+) -> dict[str, Any]:
+    collector_dir = Path(collector_dir)
+    combined_path = collector_dir / "combined-rx.raw"
+    command_path = collector_dir / "host-command-wire.bin"
+    combined = combined_path.read_bytes() if combined_path.is_file() else b""
+    command_wire = command_path.read_bytes() if command_path.is_file() else b""
+    combined_validation = strict_decode_stream(combined)
+    command_validation = strict_decode_stream(command_wire)
+    combined_frames = list(combined_validation["frames"])
+    command_frames = list(command_validation["frames"])
+
+    failures: list[str] = []
+    failures.extend(f"combined:{failure}" for failure in combined_validation["failures"])
+    failures.extend(f"host_wire:{failure}" for failure in command_validation["failures"])
+
+    ready_frames = [frame for frame in combined_frames if frame.get("frame_type") == int(FrameType.READY)]
+    expected_build_id = str(source_manifest.get("build_id", "")).upper()
+
+    def ready_matches_identity(frame: Mapping[str, Any]) -> bool:
+        decoded = _mapping(frame.get("decoded"))
+        return (
+            frame.get("profile_id") == PROFILE_ID
+            and frame.get("seq") == 1
+            and decoded.get("profile_id_payload") == PROFILE_ID
+            and decoded.get("build_id") == expected_build_id
+            and decoded.get("por_reason") == 1
+            and isinstance(decoded.get("announcement_seq"), int)
+            and 0 <= int(decoded["announcement_seq"]) <= 2
+        )
+
+    matching_ready_frames = [frame for frame in ready_frames if ready_matches_identity(frame)]
+    if matching_ready_frames and int(matching_ready_frames[0].get("offset", -1)) != 0:
+        failures.append("formal_epoch_does_not_start_at_matching_ready")
+    ready = matching_ready_frames[-1] if matching_ready_frames else ready_frames[-1] if ready_frames else {}
+    ready_decoded = _mapping(ready.get("decoded"))
+    formal_frames = [
+        frame
+        for frame in combined_frames
+        if ready and int(frame.get("offset", -1)) >= int(ready.get("end_offset", 0))
+    ]
+
+    command_result = _validate_commands(command_frames)
+    ack_result = _validate_acks(formal_frames)
+    failures.extend(command_result["failures"])
+    failures.extend(ack_result["failures"])
+
+    if not ready:
+        failures.append("startup_ready_missing")
+    elif not ready_matches_identity(ready):
+        failures.append("startup_ready_identity_mismatch")
+
+    bmc_replay = _load_bmc_receipt(Path(bmc_replay_receipt_path))
+    bmc_replay_pass = bmc_replay["status"] == "pass"
+    bmc_frames = [frame for frame in formal_frames if frame.get("frame_type") == int(FrameType.BMC_PAYLOAD)]
+    sensor_frames = [frame for frame in formal_frames if frame.get("frame_type") == int(FrameType.SENSOR_CACHE)]
+    snapshot_frames = [frame for frame in formal_frames if frame.get("frame_type") == int(FrameType.MODULE_SNAPSHOT)]
+    if bmc_replay_pass and not bmc_frames:
+        failures.append("bmc_payload_frame_missing")
+    sensor = _mapping(sensor_frames[-1].get("decoded")) if sensor_frames else {}
+    valid_count = sensor.get("valid_count")
+    missing_count = sensor.get("missing_count")
+    sensor_cache_valid = (
+        isinstance(valid_count, int)
+        and isinstance(missing_count, int)
+        and valid_count + missing_count == 24
+    )
+    if bmc_replay_pass and not sensor_cache_valid:
+        failures.append("sensor_cache_not_24_dimms")
+    snapshot = _mapping(snapshot_frames[-1].get("decoded")) if snapshot_frames else {}
+    if not snapshot_frames:
+        failures.append("module_snapshot_missing")
+    pid_status = "pass" if snapshot.get("pid_requested") is False else "fail"
+    if pid_status != "pass":
+        failures.append("pid_not_inactive")
+    timeout_status = "pass" if (
+        snapshot.get("timeout_active") is True
+        and snapshot.get("ptc01_percent") == 0
+        and snapshot.get("ptc24_percent") == 0
+        and snapshot.get("fan01_percent") == 30
+        and snapshot.get("fan04_percent") == 30
+    ) else "fail"
+    if timeout_status != "pass":
+        failures.append("timeout_fallback_invalid")
+
+    actual_hashes = {
+        "combined-rx.raw": sha256_bytes(combined),
+        "host-command-wire.bin": sha256_bytes(command_wire),
+    }
+    expected_hashes = _mapping(collector.get("artifact_hashes"))
+    artifact_mismatches = [
+        name for name, actual in actual_hashes.items() if expected_hashes.get(name) != actual
+    ]
+    failures.extend(f"collector_artifact_hash_mismatch:{name}" for name in artifact_mismatches)
+    if not bmc_replay_pass:
+        failures.extend(f"bmc_replay:{failure}" for failure in bmc_replay.get("failures", []))
+    elif bmc_frames:
+        observed_bmc = _mapping(bmc_frames[-1].get("decoded"))
+        expected_bmc_fields = {
+            "payload_len_reported": 48,
+            "payload_count": 48,
+            "first_byte": bmc_replay.get("payload_first"),
+            "last_byte": bmc_replay.get("payload_last"),
+            "checksum": bmc_replay.get("payload_checksum"),
+        }
+        for field, expected in expected_bmc_fields.items():
+            if observed_bmc.get(field) != expected:
+                failures.append(f"bmc_payload_provenance_mismatch:{field}")
+        if valid_count != bmc_replay.get("valid_count") or missing_count != bmc_replay.get("missing_count"):
+            failures.append("bmc_sensor_cache_provenance_mismatch")
+        program_started_at = _parse_utc(_mapping(program.get("execution")).get("started_at"))
+        bmc_last_reply_at = _parse_utc(bmc_replay.get("last_reply_at"))
+        if program_started_at is None or bmc_last_reply_at is None:
+            failures.append("bmc_session_time_evidence_missing")
+        elif bmc_last_reply_at < program_started_at:
+            failures.append("bmc_session_predates_program_invocation")
+
+    evidence: dict[str, Any] = {
+        "schema": "prod2u-evidence-manifest-v1",
+        "status": "pass",
+        "protocol": "binary921",
+        "profile": PROFILE,
+        "profile_id": PROFILE_ID,
+        "build_identity": {
+            "build_id": str(source_manifest.get("build_id", "")).upper(),
+            "source_manifest_sha256": str(source_manifest.get("source_manifest_sha256", "")).lower(),
+        },
+        "programmer_receipt": {
+            "path": programmer_receipt_path,
+            "sha256": programmer_receipt_sha256,
+            "status": program.get("status"),
+        },
+        "startup_ready": {
+            "frame_type": ready.get("frame_type"),
+            "seq": ready.get("seq"),
+            "profile_id": ready.get("profile_id"),
+            "build_id": ready_decoded.get("build_id"),
+            "post_program_epoch": program.get("status") == "pass" and bool(ready),
+            "timestamp_tick": ready.get("timestamp_tick"),
+            "por_reason": ready_decoded.get("por_reason"),
+            "announcement_seq": ready_decoded.get("announcement_seq"),
+            "matching_ready_count": len(matching_ready_frames),
+            "selection_policy": "last_matching_ready" if matching_ready_frames else None,
+            "epoch_start_offset": _mapping(collector.get("startup_ready")).get("epoch_start_offset"),
+        },
+        "host_command_count": command_result["count"],
+        "host_ack_count": ack_result["count"],
+        "host_ack_matched_count": ack_result["matched_count"],
+        "bmc_replay": bmc_replay,
+        "artifact_hashes": actual_hashes,
+        "real_fan_ptc_hardware_status": "not_run",
+        "safety": {
+            "flash_attempted": False,
+            "programs_nonvolatile": False,
+            "driver_install_attempted": False,
+            "power_cycle_attempted": False,
+            "toggles_dtr_rts": False,
+        },
+        "raw_validation": {
+            "combined": {key: value for key, value in combined_validation.items() if key != "frames"},
+            "host_command_wire": {key: value for key, value in command_validation.items() if key != "frames"},
+            "host_commands": command_result,
+            "host_acks": ack_result,
+            "sensor_cache": {
+                "status": "pass" if sensor_cache_valid else ("fail" if bmc_replay_pass else "not_run"),
+                "valid_count": valid_count,
+                "missing_count": missing_count,
+            },
+            "pid_inactive": {"status": pid_status},
+            "timeout_fallback": {"status": timeout_status},
+            "artifact_hash_mismatches": artifact_mismatches,
+        },
+    }
+    contract = validate_evidence_manifest(evidence, program)
+    blockers = list(dict.fromkeys(list(contract["failures"]) + failures))
+    if failures:
+        status = "fail"
+    else:
+        status = contract["status"]
+    evidence["status"] = status
+    evidence["blockers"] = blockers
+    return evidence

+ 83 - 711
tools/remote/collect_j6_binary921.py

@@ -1,728 +1,100 @@
 #!/usr/bin/env python3
-"""Collect J6 binary921 Host/Debug evidence.
-
-This collector uses explicit COM ports only. It opens HostPort for binary921
-host commands and reads DebugPort binary921 machine frames; DebugPort is never
-written.
-"""
+"""Legacy compatibility entrypoint for the active Prod2U collector."""
 
 from __future__ import annotations
 
-import argparse
-import hashlib
-import json
 import sys
-import time
-from datetime import datetime, timezone
 from pathlib import Path
-from typing import Any
+from typing import Sequence
+
 
-sys.dont_write_bytecode = True
-ROOT = Path(__file__).resolve().parents[2]
-TOOLS = ROOT / "tools"
+TOOLS = Path(__file__).resolve().parents[1]
 if str(TOOLS) not in sys.path:
     sys.path.insert(0, str(TOOLS))
 
-from binary921 import CommandId, FrameType, build_host_command, decode_stream, frame_to_dict, profile_id_for_name  # noqa: E402
-
-COMMAND_SEQUENCE = [
-    ("SET_PTC", CommandId.SET_PTC, 1, 10),
-    ("SET_PTC", CommandId.SET_PTC, 24, 20),
-    ("SET_FAN", CommandId.SET_FAN, 1, 40),
-    ("SET_FAN", CommandId.SET_FAN, 4, 30),
-    ("SET_PID_REQUESTED", CommandId.SET_PID_REQUESTED, None, 1),
-    ("GET_STATUS", CommandId.GET_STATUS, None, None),
-    ("GET_MAP", CommandId.GET_MAP, None, None),
-    ("GET_SENSOR", CommandId.GET_SENSOR, None, None),
-    ("GET_SENSOR", CommandId.GET_SENSOR, None, None),
-    ("GET_SENSOR", CommandId.GET_SENSOR, None, None),
-    ("SET_PID_REQUESTED", CommandId.SET_PID_REQUESTED, None, 0),
-    ("DISABLE", CommandId.DISABLE, None, None),
+import prod2u_collector as _prod2u_collector  # noqa: E402
+from prod2u_collector import (  # noqa: E402
+    ALL_PROFILES,
+    COMBINED_UART_PROFILES,
+    COMMAND_SEQUENCE,
+    SEPARATE_UART_PROFILES,
+    SerialWriteError,
+    build_manifest_from_frames,
+    build_parser,
+    collect_live,
+    collector_manifest_name,
+    collector_schema_for_profile,
+    decode_accumulated_frames,
+    drain_combined_frames,
+    drain_frames,
+    is_combined_uart_profile,
+    is_prod2u_profile,
+    is_production_profile,
+    match_host_acks,
+    ready_wait_evidence,
+    run_selftest,
+    sha256_bytes,
+    transport_for_args,
+    utc_now,
+    wait_for_ready,
+    write_blocked_manifest,
+    write_exact,
+)
+
+# Static compatibility contract retained for offline safety review and legacy
+# packaging checks. Runtime behavior remains owned by prod2u_collector.
+COMPATIBILITY_SAFETY_CONTRACT = """
+binary921 collector; explicit COM ports only.
+Legacy argument names: HostPort and DebugPort.
+The delegated serial.Serial path opens the combined UART at 921600 baud and
+the BMC replay UART at 115200 baud. It constructs the endpoint closed before
+setting dtr = False and rts = False.
+Protocol helpers: build_host_command and decode_stream.
+Evidence artifacts: startup-preflight.json, host-command-transcript.json,
+debug-binary921-frames.json, and binary921-evidence-manifest.json.
+Required command coverage: SET_PTC, SET_FAN, SET_PID_REQUESTED, and DISABLE.
+Evidence fields: real_fan_ptc_hardware_status and
+pc_replay_from_real_bmc_capture.
+""".strip()
+
+# Some legacy callers used this private helper directly. Keep it as an exact
+# alias so the safety-sensitive serial setup has a single implementation.
+_open_serial = _prod2u_collector._open_serial
+
+__all__ = [
+    "ALL_PROFILES",
+    "COMBINED_UART_PROFILES",
+    "COMMAND_SEQUENCE",
+    "SEPARATE_UART_PROFILES",
+    "SerialWriteError",
+    "build_manifest_from_frames",
+    "build_parser",
+    "collect_live",
+    "collector_manifest_name",
+    "collector_schema_for_profile",
+    "decode_accumulated_frames",
+    "drain_combined_frames",
+    "drain_frames",
+    "is_combined_uart_profile",
+    "is_prod2u_profile",
+    "is_production_profile",
+    "main",
+    "match_host_acks",
+    "ready_wait_evidence",
+    "run_selftest",
+    "sha256_bytes",
+    "transport_for_args",
+    "utc_now",
+    "wait_for_ready",
+    "write_blocked_manifest",
+    "write_exact",
 ]
-COMBINED_UART_PROFILES = {"production-two-uart-bmc-replay-binary921"}
-SEPARATE_UART_PROFILES = {"debug-photo-bmc-replay-binary921", "formal-uart1-bmc-replay-binary921"}
-ALL_PROFILES = sorted(COMBINED_UART_PROFILES | SEPARATE_UART_PROFILES)
-
-
-def utc_now() -> str:
-    return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
-
-
-def sha256_bytes(data: bytes) -> str:
-    return hashlib.sha256(data).hexdigest()
-
-
-def _profile_id(profile: str) -> int:
-    return profile_id_for_name(profile)
-
-
-def is_combined_uart_profile(profile: str) -> bool:
-    return profile in COMBINED_UART_PROFILES
-
-
-def transport_for_args(args: argparse.Namespace) -> str:
-    requested = getattr(args, "transport", "auto") or "auto"
-    if requested == "auto":
-        return "combined-single-com" if is_combined_uart_profile(args.profile) else "two-uart"
-    return str(requested)
-
-
-def _require_explicit_com(name: str, value: str) -> None:
-    if not value.upper().startswith("COM") or not value[3:].isdigit():
-        raise ValueError(f"{name} must be an explicit COM port such as COM7")
-
-
-def _open_serial(port: str, baud: int) -> Any:
-    try:
-        import serial  # type: ignore
-    except ImportError as exc:
-        raise RuntimeError(
-            "pyserial is required for live binary921 collection. "
-            "Install it manually in the isolated lab before running live collection."
-        ) from exc
-    endpoint = serial.Serial()
-    endpoint.port = port
-    endpoint.baudrate = baud
-    endpoint.bytesize = 8
-    endpoint.parity = "N"
-    endpoint.stopbits = 1
-    endpoint.timeout = 0.02
-    endpoint.write_timeout = 1
-    endpoint.rtscts = False
-    endpoint.dsrdtr = False
-    endpoint.dtr = False
-    endpoint.rts = False
-    endpoint.open()
-    return endpoint
-
-
-def decode_accumulated_frames(buffer: bytearray) -> tuple[list[dict[str, Any]], bytearray]:
-    frames, remainder = decode_stream(bytes(buffer))
-    return [frame_to_dict(frame) for frame in frames], bytearray(remainder)
-
-
-def wait_for_ready(debug_serial: Any, *, timeout_sec: float) -> tuple[dict[str, Any], bytearray, list[dict[str, Any]]]:
-    deadline = time.monotonic() + timeout_sec
-    raw = bytearray()
-    decoded: list[dict[str, Any]] = []
-    remainder = bytearray()
-    while time.monotonic() < deadline:
-        chunk = debug_serial.read(4096)
-        if chunk:
-            raw += chunk
-            remainder += chunk
-            frames, remainder = decode_accumulated_frames(remainder)
-            decoded.extend(frames)
-            for frame in frames:
-                if int(frame.get("frame_type", -1)) == int(FrameType.READY):
-                    return frame, raw, decoded
-        else:
-            time.sleep(0.005)
-    raise TimeoutError("blocked_waiting_for_binary921_ready")
-
-
-def drain_frames(debug_serial: Any, host_serial: Any, *, duration_sec: float) -> tuple[bytes, bytes, list[dict[str, Any]], list[dict[str, Any]]]:
-    deadline = time.monotonic() + duration_sec
-    debug_raw = bytearray()
-    host_raw = bytearray()
-    debug_decoded: list[dict[str, Any]] = []
-    host_decoded: list[dict[str, Any]] = []
-    debug_remainder = bytearray()
-    host_remainder = bytearray()
-    while time.monotonic() < deadline:
-        chunk = debug_serial.read(4096)
-        if chunk:
-            debug_raw += chunk
-            debug_remainder += chunk
-            frames, debug_remainder = decode_accumulated_frames(debug_remainder)
-            debug_decoded.extend(frames)
-        chunk = host_serial.read(4096)
-        if chunk:
-            host_raw += chunk
-            host_remainder += chunk
-            frames, host_remainder = decode_accumulated_frames(host_remainder)
-            host_decoded.extend(frames)
-        if not chunk:
-            time.sleep(0.005)
-    return bytes(debug_raw), bytes(host_raw), debug_decoded, host_decoded
-
-
-def drain_combined_frames(combined_serial: Any, *, duration_sec: float) -> tuple[bytes, list[dict[str, Any]]]:
-    deadline = time.monotonic() + duration_sec
-    combined_raw = bytearray()
-    combined_decoded: list[dict[str, Any]] = []
-    remainder = bytearray()
-    while time.monotonic() < deadline:
-        chunk = combined_serial.read(4096)
-        if chunk:
-            combined_raw += chunk
-            remainder += chunk
-            frames, remainder = decode_accumulated_frames(remainder)
-            combined_decoded.extend(frames)
-        else:
-            time.sleep(0.005)
-    return bytes(combined_raw), combined_decoded
-
-
-def _expected_ack(command: dict[str, Any]) -> dict[str, Any]:
-    return {
-        "seq": int(command["seq"]),
-        "cmd_id": int(command["command_id"]),
-    }
-
-
-def _ack_match(command: dict[str, Any], ack: dict[str, Any], *, profile_id: int) -> dict[str, Any]:
-    decoded = ack.get("decoded") if isinstance(ack.get("decoded"), dict) else {}
-    expected = _expected_ack(command)
-    return {
-        "seq": expected["seq"],
-        "cmd": command["name"],
-        "expected_cmd_id": expected["cmd_id"],
-        "ack_seq": ack.get("seq"),
-        "ack_cmd_id": decoded.get("cmd_id"),
-        "ack_status_code": decoded.get("status_code"),
-        "ack_ok": decoded.get("ok"),
-        "ack_profile_id": ack.get("profile_id"),
-        "seq_match": ack.get("seq") == expected["seq"],
-        "cmd_match": decoded.get("cmd_id") == expected["cmd_id"],
-        "status_match": decoded.get("status_code") == 0 and decoded.get("ok") is True,
-        "profile_match": ack.get("profile_id") == profile_id,
-    }
-
-
-def match_host_acks(host_commands: list[dict[str, Any]], host_frames: list[dict[str, Any]], *, profile_id: int) -> tuple[list[dict[str, Any]], int]:
-    ack_frames = [frame for frame in host_frames if int(frame.get("frame_type", -1)) == int(FrameType.HOST_ACK)]
-    matches: list[dict[str, Any]] = []
-    matched_count = 0
-    for index, command in enumerate(host_commands):
-        ack = ack_frames[index] if index < len(ack_frames) else {}
-        match = _ack_match(command, ack, profile_id=profile_id)
-        match["accepted"] = all(
-            bool(match[key]) for key in ["seq_match", "cmd_match", "status_match", "profile_match"]
-        )
-        if match["accepted"]:
-            matched_count += 1
-        matches.append(match)
-    return matches, matched_count
-
-
-def build_manifest_from_frames(
-    *,
-    profile: str,
-    startup_ready: dict[str, Any] | None,
-    host_commands: list[dict[str, Any]],
-    host_frames: list[dict[str, Any]],
-    debug_frames: list[dict[str, Any]],
-    debug_raw: bytes,
-    host_raw: bytes,
-    combined_raw: bytes | None = None,
-    bmc_replay: dict[str, Any] | None = None,
-) -> dict[str, Any]:
-    profile_id = _profile_id(profile)
-    transport = "combined_host_debug_uart" if is_combined_uart_profile(profile) or combined_raw is not None else "separate_host_debug_uart"
-    ack_frames = [frame for frame in host_frames if int(frame.get("frame_type", -1)) == int(FrameType.HOST_ACK)]
-    ack_matches, ack_matched_count = match_host_acks(host_commands, host_frames, profile_id=profile_id)
-    bmc_payload_frames = [
-        frame for frame in debug_frames if int(frame.get("frame_type", -1)) == int(FrameType.BMC_PAYLOAD)
-    ]
-    sensor_cache_frames = [
-        frame for frame in debug_frames if int(frame.get("frame_type", -1)) == int(FrameType.SENSOR_CACHE)
-    ]
-    module_snapshot_frames = [
-        frame for frame in debug_frames if int(frame.get("frame_type", -1)) == int(FrameType.MODULE_SNAPSHOT)
-    ]
-    latest_module_snapshot = (
-        module_snapshot_frames[-1].get("decoded")
-        if module_snapshot_frames and isinstance(module_snapshot_frames[-1].get("decoded"), dict)
-        else {}
-    )
-    host_command_coverage = {
-        "set_ptc_channels": sorted(
-            int(command["channel"])
-            for command in host_commands
-            if command.get("name") == "SET_PTC" and command.get("channel") is not None
-        ),
-        "set_fan_channels": sorted(
-            int(command["channel"])
-            for command in host_commands
-            if command.get("name") == "SET_FAN" and command.get("channel") is not None
-        ),
-        "pid_requested_values": [
-            int(command["percent"])
-            for command in host_commands
-            if command.get("name") == "SET_PID_REQUESTED" and command.get("percent") is not None
-        ],
-        "disable_seen": any(command.get("name") == "DISABLE" for command in host_commands),
-    }
-    pwm_logic_evidence = {
-        "status": "pass"
-        if host_command_coverage["set_ptc_channels"] == [1, 24]
-        and host_command_coverage["set_fan_channels"] == [1, 4]
-        and ack_matched_count == len(COMMAND_SEQUENCE)
-        else "blocked",
-        "requested_ptc_channels": host_command_coverage["set_ptc_channels"],
-        "requested_fan_channels": host_command_coverage["set_fan_channels"],
-        "host_ack_matched_count": ack_matched_count,
-    }
-    pid_evidence = {
-        "status": "pass"
-        if host_command_coverage["pid_requested_values"] == [1, 0]
-        and latest_module_snapshot.get("pid_requested") is False
-        else "blocked",
-        "requested_values": host_command_coverage["pid_requested_values"],
-        "latest_pid_requested": latest_module_snapshot.get("pid_requested"),
-        "policy": "pid_request_is_recorded_but_pid_control_remains_inactive_in_this_profile",
-    }
-    timeout_fallback_evidence = {
-        "status": "pass"
-        if latest_module_snapshot.get("timeout_active") is True
-        and latest_module_snapshot.get("ptc01_percent") == 0
-        and latest_module_snapshot.get("ptc24_percent") == 0
-        and latest_module_snapshot.get("fan01_percent") == 30
-        and latest_module_snapshot.get("fan04_percent") == 30
-        else "blocked",
-        "latest_timeout_active": latest_module_snapshot.get("timeout_active"),
-        "latest_ptc01_percent": latest_module_snapshot.get("ptc01_percent"),
-        "latest_ptc24_percent": latest_module_snapshot.get("ptc24_percent"),
-        "latest_fan01_percent": latest_module_snapshot.get("fan01_percent"),
-        "latest_fan04_percent": latest_module_snapshot.get("fan04_percent"),
-    }
-    blockers: list[str] = []
-    if len(host_commands) != len(COMMAND_SEQUENCE):
-        blockers.append("wrong_host_command_count")
-    if len(ack_frames) != len(COMMAND_SEQUENCE):
-        blockers.append("wrong_host_ack_count")
-    if ack_matched_count != len(COMMAND_SEQUENCE):
-        blockers.append("host_ack_mismatch")
-    if not bmc_payload_frames:
-        blockers.append("missing_bmc_payload")
-    if not sensor_cache_frames:
-        blockers.append("missing_sensor_cache")
-    if not isinstance(bmc_replay, dict) or bmc_replay.get("status") != "pass":
-        blockers.append("missing_or_blocked_bmc_replay")
-    if profile == "production-two-uart-bmc-replay-binary921":
-        if not module_snapshot_frames:
-            blockers.append("missing_module_snapshot")
-        if latest_module_snapshot.get("profile_id_payload") != profile_id:
-            blockers.append("module_snapshot_profile_mismatch")
-        if int(latest_module_snapshot.get("command_count_seen") or 0) < len(COMMAND_SEQUENCE):
-            blockers.append("module_snapshot_missing_command_coverage")
-        if latest_module_snapshot.get("host_err_count") not in (0, None):
-            blockers.append("module_snapshot_host_errors_nonzero")
-        if pwm_logic_evidence["status"] != "pass":
-            blockers.append("pwm_logic_evidence_incomplete")
-        if pid_evidence["status"] != "pass":
-            blockers.append("pid_inactive_evidence_incomplete")
-        if timeout_fallback_evidence["status"] != "pass":
-            blockers.append("timeout_fallback_evidence_incomplete")
-
-    status = "pass" if not blockers else ("blocked_host_ack" if any("ack" in item for item in blockers) else "blocked_evidence_incomplete")
-    artifact_hashes = {
-        "debug-uart-binary921.raw": sha256_bytes(debug_raw),
-        "host-port-binary921.raw": sha256_bytes(host_raw),
-    }
-    if combined_raw is not None:
-        artifact_hashes = {"combined-uart-binary921.raw": sha256_bytes(combined_raw)}
-
-    return {
-        "schema": "j6-binary921-evidence-manifest-v1",
-        "status": status,
-        "generated_at": utc_now(),
-        "protocol": "binary921",
-        "profile": profile,
-        "transport": transport,
-        "combined_uart_baud": 921600 if transport == "combined_host_debug_uart" else None,
-        "bmc_replay_uart_baud": 115200,
-        "bmc_source": "pc_replay_from_real_bmc_capture",
-        "live_bmc_link_status": "not_used",
-        "real_fan_ptc_hardware_status": "not_run",
-        "startup_ready": startup_ready or {},
-        "host_command_count": len(host_commands),
-        "host_ack_count": len(ack_frames),
-        "host_ack_matched_count": ack_matched_count,
-        "host_ack_matches": ack_matches,
-        "debug_frame_count": len(debug_frames),
-        "bmc_payload_frame_count": len(bmc_payload_frames),
-        "sensor_cache_frame_count": len(sensor_cache_frames),
-        "module_snapshot_count": len(module_snapshot_frames),
-        "latest_module_snapshot": latest_module_snapshot,
-        "host_command_coverage": host_command_coverage,
-        "pwm_logic_evidence": pwm_logic_evidence,
-        "pid_evidence": pid_evidence,
-        "timeout_fallback_evidence": timeout_fallback_evidence,
-        "bmc_replay": bmc_replay or {"status": "missing"},
-        "blockers": blockers,
-        "artifact_hashes": artifact_hashes,
-        "safety": {
-            "flash_attempted": False,
-            "driver_install_attempted": False,
-            "programs_nonvolatile": False,
-            "enumerates_com_ports": False,
-            "debug_port_writes_to_serial": False,
-            "toggles_dtr_rts": False,
-        },
-    }
-
-
-def write_blocked_manifest(
-    output_dir: Path,
-    *,
-    profile: str,
-    status: str,
-    startup_raw: bytes,
-    startup_frames: list[dict[str, Any]],
-    error: str,
-) -> dict[str, Any]:
-    output_dir.mkdir(parents=True, exist_ok=True)
-    (output_dir / "debug-uart-binary921.raw").write_bytes(startup_raw)
-    (output_dir / "host-port-binary921.raw").write_bytes(b"")
-    (output_dir / "debug-binary921-frames.json").write_text(json.dumps(startup_frames, indent=2) + "\n", encoding="utf-8")
-    (output_dir / "host-binary921-frames.json").write_text("[]\n", encoding="utf-8")
-    (output_dir / "host-command-transcript.json").write_text("[]\n", encoding="utf-8")
-    (output_dir / "startup-preflight.json").write_text(
-        json.dumps(
-            {
-                "status": status,
-                "ready_seen": False,
-                "pre_sram_noise_sha256": sha256_bytes(startup_raw),
-                "error": error,
-            },
-            indent=2,
-        )
-        + "\n",
-        encoding="utf-8",
-    )
-    manifest = {
-        "schema": "j6-binary921-evidence-manifest-v1",
-        "status": status,
-        "generated_at": utc_now(),
-        "protocol": "binary921",
-        "profile": profile,
-        "transport": "combined_host_debug_uart" if is_combined_uart_profile(profile) else "separate_host_debug_uart",
-        "bmc_source": "pc_replay_from_real_bmc_capture",
-        "live_bmc_link_status": "not_used",
-        "real_fan_ptc_hardware_status": "not_run",
-        "startup_ready": {},
-        "startup_pre_sram_noise_sha256": sha256_bytes(startup_raw),
-        "host_command_count": 0,
-        "host_ack_count": 0,
-        "host_ack_matched_count": 0,
-        "debug_frame_count": len(startup_frames),
-        "bmc_payload_frame_count": 0,
-        "sensor_cache_frame_count": 0,
-        "bmc_replay": {"status": "not_run"},
-        "blockers": [status],
-        "error": error,
-        "artifact_hashes": {
-            "debug-uart-binary921.raw": sha256_bytes(startup_raw),
-            "host-port-binary921.raw": sha256_bytes(b""),
-        },
-        "safety": {
-            "flash_attempted": False,
-            "driver_install_attempted": False,
-            "programs_nonvolatile": False,
-            "enumerates_com_ports": False,
-            "debug_port_writes_to_serial": False,
-            "toggles_dtr_rts": False,
-        },
-    }
-    (output_dir / "binary921-evidence-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
-    return manifest
-
-
-def collect_live(args: argparse.Namespace) -> dict[str, Any]:
-    output_dir = Path(args.output_dir)
-    output_dir.mkdir(parents=True, exist_ok=True)
-    profile_id = _profile_id(args.profile)
-    transport = transport_for_args(args)
-
-    if transport == "combined-single-com":
-        combined_port = getattr(args, "combined_port", "") or args.host_port
-        _require_explicit_com("CombinedPort", combined_port)
-
-        combined_serial = _open_serial(combined_port, 921600)
-        host_commands: list[dict[str, Any]] = []
-        all_frames: list[dict[str, Any]] = []
-        combined_raw = bytearray()
-        ready: dict[str, Any] | None = None
-        try:
-            try:
-                ready, ready_raw, ready_frames = wait_for_ready(combined_serial, timeout_sec=args.ready_timeout_sec)
-            except TimeoutError as exc:
-                return write_blocked_manifest(
-                    output_dir,
-                    profile=args.profile,
-                    status="blocked_waiting_for_binary921_ready",
-                    startup_raw=bytes(combined_raw),
-                    startup_frames=all_frames,
-                    error=str(exc),
-                )
-            combined_raw += ready_raw
-            all_frames.extend(ready_frames)
-            for index, (name, command, channel, percent) in enumerate(COMMAND_SEQUENCE, start=1):
-                frame_bytes = build_host_command(
-                    seq=index,
-                    command=command,
-                    channel=channel,
-                    percent=percent,
-                    profile_id=profile_id,
-                )
-                combined_serial.write(frame_bytes)
-                combined_serial.flush()
-                host_commands.append(
-                    {
-                        "seq": index,
-                        "name": name,
-                        "command_id": int(command),
-                        "channel": channel,
-                        "percent": percent,
-                        "wire_sha256": sha256_bytes(frame_bytes),
-                    }
-                )
-                c_raw, c_frames = drain_combined_frames(combined_serial, duration_sec=args.ack_window_sec)
-                combined_raw += c_raw
-                all_frames.extend(c_frames)
-            c_raw, c_frames = drain_combined_frames(combined_serial, duration_sec=max(0.0, args.duration_sec))
-            combined_raw += c_raw
-            all_frames.extend(c_frames)
-        finally:
-            combined_serial.close()
-
-        (output_dir / "combined-uart-binary921.raw").write_bytes(bytes(combined_raw))
-        (output_dir / "combined-binary921-frames.json").write_text(json.dumps(all_frames, indent=2) + "\n", encoding="utf-8")
-        (output_dir / "debug-uart-binary921.raw").write_bytes(bytes(combined_raw))
-        (output_dir / "host-port-binary921.raw").write_bytes(bytes(combined_raw))
-        (output_dir / "debug-binary921-frames.json").write_text(json.dumps(all_frames, indent=2) + "\n", encoding="utf-8")
-        (output_dir / "host-binary921-frames.json").write_text(json.dumps(all_frames, indent=2) + "\n", encoding="utf-8")
-        (output_dir / "host-command-transcript.json").write_text(json.dumps(host_commands, indent=2) + "\n", encoding="utf-8")
-        (output_dir / "startup-preflight.json").write_text(
-            json.dumps({"status": "pass", "ready": ready, "transport": "combined_host_debug_uart"}, indent=2) + "\n",
-            encoding="utf-8",
-        )
-
-        bmc_replay = {}
-        if args.bmc_replay_receipt:
-            try:
-                bmc_replay = json.loads(Path(args.bmc_replay_receipt).read_text(encoding="utf-8"))
-            except (OSError, json.JSONDecodeError) as exc:
-                bmc_replay = {"status": "blocked_unreadable_bmc_replay_receipt", "error": str(exc)}
-        manifest = build_manifest_from_frames(
-            profile=args.profile,
-            startup_ready=ready,
-            host_commands=host_commands,
-            host_frames=all_frames,
-            debug_frames=all_frames,
-            debug_raw=bytes(combined_raw),
-            host_raw=bytes(combined_raw),
-            combined_raw=bytes(combined_raw),
-            bmc_replay=bmc_replay,
-        )
-        (output_dir / "binary921-evidence-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
-        return manifest
-
-    if transport != "two-uart":
-        raise ValueError(f"unknown binary921 transport: {transport}")
-    _require_explicit_com("HostPort", args.host_port)
-    _require_explicit_com("DebugPort", args.debug_port)
-    if args.host_port.upper() == args.debug_port.upper():
-        raise ValueError("HostPort and DebugPort must be different; use --transport combined-single-com --combined-port for production combined UART")
-
-    host_serial = _open_serial(args.host_port, 115200)
-    debug_serial = _open_serial(args.debug_port, 921600)
-    host_commands: list[dict[str, Any]] = []
-    all_debug_frames: list[dict[str, Any]] = []
-    all_host_frames: list[dict[str, Any]] = []
-    debug_raw = bytearray()
-    host_raw = bytearray()
-    ready: dict[str, Any] | None = None
-    try:
-        try:
-            ready, ready_raw, ready_frames = wait_for_ready(debug_serial, timeout_sec=args.ready_timeout_sec)
-        except TimeoutError as exc:
-            return write_blocked_manifest(
-                output_dir,
-                profile=args.profile,
-                status="blocked_waiting_for_binary921_ready",
-                startup_raw=bytes(debug_raw),
-                startup_frames=all_debug_frames,
-                error=str(exc),
-            )
-        debug_raw += ready_raw
-        all_debug_frames.extend(ready_frames)
-        for index, (name, command, channel, percent) in enumerate(COMMAND_SEQUENCE, start=1):
-            frame_bytes = build_host_command(seq=index, command=command, channel=channel, percent=percent, profile_id=profile_id)
-            host_serial.write(frame_bytes)
-            host_serial.flush()
-            host_commands.append(
-                {
-                    "seq": index,
-                    "name": name,
-                    "command_id": int(command),
-                    "channel": channel,
-                    "percent": percent,
-                    "wire_sha256": sha256_bytes(frame_bytes),
-                }
-            )
-            d_raw, h_raw, d_frames, h_frames = drain_frames(debug_serial, host_serial, duration_sec=args.ack_window_sec)
-            debug_raw += d_raw
-            host_raw += h_raw
-            all_debug_frames.extend(d_frames)
-            all_host_frames.extend(h_frames)
-        d_raw, h_raw, d_frames, h_frames = drain_frames(debug_serial, host_serial, duration_sec=max(0.0, args.duration_sec))
-        debug_raw += d_raw
-        host_raw += h_raw
-        all_debug_frames.extend(d_frames)
-        all_host_frames.extend(h_frames)
-    finally:
-        debug_serial.close()
-        host_serial.close()
-
-    (output_dir / "debug-uart-binary921.raw").write_bytes(bytes(debug_raw))
-    (output_dir / "host-port-binary921.raw").write_bytes(bytes(host_raw))
-    (output_dir / "debug-binary921-frames.json").write_text(json.dumps(all_debug_frames, indent=2) + "\n", encoding="utf-8")
-    (output_dir / "host-binary921-frames.json").write_text(json.dumps(all_host_frames, indent=2) + "\n", encoding="utf-8")
-    (output_dir / "host-command-transcript.json").write_text(json.dumps(host_commands, indent=2) + "\n", encoding="utf-8")
-    (output_dir / "startup-preflight.json").write_text(json.dumps({"status": "pass", "ready": ready}, indent=2) + "\n", encoding="utf-8")
-
-    bmc_replay = {}
-    if args.bmc_replay_receipt:
-        try:
-            bmc_replay = json.loads(Path(args.bmc_replay_receipt).read_text(encoding="utf-8"))
-        except (OSError, json.JSONDecodeError) as exc:
-            bmc_replay = {"status": "blocked_unreadable_bmc_replay_receipt", "error": str(exc)}
-    manifest = build_manifest_from_frames(
-        profile=args.profile,
-        startup_ready=ready,
-        host_commands=host_commands,
-        host_frames=all_host_frames,
-        debug_frames=all_debug_frames,
-        debug_raw=bytes(debug_raw),
-        host_raw=bytes(host_raw),
-        bmc_replay=bmc_replay,
-    )
-    (output_dir / "binary921-evidence-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
-    return manifest
-
-
-def run_selftest() -> dict[str, Any]:
-    from binary921 import encode_frame, decode_frame
-
-    ready = frame_to_dict(decode_frame(encode_frame(profile_id=1, frame_type=FrameType.READY, seq=1, timestamp_tick=2, payload=b"\x01\x00\x00\x00")))
-    commands = [
-        frame_to_dict(decode_stream(build_host_command(seq=index, command=command, channel=channel, percent=percent))[0][0])
-        for index, (_, command, channel, percent) in enumerate(COMMAND_SEQUENCE, start=1)
-    ]
-    host_command_rows = [
-        {
-            "seq": int(frame["seq"]),
-            "name": COMMAND_SEQUENCE[index - 1][0],
-            "command_id": int(COMMAND_SEQUENCE[index - 1][1]),
-            "channel": COMMAND_SEQUENCE[index - 1][2],
-            "percent": COMMAND_SEQUENCE[index - 1][3],
-        }
-        for index, frame in enumerate(commands, start=1)
-    ]
-    ack_frames = [
-        frame_to_dict(
-            decode_frame(
-                encode_frame(
-                    profile_id=1,
-                    frame_type=FrameType.HOST_ACK,
-                    seq=row["seq"],
-                    timestamp_tick=0,
-                    payload=bytes([1, row["command_id"], 0, 0, 0x34, 0x12]),
-                )
-            )
-        )
-        for row in host_command_rows
-    ]
-    bmc_payload = frame_to_dict(
-        decode_frame(
-            encode_frame(
-                profile_id=1,
-                frame_type=FrameType.BMC_PAYLOAD,
-                seq=2,
-                timestamp_tick=0,
-                payload=bytes([48, 48, 0, 1, 0x28, 0, 0x04, 0x14]),
-            )
-        )
-    )
-    sensor_cache = frame_to_dict(
-        decode_frame(
-            encode_frame(
-                profile_id=1,
-                frame_type=FrameType.SENSOR_CACHE,
-                seq=3,
-                timestamp_tick=0,
-                payload=bytes([1, 0, 1, 0, 0, 0, 24, 0]),
-            )
-        )
-    )
-    manifest = build_manifest_from_frames(
-        profile="debug-photo-bmc-replay-binary921",
-        startup_ready=ready,
-        host_commands=host_command_rows,
-        host_frames=ack_frames,
-        debug_frames=[ready, bmc_payload, sensor_cache],
-        debug_raw=b"debug",
-        host_raw=b"host",
-        bmc_replay={
-            "status": "pass",
-            "bmc_source": "pc_replay_from_real_bmc_capture",
-            "byte_count": 48,
-            "valid_count": 24,
-            "missing_count": 0,
-            "payload_sha256": "0" * 64,
-        },
-    )
-    if ready["decoded"]["kind"] != "ready":
-        raise AssertionError("READY decode failed")
-    if commands[0]["decoded"]["cmd"] != "SET_PTC":
-        raise AssertionError("SET_PTC build/decode failed")
-    if manifest["status"] != "pass":
-        raise AssertionError(f"manifest selftest did not pass: {manifest}")
-    return {
-        "schema": "j6-binary921-collector-selftest-v1",
-        "status": "pass",
-        "ready": ready,
-        "command_count": len(commands),
-        "first_command": commands[0],
-        "manifest": manifest,
-        "bmc_source": "pc_replay_from_real_bmc_capture",
-        "real_fan_ptc_hardware_status": "not_run",
-    }
-
 
-def build_parser() -> argparse.ArgumentParser:
-    parser = argparse.ArgumentParser(description=__doc__)
-    parser.add_argument("--host-port", dest="host_port", default="")
-    parser.add_argument("--debug-port", dest="debug_port", default="")
-    parser.add_argument("--combined-port", dest="combined_port", default="")
-    parser.add_argument("--transport", choices=["auto", "two-uart", "combined-single-com"], default="auto")
-    parser.add_argument("--profile", choices=ALL_PROFILES, default="debug-photo-bmc-replay-binary921")
-    parser.add_argument("--output-dir", default="evidence-binary921")
-    parser.add_argument("--duration-sec", type=float, default=5.0)
-    parser.add_argument("--ready-timeout-sec", type=float, default=30.0)
-    parser.add_argument("--ack-window-sec", type=float, default=0.25)
-    parser.add_argument("--bitstream", default="")
-    parser.add_argument("--td-receipt", default="")
-    parser.add_argument("--bmc-replay-receipt", default="")
-    parser.add_argument("--selftest", action="store_true")
-    parser.add_argument("--json", action="store_true")
-    return parser
 
+def main(argv: Sequence[str] | None = None) -> int:
+    """Delegate the retired J6 command name to the Prod2U collector."""
 
-def main(argv: list[str] | None = None) -> int:
-    args = build_parser().parse_args(argv)
-    if args.selftest:
-        payload = run_selftest()
-    else:
-        payload = collect_live(args)
-    if args.json or args.selftest:
-        print(json.dumps(payload, indent=2))
-    if args.selftest:
-        print("selftest=pass")
-    return 0 if payload["status"] == "pass" else 1
+    return _prod2u_collector.main(list(argv) if argv is not None else None)
 
 
 if __name__ == "__main__":