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

refactor: retire legacy protocol implementation

Codex Resource Selftest 4 месяцев назад
Родитель
Сommit
02b0f2f1a0
97 измененных файлов с 27 добавлено и 20423 удалено
  1. 15 73
      README.zh-CN.md
  2. 0 120
      docs/prod2u-p4-normal-v3-runbook.zh-CN.md
  3. 0 22
      src/rtl/binary921_crc16.v
  4. 0 140
      src/rtl/binary921_frame_tx.v
  5. 0 125
      src/rtl/prod2u_p4_axis_executor.v
  6. 0 58
      src/rtl/prod2u_p4_motor_hub.v
  7. 0 446
      src/rtl/prod2u_p4_normal_v3_core.v
  8. 0 215
      src/rtl/prod2u_p4_normal_v3_output_state.v
  9. 0 256
      src/rtl/prod2u_p4_normal_v3_rx.v
  10. 0 134
      src/rtl/prod2u_p4_normal_v3_tx.v
  11. 0 68
      src/rtl/prod2u_p4_normal_v3_watchdog.v
  12. 0 80
      src/rtl/prod2u_p4_response_scheduler.v
  13. 0 149
      src/rtl/prod2u_p4_temperature_short_tx.v
  14. 0 199
      src/rtl/prod2u_p4_temperature_store.v
  15. 7 12
      tests/README.md
  16. 0 167
      tests/cocotb/prod2u_p4_ct7428_slave.v
  17. 0 96
      tests/cocotb/prod2u_p4_fast_jog_top.v
  18. 0 90
      tests/cocotb/prod2u_p4_normal_v3_ack_only_top.v
  19. 0 58
      tests/cocotb/run_prod2u_p4_fast_jog_top.py
  20. 0 64
      tests/cocotb/run_prod2u_p4_normal_v3_ack_only_top_e2e.py
  21. 0 241
      tests/cocotb/test_prod2u_p4_fast_jog_top.py
  22. 0 366
      tests/cocotb/test_prod2u_p4_normal_v3_ack_only_top_e2e.py
  23. 5 21
      tests/formal/README.md
  24. 0 21
      tests/formal/prod2u_p4_axis_cdc_structure.sby
  25. 0 36
      tests/formal/prod2u_p4_axis_cdc_structure_formal.v
  26. 0 21
      tests/formal/prod2u_p4_axis_force_jog_limit_ignore.sby
  27. 0 39
      tests/formal/prod2u_p4_axis_force_jog_limit_ignore_formal.v
  28. 0 21
      tests/formal/prod2u_p4_axis_force_jog_replace.sby
  29. 0 44
      tests/formal/prod2u_p4_axis_force_jog_replace_formal.v
  30. 0 21
      tests/formal/prod2u_p4_axis_safety.sby
  31. 0 169
      tests/formal/prod2u_p4_axis_safety_formal.v
  32. 0 27
      tests/formal/prod2u_p4_core_disable_motor_safety.sby
  33. 0 247
      tests/formal/prod2u_p4_core_disable_motor_safety_formal.v
  34. 0 27
      tests/formal/prod2u_p4_core_watchdog_race.sby
  35. 0 329
      tests/formal/prod2u_p4_core_watchdog_race_formal.v
  36. 0 48
      tests/formal/prod2u_p4_fast_jog_path.sby
  37. 0 627
      tests/formal/prod2u_p4_fast_jog_path_formal.v
  38. 0 33
      tests/formal/prod2u_p4_jog_no_gates.sby
  39. 0 72
      tests/formal/prod2u_p4_jog_no_gates_formal.v
  40. 0 43
      tests/formal/prod2u_p4_motor_hub_axis_isolation.sby
  41. 0 118
      tests/formal/prod2u_p4_motor_hub_axis_isolation_formal.v
  42. 0 23
      tests/formal/prod2u_p4_normal_v3_rx.sby
  43. 0 140
      tests/formal/prod2u_p4_normal_v3_rx_formal.v
  44. 0 15
      tests/formal/prod2u_p4_normal_v3_rx_payload.sby
  45. 0 151
      tests/formal/prod2u_p4_normal_v3_rx_payload_formal.v
  46. 0 14
      tests/formal/prod2u_p4_normal_v3_watchdog_contract.sby
  47. 0 83
      tests/formal/prod2u_p4_normal_v3_watchdog_contract_formal.v
  48. 0 23
      tests/formal/prod2u_p4_output_state.sby
  49. 0 82
      tests/formal/prod2u_p4_output_state_formal.v
  50. 0 21
      tests/formal/prod2u_p4_temperature_i2c_contract.sby
  51. 0 85
      tests/formal/prod2u_p4_temperature_i2c_contract_formal.v
  52. 0 21
      tests/formal/prod2u_p4_temperature_store_contract.sby
  53. 0 63
      tests/formal/prod2u_p4_temperature_store_contract_formal.v
  54. 0 24
      tests/formal/prod2u_p4_temperature_tx_contract.sby
  55. 0 101
      tests/formal/prod2u_p4_temperature_tx_contract_formal.v
  56. 0 318
      tests/sim/prod2u_p4_axis_force_jog_v1_tb.v
  57. 0 56
      tests/sim/prod2u_p4_axis_jog_16bit_tb.v
  58. 0 56
      tests/sim/prod2u_p4_cdc_sync_depth_tb.v
  59. 0 447
      tests/sim/prod2u_p4_completion_ack_contract_tb.v
  60. 0 255
      tests/sim/prod2u_p4_core_watchdog_refresh_tb.v
  61. 0 365
      tests/sim/prod2u_p4_fast_jog_core_tb.v
  62. 0 215
      tests/sim/prod2u_p4_i2c_stop_start_read_tb.v
  63. 0 82
      tests/sim/prod2u_p4_jog_no_gates_contract_tb.v
  64. 0 236
      tests/sim/prod2u_p4_minimal_snapshot_contract_tb.v
  65. 0 165
      tests/sim/prod2u_p4_motor_hub_axis_isolation_tb.v
  66. 0 62
      tests/sim/prod2u_p4_motor_status_payload_tb.v
  67. 0 327
      tests/sim/prod2u_p4_normal_v3_rx_fast_jog_tb.v
  68. 0 530
      tests/sim/prod2u_p4_normal_v3_rx_tb.v
  69. 0 114
      tests/sim/prod2u_p4_normal_v3_tx_tb.v
  70. 0 110
      tests/sim/prod2u_p4_normal_v3_watchdog_contract_tb.v
  71. 0 86
      tests/sim/prod2u_p4_production_defaults_tb.v
  72. 0 216
      tests/sim/prod2u_p4_temperature_core_integration_tb.v
  73. 0 230
      tests/sim/prod2u_p4_temperature_short_tx_tb.v
  74. 0 260
      tests/sim/prod2u_p4_temperature_top_integration_tb.v
  75. 0 201
      tests/sim/uart_8n1_phy_tb.v
  76. 0 94
      tests/sim/uart_rx_back_to_back_tb.v
  77. 0 206
      tests/unit/test_prod2u_p4_ack_only_host_contract.py
  78. 0 304
      tests/unit/test_prod2u_p4_activate_verification_toolchain.py
  79. 0 294
      tests/unit/test_prod2u_p4_cli_v3.py
  80. 0 393
      tests/unit/test_prod2u_p4_fast_jog_contract.py
  81. 0 61
      tests/unit/test_prod2u_p4_fast_jog_rx_contract.py
  82. 0 1559
      tests/unit/test_prod2u_p4_harness.py
  83. 0 1383
      tests/unit/test_prod2u_p4_minimal_delivery_contract.py
  84. 0 67
      tests/unit/test_prod2u_p4_minimal_snapshot_contract_rtl.py
  85. 0 655
      tests/unit/test_prod2u_p4_motion_source_mutations.py
  86. 0 403
      tests/unit/test_prod2u_p4_normal_v3_model.py
  87. 0 69
      tests/unit/test_prod2u_p4_output_storage_structure.py
  88. 0 153
      tests/unit/test_prod2u_p4_parallel_offline_gate.py
  89. 0 394
      tests/unit/test_prod2u_p4_protocol_v3.py
  90. 0 142
      tests/unit/test_prod2u_p4_retirement_contract.py
  91. 0 383
      tests/unit/test_prod2u_p4_send_hex_template.py
  92. 0 176
      tests/unit/test_prod2u_p4_td_cdc_structure.py
  93. 0 200
      tests/unit/test_prod2u_p4_temperature_contract.py
  94. 0 88
      tests/unit/test_prod2u_p4_wrapper_v3.py
  95. 0 751
      tools/prod2u_p4_cli.py
  96. 0 1699
      tools/prod2u_p4_normal_v3_model.py
  97. 0 629
      tools/prod2u_p4_protocol.py

+ 15 - 73
README.zh-CN.md

@@ -1,85 +1,27 @@
-# Prod2U Profile 4 Normal v3
+# Prod2U Door Temp CPLD
 
-本仓库构建一个 binary921-v3、921600 baud 的 CPLD 生产镜像,保留 PTC、FAN、solenoid、X/Y 电机、LS1/LS2 物理引脚、非电机输出 watchdog 和 SRAM 编程支持。
+本仓库只实现 `prod2u-door-temp` 新架构:25 MHz、115200 8N1、无流控,统一帧为 `A5 5A type length payload CRC16_LE`。
 
-当前极简运动合同:
+正式类型只有:
 
-- X/Y 可独立并行运动,`DIR=0` 打开、`DIR=1` 关闭。
-- 只有 `0x35 JOG` 能驱动电机;legacy 标准 OPEN/CLOSE 只修改 Snapshot 的兼容字段,不产生 STEP。
-- Snapshot 的 X/Y/Z 字段允许任意 `u8`,但全部忽略且没有电机作用。
-- JOG 保持 `1..65535` 请求字段;超过 800 步的请求也会完整执行,两个方向都忽略限位。
-- 合法 X/Y JOG 永不返回 BUSY。ACK 在首个实际 STEP 上升沿已经发出后返回,但不表示整段运动完成。
-- CPLD 按 `RAW_U16_TRUSTED_HOST_NO_CPLD_CAP` 原样加载 16 位步数;RX 按 `RX_FAST_JOG_BYPASSES_NORMAL_REQUEST_SLOT` 让合法 JOG 绕过普通请求槽和响应阻塞。完成由上位机计时,同轴完成前不得重发。
-- 同轴新 JOG 立即拉低旧 STEP、丢弃旧剩余步数并重新等待 1 ms DIR setup;X/Y 互不阻塞。
-- `busy_mask`、`fault_mask` 和 `position_valid_mask` 恒为 0,current/target 恒为 `0xFF`。
-- DISABLE、watchdog 和 LS 都不会停止电机;异常时必须断电、复位或重新配置 CPLD。
-- LS1/X=`B9`、LS2/Y=`A11`,A5 不使用。
-- 版本号统一使用 8 位小写 Git SHA,不在设备运行时发送额外身份帧。
+- `0x01 SET_ALL`:24 路 PTC、4 路 FAN、进风门方向、出风门方向;无回复。
+- `0x02 GET_TEMPERATURE`:无 payload;完成 27 项读取后只回复一个 `0x82` 温度帧。
+- `0x82 TEMPERATURE_DATA`:27 字节 payload,总帧长 33 字节。
 
-## 离线验证
+两台马达严格串行,先进风门后出风门,每台固定 450 步;无限位、ACK、ERROR、BUSY、JOG、STOP、watchdog、replay 或旧协议兼容。
 
-```powershell
-Set-Location 'C:\Users\Administrator\CodexTemp\p4-normal-v1-no-gates-73df4ee'
-$verificationRunId = [Guid]::NewGuid().ToString('N').ToLowerInvariant()
-python tools\prod2u_p4_harness.py p4-normal-v3-strict-offline-gate `
-  --work-root C:\Users\Administrator\CodexTemp\p4-normal-v3-minimal-offline `
-  --verification-run-id $verificationRunId `
-  --json `
-  --report-file C:\Users\Administrator\CodexTemp\p4-normal-v3-minimal-offline\receipt.json
-```
-
-## TD 构建
-
-必须从 clean commit 构建;两次确认构建使用两个仓外目录:
-
-```powershell
-python tools\prod2u_p4_harness.py td-build --run --top prod2u_p4_normal_v3 `
-  --work-root C:\Users\Administrator\CodexTemp\p4-normal-v3-minimal-td-a `
-  --verification-run-id $verificationRunId `
-  --json `
-  --report-file C:\Users\Administrator\CodexTemp\p4-normal-v3-minimal-td-a\receipt.json
+权威协议和项目事实见 `CPLD_多项目_UART协议_项目适配_Codex并行Harness_详细设计_v1.0.md`、`projects/prod2u-door-temp/project.json` 和 `docs/prod2u-door-temp-protocol.zh-CN.md`。
 
-python tools\prod2u_p4_harness.py td-build --run --top prod2u_p4_normal_v3 `
-  --work-root C:\Users\Administrator\CodexTemp\p4-normal-v3-minimal-td-b `
-  --verification-run-id $verificationRunId `
-  --json `
-  --report-file C:\Users\Administrator\CodexTemp\p4-normal-v3-minimal-td-b\receipt.json
-```
-
-TD 记录 `BRAM`、`DSP`、`IO`、setup/hold 和全部失败。只要路由数据库可用就继续尝试 bitgen;验证失败不伪装成通过,也不阻止非空 bitstream 的临时包交付。
-
-## 打包
+## Offline verification
 
 ```powershell
-powershell.exe -NoProfile -ExecutionPolicy Bypass `
-  -File tools\package_prod2u_p4_normal_v3.ps1 `
-  -OutputDir C:\Users\Administrator\CodexTemp\p4-normal-images `
-  -NormalBitstream '<td-bitgen-path>\prod2u_p4_normal_v3.bit' `
-  -TdReceipt '<td-a-path>\receipt.json' `
-  -VerificationRunId $verificationRunId `
-  -ConfirmationTdReceipt '<td-b-path>\receipt.json' `
-  -ValidationReceipt '<strict-offline-path>\receipt.json'
-
-$commit = (git rev-parse --short=8 HEAD).Trim().ToLowerInvariant()
-$bitstreamSha256 = (Get-FileHash -Algorithm SHA256 '<td-bitgen-path>\prod2u_p4_normal_v3.bit').Hash.ToLowerInvariant()
-$packageDir = "C:\Users\Administrator\CodexTemp\p4-normal-images\$commit\prod2u-p4-normal-$commit-$($bitstreamSha256.Substring(0, 16))"
-
-python tools\prod2u_p4_harness.py package-selftest `
-  --package-dir $packageDir `
-  --verification-run-id $verificationRunId `
-  --report-file C:\Users\Administrator\CodexTemp\p4-normal-v3-package-selftest-receipt.json
-
-python tools\prod2u_p4_harness.py p4-normal-v3-final-gate `
-  --offline-receipt C:\Users\Administrator\CodexTemp\p4-normal-v3-minimal-offline\receipt.json `
-  --td-receipt C:\Users\Administrator\CodexTemp\p4-normal-v3-minimal-td-a\receipt.json `
-  --confirmation-td-receipt C:\Users\Administrator\CodexTemp\p4-normal-v3-minimal-td-b\receipt.json `
-  --package-receipt C:\Users\Administrator\CodexTemp\p4-normal-v3-package-selftest-receipt.json `
-  --verification-run-id $verificationRunId `
-  --report-file C:\Users\Administrator\CodexTemp\p4-normal-v3-final-gate-v3-receipt.json
+python tools\prod2u_p4_harness.py hdl-sim --backend icarus --run --work-root <work-root>
+python tools\prod2u_p4_harness.py hdl-sim --backend verilator --run --work-root <work-root>
+python tools\prod2u_p4_harness.py formal --run --work-root <work-root>
 ```
 
-输出固定为 `C:\Users\Administrator\CodexTemp\p4-normal-images\<8位小写SHA>\prod2u-p4-normal-<8位小写SHA>-<bitstream-sha256前16位>`。包内包含两份 TD receipt/报告、验证矩阵、包自检结果、SRAM 脚本、初始化 DISABLE、通用 HEX 发送方法以及兼容 Snapshot 和 JOG 的冻结 HEX。
+目标只从 `config/prod2u_p4_verification_targets_v1.json` 读取。缺少工具或未完成的层必须标记 `blocked`/`not_run`,不得升级为通过。
 
-strict offline、两次 TD、打包自检和 final gate 必须显式使用同一个 32 位小写十六进制 `verification_run_id`。最终 normal dual-TD 交付只接受两份独立 TD receipt 的 bitstream SHA-256 完全相同;run ID、位流或包内验证 receipt 任一不一致都会 fail closed。
+## TD and hardware boundary
 
-仓库构建和打包不会连接串口或 JTAG,也不会执行 SRAM/Flash 操作。详细风险与实板步骤见 [运行手册](docs/prod2u-p4-normal-v3-runbook.zh-CN.md)。
+TD 入口是 `td/prod2u_p4_normal_v3.prj` 及同名脚本。构建只生成 bitstream 和 receipt,不打开 COM/JTAG、不烧录、不安装驱动、不修改全局 PATH,也不执行真实热闭环。

+ 0 - 120
docs/prod2u-p4-normal-v3-runbook.zh-CN.md

@@ -1,120 +0,0 @@
-# Prod2U Profile 4 Normal v3 V1 强制 JOG 临时刷机包
-
-## 固件合同
-
-- 上位机输入仍使用 binary921-v3、Profile ID 4、921600 baud、8N1。
-- X/Y 是独立执行器,可以同时运动;`DIR=0` 为打开,`DIR=1` 为关闭。
-- X/Y 的 STEP 和 DIR 独立,板上共享 `motor_en_n` 恒为低电平使能;MOTION_STATUS 的 EN active 恒为 1。
-- 只有 `0x35 JOG` 能驱动电机。Snapshot 中原有 X/Y/Z 字节和旧 OPEN/CLOSE CLI 线格式仍保留,但任意 `0..255` 值都被忽略,不产生 STEP。
-- JOG 步数策略为 `RAW_U16_TRUSTED_HOST_NO_CPLD_CAP`:字段保持原始 16 位,CPLD 不检查、钳位或修正;上位机构造器必须保证 `steps=1..65535`。超过 800 步的请求也会完整执行,不再截断。
-- `speed_code=0..3` 的 speed 字段仍会校验,但执行时忽略该值,四个值的实际速度都固定为 1000 step/s。
-- 快速路径策略为 `RX_FAST_JOG_BYPASSES_NORMAL_REQUEST_SLOT`。合法 X/Y JOG 永不返回 BUSY,也不受普通请求槽、core 状态、旧响应、TX 停顿、snapshot、LS、watchdog timeout 或 DISABLE 阻止。ACK 在该命令首个实际 STEP 上升沿已经发出后才返回,不表示整段运动完成。
-- 两个方向 JOG 都忽略限位。LS1/X=B9、LS2/Y=A11 只保留物理引脚,没有同步、滤波或 RTL 消费者。
-- LS1/X 使用 B9,LS2/Y 使用 A11;`0V=未触发`,`3.3V=关闭端触发`。A5 不使用。
-- 同轴新 JOG 会立即把旧 STEP 拉低并丢弃旧剩余步数,然后重新等待完整 1 ms DIR setup;旧 STEP 高脉冲允许被截短。X/Y 可独立重载并重叠运行。
-- 上位机必须遵守 `HOST_MUST_NOT_REPEAT_SAME_AXIS_BEFORE_COMPLETION`,并自行根据步数和固定 1 kHz 波形判断每轴完成。违规重发采用 `LATEST_COMMAND_WINS_OLD_ACK_NOT_GUARANTEED`;下位机没有完成事件(`NONE_HOST_TRACKS_TIME`),只保留一个快速 ACK 记录。
-- `busy_mask`、`fault_mask`、`position_valid_mask` 是恒为 0 的只读遥测,current/target 恒为 `0xFF`;这些字段不再表示运动进度或位置。
-- Snapshot 的合法 PTC/FAN/solenoid 总是提交并返回 OK,result_flags 只有 bit0 为 1;X/Y/Z 对应的轴位全部为 0。
-- watchdog 仍保护非电机输出,但 JOG 不 arm 或 refresh watchdog。watchdog 到期和 DISABLE 都不会停止、暂停或改变电机;只能通过复位、断电或重新配置停止。
-- 合法 JOG 无需先发送 DISABLE。GET_STATUS 和 GET_MOTOR_STATUS 都不能复活、暂停或停止电机运动。
-- 固件不保存限位位置,不自动学习方向,不提供 MARK_CLOSED、恢复步数、永久锁定或开端保护。
-
-固件不提供电机位置、完成进度或机械端点确认。
-
-## 按需读取温度
-
-- 唯一合法请求是 `A55A020405000000000000000004280000009E0C`,payload 为 `28 00 00 00`。
-- 成功时不先返回 HOST_ACK,只返回 35 字节短帧:`A5 5A 02 04 10 1B`、27 个温度字节、CRC 低字节、CRC 高字节。CRC-16/CCITT-FALSE 覆盖 `02 04 10 1B` 和 27 个温度字节。
-- 读取顺序固定为 U6(`0x49`) -> U24(`0x48`) -> U25(`0x4B`);每颗依次读取寄存器 `0x00..0x08`,输出顺序为每颗 local、remote1..8。
-- 上电不足一秒时不访问 I2C,直接返回 27 个 `FF`:`A55A0204101BFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF1BC4`。
-- 当前项 NACK 时该项写 `FF` 并继续;线路卡低、超时或其他无法继续的总线错误返回标准 HOST_ACK,status=`0x0A`,下一次请求从 U6/`0x00` 重新开始。
-- `SEND_HEX.ps1` 目前只解析标准 HOST_ACK 和 GET_MOTOR_STATUS 的后续标准帧,不能用于判定成功的 35 字节温度短帧。发送 `0x28` 时应使用能按上述长度和 CRC 解析短帧的上位机工具。
-
-## 离线检查
-
-从 clean commit 开始先生成一个 32 位小写十六进制 `verification_run_id`,并把同一个值传给 strict offline、两次独立 TD、打包器、package selftest 和 final gate。不得混用同一 commit 的不同批次 receipt。两份 TD 必须来自不同仓外 work-root 和不同 TD `run_id`,但 synthesis manifest、synthesis input hash 与 bitstream SHA-256 必须完全相同;任一不一致都不是可交付的 normal dual-TD 包。
-
-在包目录执行:
-
-```powershell
-Set-Location '<package-path>'
-powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\selftest.ps1
-```
-
-该命令只检查包内文件和 SHA-256,不打开串口、不访问 JTAG。
-
-## SRAM 编程
-
-编程脚本只发起一次 SRAM 下载,频率固定 200 kHz,不含自动重试和 Flash 操作:
-
-```powershell
-Set-Location '<package-path>'
-powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\PROGRAM_SRAM.ps1 -Confirm PROGRAM_SRAM
-```
-
-脚本若发现 TD 或 BitWriter 进程已经运行会直接停止,且不会自动结束这些进程。编程成功后立即执行初始化 DISABLE;该命令只初始化非电机输出,不具备电机停机作用:
-
-```powershell
-powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\INITIALIZE_DISABLE.ps1 -Port COM5
-```
-
-## 直接发送 HEX
-
-通用入口:
-
-```powershell
-powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\SEND_HEX.ps1 -Port COM5 -Hex '<HEX>'
-```
-
-发送器要求普通命令恰好返回一个匹配命令且成功的 HOST_ACK;GET_MOTOR_STATUS 必须恰好返回 HOST_ACK 后紧跟一个 10 字节 MOTION_STATUS。错误 ACK、缺帧、多帧、乱序、长度或 CRC 错误都会失败,且不会自动重试命令。
-
-| 功能 | HEX |
-|---|---|
-| GET_STATUS | `A55A02040500000000000000000424000000AC43` |
-| DISABLE | `A55A02040500000000000000000426000000C4AE` |
-| GET_MOTOR_STATUS | `A55A0204110000000000000000083700000000000000347F` |
-| 全输出关闭;legacy XYZ=0(无电机作用) | `A55A0204070000000000000000222A0000000000000000000000000000000000000000000000000000000000000000005528` |
-| FAN 1..4=30%;legacy XYZ=0(无电机作用) | `A55A0204070000000000000000222A000000000000000000000000000000000000000000000000001E1E1E1E00000000D6DF` |
-| PTC1=10%,FAN 1..4=30%;legacy XYZ=0 | `A55A0204070000000000000000222A000A00000000000000000000000000000000000000000000001E1E1E1E000000002887` |
-| 仅 FAN3=30%;legacy XYZ=0 | `A55A0204070000000000000000222A0000000000000000000000000000000000000000000000000000001E000000000072B2` |
-| solenoid=100,FAN 1..4=30%;legacy XYZ=0 | `A55A0204070000000000000000222A000000000000000000000000000000000000000000000000001E1E1E1E64000000F54C` |
-| 全输出关闭;legacy X/Y=100(仍无电机作用) | `A55A0204070000000000000000222A00000000000000000000000000000000000000000000000000000000000064640010A8` |
-| FAN 1..4=30%;legacy X=100/Y=0(无电机作用) | `A55A0204070000000000000000222A000000000000000000000000000000000000000000000000001E1E1E1E006400007D98` |
-| FAN 1..4=30%;legacy X=0/Y=100(无电机作用) | `A55A0204070000000000000000222A000000000000000000000000000000000000000000000000001E1E1E1E000064003818` |
-| X JOG 打开,speed=3,1 步 | `A55A0204110000000000000000083500000301000000F468` |
-| X JOG 关闭,speed=3,1 步 | `A55A0204110000000000000000083500010301000000542D` |
-| Y JOG 打开,speed=3,1 步 | `A55A020411000000000000000008350100030100000095D0` |
-| Y JOG 关闭,speed=3,1 步 | `A55A02041100000000000000000835010103010000003595` |
-| X JOG 打开,speed=3,800 步 | `A55A02041100000000000000000835000003200300005E70` |
-| X JOG 关闭,speed=3,800 步 | `A55A0204110000000000000000083500010320030000FE35` |
-| Y JOG 打开,speed=3,800 步 | `A55A02041100000000000000000835010003200300003FC8` |
-| Y JOG 关闭,speed=3,800 步 | `A55A02041100000000000000000835010103200300009F8D` |
-| X JOG 打开,speed=3,65535 步 | `A55A02041100000000000000000835000003FFFF0000809A` |
-| X JOG 关闭,speed=3,65535 步 | `A55A02041100000000000000000835000103FFFF000020DF` |
-| Y JOG 打开,speed=3,65535 步 | `A55A02041100000000000000000835010003FFFF0000E122` |
-| Y JOG 关闭,speed=3,65535 步 | `A55A02041100000000000000000835010103FFFF00004167` |
-| 旧 `0x29` 请求,固定返回 UNSUPPORTED | `A55A020405000000000000000004290000002A7A` |
-| 旧 MARK_CLOSED X/DIR0,固定返回 UNSUPPORTED | `A55A0204110000000000000000083600000000000000E738` |
-
-JOG payload 为 `35 axis dir speed steps_le16 0000`。`axis=0/1` 分别为 X/Y,`dir=0/1` 分别为打开/关闭;speed `0/1/2/3` 都执行 1 ms 完整步周期。表中 65535 步会实际执行 65535 步。ACK 超时只覆盖首 STEP 启动,不按总步数推导完成时间;修改字段后必须重新计算 CRC,不能只替换表格 HEX 中的字节。
-
-请求帧和 HEX 不变。`axis` 非 X/Y、非法方向或速度、保留字段非零等错误在普通请求槽可用时返回 BAD_VALUE;`steps=0` 是上位机合同违规,CPLD 不为其定义运动或响应语义。合法 JOG 不会返回 BUSY。
-
-### X ACK 后启动 Y
-
-以下示例先启动 X 打开 800 步。`SEND_HEX.ps1` 收到并校验 X 的 HOST_ACK 后才退出;确认第一条命令成功返回 HOST_ACK,再执行第二条启动 Y。X/Y 执行器彼此独立,因此两段运动可以重叠。
-
-```powershell
-powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\SEND_HEX.ps1 -Port COM5 -Baud 921600 -Hex 'A55A02041100000000000000000835000003200300005E70'
-# Wait for the matching X HOST_ACK before sending Y.
-powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\SEND_HEX.ps1 -Port COM5 -Baud 921600 -Hex 'A55A02041100000000000000000835010003200300003FC8'
-```
-
-## 已接受风险
-
-- legacy 标准 OPEN/CLOSE 命令不会驱动电机,必须使用 JOG。
-- JOG 完全忽略限位,单条最多实际执行 65535 步,可直接造成严重机械越程。
-- 同轴新 JOG 会截短旧 STEP 并立即覆盖旧剩余距离;ACK 只证明首个新 STEP 已发出。
-- DISABLE、watchdog、失联和 LS 都不能停止电机;异常时必须立即断电或复位/重新配置。
-- 固件不检测堵转、失步、限位卡低、相线接反或机械方向错误。
-- 本包生成和离线验证不等于实板机械验收。任何异常应立即断电;不得自动再次编程。

+ 0 - 22
src/rtl/binary921_crc16.v

@@ -1,22 +0,0 @@
-`timescale 1ns/1ps
-
-module binary921_crc16 (
-    input  wire [15:0] crc_in,
-    input  wire [7:0]  data,
-    output reg  [15:0] crc_out
-);
-    reg [15:0] crc;
-    integer i;
-
-    always @* begin
-        crc = crc_in ^ {data, 8'h00};
-        for (i = 0; i < 8; i = i + 1) begin
-            if (crc[15]) begin
-                crc = (crc << 1) ^ 16'h1021;
-            end else begin
-                crc = (crc << 1);
-            end
-        end
-        crc_out = crc;
-    end
-endmodule

+ 0 - 140
src/rtl/binary921_frame_tx.v

@@ -1,140 +0,0 @@
-`timescale 1ns/1ps
-
-module binary921_frame_tx #(
-    parameter integer MAX_PAYLOAD_BYTES = 64,
-    parameter integer LATCH_PAYLOAD = 1,
-    parameter [7:0] VERSION = 8'h01
-) (
-    input  wire                         clk,
-    input  wire                         rst_n,
-    input  wire                         start,
-    input  wire [7:0]                   profile_id,
-    input  wire [7:0]                   frame_type,
-    input  wire [31:0]                  frame_seq,
-    input  wire [31:0]                  timestamp_tick,
-    input  wire [7:0]                   payload_len,
-    input  wire [(MAX_PAYLOAD_BYTES*8)-1:0] payload,
-    output reg                          busy,
-    output reg                          done,
-    output reg                          tx_valid,
-    output reg  [7:0]                   tx_data,
-    input  wire                         tx_ready
-);
-    localparam [7:0] MAGIC0 = 8'ha5;
-    localparam [7:0] MAGIC1 = 8'h5a;
-    reg [7:0] byte_index;
-    reg [7:0] total_bytes;
-    reg [15:0] crc;
-    wire [15:0] crc_next;
-    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),
-        .data(tx_data),
-        .crc_out(crc_next)
-    );
-
-    function [7:0] payload_byte;
-        input [7:0] index;
-        begin
-            if (LATCH_PAYLOAD != 0) begin
-                payload_byte = latched_payload[(index * 8) +: 8];
-            end else begin
-                payload_byte = payload[(index * 8) +: 8];
-            end
-        end
-    endfunction
-
-    always @* begin
-        crc_after_accept = crc;
-        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;
-        case (next_byte_index)
-            8'd0: next_send_byte = MAGIC0;
-            8'd1: next_send_byte = MAGIC1;
-            8'd2: next_send_byte = VERSION;
-            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 + latched_payload_len)) begin
-                    next_send_byte = payload_byte(next_byte_index - 8'd14);
-                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];
-                end
-            end
-        endcase
-    end
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            busy <= 1'b0;
-            done <= 1'b0;
-            tx_valid <= 1'b0;
-            tx_data <= 8'd0;
-            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
-                busy <= 1'b1;
-                byte_index <= 8'd0;
-                total_bytes <= 8'd16 + payload_len;
-                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 + latched_payload_len)) begin
-                    crc <= crc_next;
-                end
-                if (byte_index == total_bytes - 8'd1) begin
-                    busy <= 1'b0;
-                    done <= 1'b1;
-                    tx_valid <= 1'b0;
-                    byte_index <= 8'd0;
-                end else begin
-                    byte_index <= byte_index + 8'd1;
-                    tx_valid <= 1'b1;
-                    tx_data <= next_send_byte;
-                end
-            end else if (busy) begin
-                tx_valid <= 1'b1;
-            end else begin
-                tx_valid <= 1'b0;
-            end
-        end
-    end
-endmodule

+ 0 - 125
src/rtl/prod2u_p4_axis_executor.v

@@ -1,125 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_axis_executor #(
-    parameter integer DIR_SETUP_CYCLES = 25000,
-    parameter integer STEP_HALF_CYCLES = 12500
-) (
-    input  wire        clk,
-    input  wire        rst_n,
-    input  wire        command_start,
-    input  wire        command_dir,
-    input  wire [15:0] command_steps,
-    output wire        step_out,
-    output wire        dir_out,
-    output reg         started_pulse
-`ifdef FORMAL
-    , output wire [1:0]  formal_motion_phase
-    , output wire [31:0] formal_phase_counter
-    , output wire [15:0] formal_remaining_steps
-`endif
-);
-    localparam [1:0] PHASE_IDLE = 2'd0;
-    localparam [1:0] PHASE_DIR_SETUP = 2'd1;
-    localparam [1:0] PHASE_STEP_HIGH = 2'd2;
-    localparam [1:0] PHASE_STEP_LOW = 2'd3;
-
-    localparam integer MAX_PHASE_CYCLES =
-        (DIR_SETUP_CYCLES > STEP_HALF_CYCLES) ?
-        DIR_SETUP_CYCLES : STEP_HALF_CYCLES;
-    localparam integer PHASE_COUNTER_BITS =
-        (MAX_PHASE_CYCLES <= 1) ? 1 : $clog2(MAX_PHASE_CYCLES);
-    localparam [31:0] DIR_SETUP_LAST_32 = DIR_SETUP_CYCLES - 1;
-    localparam [31:0] STEP_HALF_LAST_32 = STEP_HALF_CYCLES - 1;
-    localparam [PHASE_COUNTER_BITS-1:0] DIR_SETUP_LAST =
-        DIR_SETUP_LAST_32[PHASE_COUNTER_BITS-1:0];
-    localparam [PHASE_COUNTER_BITS-1:0] STEP_HALF_LAST =
-        STEP_HALF_LAST_32[PHASE_COUNTER_BITS-1:0];
-
-    (* keep = "true", syn_encoding = "sequential", fsm_encoding = "none" *)
-    reg [1:0] motion_phase;
-    reg dir_reg;
-    reg [15:0] remaining_steps;
-    reg [PHASE_COUNTER_BITS-1:0] phase_counter;
-
-    assign step_out = (motion_phase == PHASE_STEP_HIGH);
-    assign dir_out = dir_reg;
-`ifdef FORMAL
-    assign formal_motion_phase = motion_phase;
-    assign formal_phase_counter = {{(32-PHASE_COUNTER_BITS){1'b0}}, phase_counter};
-    assign formal_remaining_steps = remaining_steps;
-`endif
-
-    generate
-        if ((DIR_SETUP_CYCLES < 1) || (STEP_HALF_CYCLES < 1)) begin : g_invalid_motion_period
-            prod2u_p4_axis_motion_period_must_be_positive u_motion_period_error();
-        end
-    endgenerate
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            motion_phase <= PHASE_IDLE;
-            dir_reg <= 1'b0;
-            remaining_steps <= 16'd0;
-            phase_counter <= {PHASE_COUNTER_BITS{1'b0}};
-            started_pulse <= 1'b0;
-        end else begin
-            started_pulse <= 1'b0;
-
-            // A new command always wins. This intentionally lowers STEP on
-            // the acceptance edge, discards the old distance, and restarts
-            // the complete DIR setup interval.
-            if (command_start) begin
-                dir_reg <= command_dir;
-                remaining_steps <= command_steps;
-                motion_phase <= PHASE_DIR_SETUP;
-                phase_counter <= DIR_SETUP_LAST;
-            end else begin
-                case (motion_phase)
-                    PHASE_IDLE: begin
-                        remaining_steps <= 16'd0;
-                        phase_counter <= {PHASE_COUNTER_BITS{1'b0}};
-                    end
-
-                    PHASE_DIR_SETUP: begin
-                        if (phase_counter != {PHASE_COUNTER_BITS{1'b0}}) begin
-                            phase_counter <= phase_counter - 1'b1;
-                        end else begin
-                            motion_phase <= PHASE_STEP_HIGH;
-                            phase_counter <= STEP_HALF_LAST;
-                            started_pulse <= 1'b1;
-                        end
-                    end
-
-                    PHASE_STEP_HIGH: begin
-                        if (phase_counter != {PHASE_COUNTER_BITS{1'b0}}) begin
-                            phase_counter <= phase_counter - 1'b1;
-                        end else begin
-                            motion_phase <= PHASE_STEP_LOW;
-                            phase_counter <= STEP_HALF_LAST;
-                        end
-                    end
-
-                    PHASE_STEP_LOW: begin
-                        if (phase_counter != {PHASE_COUNTER_BITS{1'b0}}) begin
-                            phase_counter <= phase_counter - 1'b1;
-                        end else if (remaining_steps == 16'd1) begin
-                            motion_phase <= PHASE_IDLE;
-                            remaining_steps <= 16'd0;
-                            phase_counter <= {PHASE_COUNTER_BITS{1'b0}};
-                        end else begin
-                            motion_phase <= PHASE_STEP_HIGH;
-                            remaining_steps <= remaining_steps - 16'd1;
-                            phase_counter <= STEP_HALF_LAST;
-                        end
-                    end
-
-                    default: begin
-                        motion_phase <= PHASE_IDLE;
-                        remaining_steps <= 16'd0;
-                        phase_counter <= {PHASE_COUNTER_BITS{1'b0}};
-                    end
-                endcase
-            end
-        end
-    end
-endmodule

+ 0 - 58
src/rtl/prod2u_p4_motor_hub.v

@@ -1,58 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_motor_hub #(
-    parameter integer DIR_SETUP_CYCLES = 25000,
-    parameter integer STEP_HALF_CYCLES = 12500
-) (
-    input  wire        clk,
-    input  wire        rst_n,
-    input  wire        jog_start,
-    input  wire [1:0]  jog_axis,
-    input  wire        jog_dir,
-    input  wire [15:0] jog_steps,
-    output wire [1:0]  axis_started_pulse,
-    output wire [2:0]  step_out,
-    output wire [2:0]  dir_out
-);
-    wire x_step;
-    wire y_step;
-    wire x_dir;
-    wire y_dir;
-    wire x_started_pulse;
-    wire y_started_pulse;
-
-    wire x_command_start = jog_start && (jog_axis == 2'd0);
-    wire y_command_start = jog_start && (jog_axis == 2'd1);
-
-    assign axis_started_pulse = {y_started_pulse, x_started_pulse};
-    assign step_out = {1'b0, y_step, x_step};
-    assign dir_out = {1'b0, y_dir, x_dir};
-
-    prod2u_p4_axis_executor #(
-        .DIR_SETUP_CYCLES(DIR_SETUP_CYCLES),
-        .STEP_HALF_CYCLES(STEP_HALF_CYCLES)
-    ) u_x_axis (
-        .clk(clk),
-        .rst_n(rst_n),
-        .command_start(x_command_start),
-        .command_dir(jog_dir),
-        .command_steps(jog_steps),
-        .step_out(x_step),
-        .dir_out(x_dir),
-        .started_pulse(x_started_pulse)
-    );
-
-    prod2u_p4_axis_executor #(
-        .DIR_SETUP_CYCLES(DIR_SETUP_CYCLES),
-        .STEP_HALF_CYCLES(STEP_HALF_CYCLES)
-    ) u_y_axis (
-        .clk(clk),
-        .rst_n(rst_n),
-        .command_start(y_command_start),
-        .command_dir(jog_dir),
-        .command_steps(jog_steps),
-        .step_out(y_step),
-        .dir_out(y_dir),
-        .started_pulse(y_started_pulse)
-    );
-endmodule

+ 0 - 446
src/rtl/prod2u_p4_normal_v3_core.v

@@ -1,446 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_normal_v3_core #(
-    parameter integer CLK_HZ = 25000000,
-    parameter integer WATCHDOG_SECONDS = 5,
-    parameter integer DIR_SETUP_CYCLES = 25000,
-    parameter integer STEP_HALF_CYCLES = 12500
-) (
-    input  wire         clk,
-    input  wire         rst_n,
-    input  wire         request_valid,
-    output wire         request_ready,
-    input  wire [7:0]   request_type,
-    input  wire [5:0]   request_length,
-    input  wire [271:0] request_payload,
-    input  wire [15:0]  request_crc16,
-    input  wire         fast_jog_valid,
-    input  wire [1:0]   fast_jog_axis,
-    input  wire         fast_jog_dir,
-    input  wire [15:0]  fast_jog_steps,
-    input  wire         powerup_ready,
-    output reg          temperature_read_start,
-    input  wire         temperature_read_done,
-    input  wire         temperature_bus_error,
-    output reg          temperature_tx_start,
-    output reg          temperature_tx_force_ff,
-    input  wire         temperature_tx_done,
-    output wire         frame_valid,
-    input  wire         frame_ready,
-    output wire [7:0]   frame_type,
-    output wire [7:0]   frame_payload_len,
-    output wire [143:0] frame_payload,
-    output wire [191:0] ptc_percent,
-    output wire [31:0]  fan_percent,
-    output wire [7:0]   solenoid_percent,
-    output wire [15:0]  state_hash16,
-    output wire [2:0]   step_out,
-    output wire [2:0]   dir_out,
-    output wire         en_n,
-    output wire         disabled,
-    output wire         watchdog_timeout
-`ifdef FORMAL
-    , output wire [2:0] formal_state
-`endif
-);
-    localparam [7:0] FT_HOST_CMD = 8'h05;
-    localparam [7:0] FT_HOST_BATCH_CMD = 8'h07;
-    localparam [7:0] FT_MOTION_CMD = 8'h11;
-    localparam [7:0] FT_MOTION_STATUS = 8'h12;
-
-    localparam [7:0] CMD_GET_STATUS = 8'h24;
-    localparam [7:0] CMD_DISABLE = 8'h26;
-    localparam [7:0] CMD_GET_TEMPERATURES = 8'h28;
-    localparam [7:0] CMD_SET_SNAPSHOT = 8'h2a;
-    localparam [7:0] MOTION_JOG = 8'h35;
-    localparam [7:0] MOTION_MARK_CLOSED = 8'h36;
-    localparam [7:0] MOTION_GET_STATUS = 8'h37;
-
-    localparam [7:0] STATUS_OK = 8'h00;
-    localparam [7:0] STATUS_UNSUPPORTED = 8'h01;
-    localparam [7:0] STATUS_BAD_FLAGS = 8'h02;
-    localparam [7:0] STATUS_BAD_LENGTH = 8'h03;
-    localparam [7:0] STATUS_BAD_VALUE = 8'h05;
-    localparam [7:0] STATUS_TEMP_BUS = 8'h0a;
-
-    localparam [2:0] ST_IDLE = 3'd0;
-    localparam [2:0] ST_SNAPSHOT_VALIDATE = 3'd1;
-    localparam [2:0] ST_SNAPSHOT_COMMIT = 3'd2;
-    localparam [2:0] ST_DISABLE_WAIT = 3'd3;
-    localparam [2:0] ST_TEMP_READ_WAIT = 3'd4;
-    localparam [2:0] ST_TEMP_TX_WAIT = 3'd5;
-
-    (* keep = "true", syn_encoding = "sequential", fsm_encoding = "none" *)
-    reg [2:0] state;
-`ifdef FORMAL
-    assign formal_state = state;
-`endif
-    wire command_accept = request_valid && request_ready;
-    wire [7:0] request_command = request_payload[7:0];
-    wire [7:0] request_channel = request_payload[15:8];
-    wire [7:0] request_value = request_payload[23:16];
-    wire [7:0] request_flags = request_payload[31:24];
-    wire host_zeros_valid = (request_channel == 8'd0) &&
-        (request_value == 8'd0) && (request_flags == 8'd0);
-    wire motor_status_payload_valid = (request_payload[63:8] == 56'd0);
-
-    reg snapshot_scan_start;
-    reg snapshot_commit_authorize;
-    reg [271:0] snapshot_payload_latched;
-    wire snapshot_ready;
-    wire snapshot_output_result_valid;
-    wire snapshot_output_accepted;
-    wire snapshot_commit_pulse;
-
-    wire [1:0] motor_axis_started_pulse;
-    reg fast_jog_ack_pending;
-    reg fast_jog_ack_ready;
-    reg [1:0] fast_jog_ack_axis;
-    reg [63:0] fast_jog_ack_payload;
-    wire fast_jog_started =
-        ((fast_jog_ack_axis == 2'd0) && motor_axis_started_pulse[0]) ||
-        ((fast_jog_ack_axis == 2'd1) && motor_axis_started_pulse[1]);
-    wire [63:0] fast_jog_ok_payload = {
-        8'd0, 8'd0, state_hash16[15:8], state_hash16[7:0],
-        8'd0, STATUS_OK, MOTION_JOG, 8'h01
-    };
-
-    reg watchdog_disable;
-    reg watchdog_snapshot_arm;
-    /* verilator lint_off UNUSEDSIGNAL */
-    wire watchdog_armed;
-    /* verilator lint_on UNUSEDSIGNAL */
-    wire watchdog_force_safe;
-    wire watchdog_expiry_due;
-    // The non-motor output watchdog measures host-command silence. Any
-    // complete command accepted by the normal path, or any CRC-valid fast
-    // JOG event, proves that the host is still communicating.
-    wire watchdog_command_refresh = command_accept || fast_jog_valid;
-    wire [7:0] motion_status_flags = {
-        4'd0, watchdog_timeout, disabled, 1'b1, 1'b0
-    };
-    wire [79:0] unknown_motion_status = {
-        8'd0, 48'hffffffffffff, 16'd0, motion_status_flags
-    };
-
-    reg command_inflight;
-    reg command_response_valid;
-    reg [63:0] command_ack_payload;
-    reg command_followup_valid;
-    reg [7:0] command_followup_frame_type;
-    reg [79:0] command_followup_payload;
-    wire response_command_done;
-    wire response_frame_valid;
-    wire [7:0] response_frame_type;
-    wire [7:0] response_payload_len;
-    wire [143:0] response_payload;
-
-    assign request_ready = (state == ST_IDLE) && !command_inflight &&
-        !fast_jog_ack_pending && !fast_jog_ack_ready &&
-        (!request_valid || (request_type != FT_HOST_BATCH_CMD) ||
-         (request_length != 6'd34) || snapshot_ready);
-    assign frame_valid = response_frame_valid;
-    assign frame_type = response_frame_type;
-    assign frame_payload_len = response_payload_len;
-    assign frame_payload = response_payload;
-    assign en_n = 1'b0;
-
-    task queue_response;
-        input response_ok;
-        input [7:0] response_command;
-        input [7:0] response_status;
-        input [7:0] response_detail;
-        input [15:0] response_hash;
-        input [7:0] response_type;
-        input [7:0] response_flags;
-        input response_has_followup;
-        input [79:0] response_followup;
-        begin
-            command_ack_payload <= {
-                response_flags,
-                response_type,
-                response_hash[15:8],
-                response_hash[7:0],
-                response_detail,
-                response_status,
-                response_command,
-                {7'd0, response_ok}
-            };
-            command_followup_valid <= response_has_followup;
-            command_followup_frame_type <= response_type;
-            command_followup_payload <= response_followup;
-            command_response_valid <= 1'b1;
-        end
-    endtask
-
-    prod2u_p4_normal_v3_output_state u_outputs (
-        .clk(clk),
-        .rst_n(rst_n),
-        .force_safe(watchdog_force_safe),
-        .snapshot_valid(snapshot_scan_start),
-        .snapshot_ready(snapshot_ready),
-        .snapshot_payload(snapshot_payload_latched),
-        .commit_authorize(snapshot_commit_authorize),
-        .result_valid(snapshot_output_result_valid),
-        .result_accepted(snapshot_output_accepted),
-        .commit_pulse(snapshot_commit_pulse),
-        .ptc_percent(ptc_percent),
-        .fan_percent(fan_percent),
-        .solenoid_percent(solenoid_percent),
-        .state_hash16(state_hash16)
-    );
-
-    prod2u_p4_normal_v3_watchdog #(
-        .CLK_HZ(CLK_HZ),
-        .WATCHDOG_SECONDS(WATCHDOG_SECONDS)
-    ) u_watchdog (
-        .clk(clk),
-        .rst_n(rst_n),
-        .arm(watchdog_snapshot_arm),
-        .refresh(watchdog_command_refresh),
-        .disable_cmd(watchdog_disable),
-        .disabled(disabled),
-        .armed(watchdog_armed),
-        .watchdog_timeout(watchdog_timeout),
-        .expiry_due(watchdog_expiry_due),
-        .force_safe(watchdog_force_safe)
-    );
-
-    prod2u_p4_motor_hub #(
-        .DIR_SETUP_CYCLES(DIR_SETUP_CYCLES),
-        .STEP_HALF_CYCLES(STEP_HALF_CYCLES)
-    ) u_motors (
-        .clk(clk),
-        .rst_n(rst_n),
-        .jog_start(fast_jog_valid),
-        .jog_axis(fast_jog_axis),
-        .jog_dir(fast_jog_dir),
-        .jog_steps(fast_jog_steps),
-        .axis_started_pulse(motor_axis_started_pulse),
-        .step_out(step_out),
-        .dir_out(dir_out)
-    );
-
-    prod2u_p4_response_scheduler u_response_scheduler (
-        .clk(clk),
-        .rst_n(rst_n),
-        .command_valid(command_response_valid),
-        .command_ack_payload(command_ack_payload),
-        .followup_valid(command_followup_valid),
-        .followup_frame_type(command_followup_frame_type),
-        .followup_payload(command_followup_payload),
-        .command_done(response_command_done),
-        .tx_valid(response_frame_valid),
-        .tx_ready(frame_ready),
-        .tx_frame_type(response_frame_type),
-        .tx_payload_len(response_payload_len),
-        .tx_payload(response_payload)
-    );
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            state <= ST_IDLE;
-            snapshot_scan_start <= 1'b0;
-            snapshot_commit_authorize <= 1'b0;
-            snapshot_payload_latched <= 272'd0;
-            fast_jog_ack_pending <= 1'b0;
-            fast_jog_ack_ready <= 1'b0;
-            fast_jog_ack_axis <= 2'd0;
-            fast_jog_ack_payload <= 64'd0;
-            watchdog_disable <= 1'b0;
-            watchdog_snapshot_arm <= 1'b0;
-            temperature_read_start <= 1'b0;
-            temperature_tx_start <= 1'b0;
-            temperature_tx_force_ff <= 1'b0;
-            command_inflight <= 1'b0;
-            command_response_valid <= 1'b0;
-            command_ack_payload <= 64'd0;
-            command_followup_valid <= 1'b0;
-            command_followup_frame_type <= 8'd0;
-            command_followup_payload <= 80'd0;
-        end else begin
-            snapshot_scan_start <= 1'b0;
-            snapshot_commit_authorize <= 1'b0;
-            watchdog_disable <= 1'b0;
-            watchdog_snapshot_arm <= 1'b0;
-            temperature_read_start <= 1'b0;
-            temperature_tx_start <= 1'b0;
-            temperature_tx_force_ff <= 1'b0;
-
-            if (fast_jog_valid) begin
-                fast_jog_ack_pending <= 1'b1;
-                fast_jog_ack_ready <= 1'b0;
-                fast_jog_ack_axis <= fast_jog_axis;
-            end else if (fast_jog_ack_pending && fast_jog_started) begin
-                fast_jog_ack_pending <= 1'b0;
-                fast_jog_ack_ready <= 1'b1;
-                fast_jog_ack_payload <= fast_jog_ok_payload;
-            end
-
-            if (response_command_done) begin
-                command_inflight <= 1'b0;
-                command_response_valid <= 1'b0;
-                command_followup_valid <= 1'b0;
-            end
-
-            case (state)
-                ST_IDLE: begin
-                    if (!response_command_done && !fast_jog_valid &&
-                        !command_inflight && fast_jog_ack_ready) begin
-                        command_inflight <= 1'b1;
-                        command_ack_payload <= fast_jog_ack_payload;
-                        command_followup_valid <= 1'b0;
-                        command_followup_frame_type <= 8'd0;
-                        command_followup_payload <= 80'd0;
-                        command_response_valid <= 1'b1;
-                        fast_jog_ack_ready <= 1'b0;
-                    end else if (command_accept) begin
-                        command_inflight <= 1'b1;
-                        command_response_valid <= 1'b0;
-                        command_followup_valid <= 1'b0;
-
-                        if (request_type == FT_HOST_BATCH_CMD) begin
-                            if (request_length != 6'd34) begin
-                                queue_response(1'b0, request_command,
-                                    STATUS_BAD_LENGTH, 8'd0, state_hash16,
-                                    8'd0, 8'd0, 1'b0, 80'd0);
-                            end else begin
-                                snapshot_payload_latched <= request_payload;
-                                snapshot_scan_start <= 1'b1;
-                                state <= ST_SNAPSHOT_VALIDATE;
-                            end
-                        end else if (request_type == FT_HOST_CMD) begin
-                            if (request_length != 6'd4) begin
-                                queue_response(1'b0, request_command,
-                                    STATUS_BAD_LENGTH, 8'd0, state_hash16,
-                                    8'd0, 8'd0, 1'b0, 80'd0);
-                            end else if (request_flags != 8'd0) begin
-                                queue_response(1'b0, request_command,
-                                    STATUS_BAD_FLAGS, 8'd0, state_hash16,
-                                    8'd0, 8'd0, 1'b0, 80'd0);
-                            end else if (!host_zeros_valid) begin
-                                queue_response(1'b0, request_command,
-                                    STATUS_BAD_VALUE, 8'd0, state_hash16,
-                                    8'd0, 8'd0, 1'b0, 80'd0);
-                            end else if (request_command == CMD_GET_STATUS) begin
-                                queue_response(1'b1, CMD_GET_STATUS, STATUS_OK,
-                                    {6'd0, watchdog_timeout, disabled},
-                                    state_hash16, 8'd0, 8'd0, 1'b0, 80'd0);
-                            end else if (request_command == CMD_DISABLE) begin
-                                watchdog_disable <= 1'b1;
-                                state <= ST_DISABLE_WAIT;
-                            end else if (request_command == CMD_GET_TEMPERATURES) begin
-                                if (powerup_ready) begin
-                                    temperature_read_start <= 1'b1;
-                                    state <= ST_TEMP_READ_WAIT;
-                                end else begin
-                                    temperature_tx_start <= 1'b1;
-                                    temperature_tx_force_ff <= 1'b1;
-                                    state <= ST_TEMP_TX_WAIT;
-                                end
-                            end else begin
-                                queue_response(1'b0, request_command,
-                                    STATUS_UNSUPPORTED, 8'd0, state_hash16,
-                                    8'd0, 8'd0, 1'b0, 80'd0);
-                            end
-                        end else if (request_type == FT_MOTION_CMD) begin
-                            if (request_length != 6'd8) begin
-                                queue_response(1'b0, request_command,
-                                    STATUS_BAD_LENGTH, 8'd0, state_hash16,
-                                    8'd0, 8'd0, 1'b0, 80'd0);
-                            end else if (request_command == MOTION_JOG) begin
-                                queue_response(1'b0, MOTION_JOG,
-                                    STATUS_BAD_VALUE, 8'd0, state_hash16,
-                                    8'd0, 8'd0, 1'b0, 80'd0);
-                            end else if (request_command == MOTION_MARK_CLOSED) begin
-                                queue_response(1'b0, MOTION_MARK_CLOSED,
-                                    STATUS_UNSUPPORTED, 8'd0, state_hash16,
-                                    8'd0, 8'd0, 1'b0, 80'd0);
-                            end else if (request_command == MOTION_GET_STATUS) begin
-                                if (!motor_status_payload_valid) begin
-                                    queue_response(1'b0, MOTION_GET_STATUS,
-                                        STATUS_BAD_VALUE, 8'd0, state_hash16,
-                                        8'd0, 8'd0, 1'b0, 80'd0);
-                                end else begin
-                                    queue_response(1'b1, MOTION_GET_STATUS,
-                                        STATUS_OK, 8'd0, state_hash16,
-                                        FT_MOTION_STATUS, 8'h08, 1'b1,
-                                        unknown_motion_status);
-                                end
-                            end else begin
-                                queue_response(1'b0, request_command,
-                                    STATUS_UNSUPPORTED, 8'd0, state_hash16,
-                                    8'd0, 8'd0, 1'b0, 80'd0);
-                            end
-                        end else begin
-                            queue_response(1'b0, request_command,
-                                STATUS_UNSUPPORTED, 8'd0, state_hash16,
-                                8'd0, 8'd0, 1'b0, 80'd0);
-                        end
-                    end
-                end
-
-                ST_SNAPSHOT_VALIDATE: begin
-                    if (snapshot_output_result_valid) begin
-                        if (snapshot_output_accepted) begin
-                            snapshot_commit_authorize <= 1'b1;
-                            state <= ST_SNAPSHOT_COMMIT;
-                        end else begin
-                            queue_response(1'b0, CMD_SET_SNAPSHOT,
-                                STATUS_BAD_VALUE, 8'd0, state_hash16,
-                                8'd0, 8'd0, 1'b0, 80'd0);
-                            state <= ST_IDLE;
-                        end
-                    end
-                end
-
-                ST_SNAPSHOT_COMMIT: begin
-                    if (snapshot_commit_pulse) begin
-                        watchdog_snapshot_arm <= 1'b1;
-                        queue_response(1'b1, CMD_SET_SNAPSHOT, STATUS_OK,
-                            8'd0, state_hash16, 8'd0, 8'h01,
-                            1'b0, 80'd0);
-                        state <= ST_IDLE;
-                    end
-                end
-
-                ST_DISABLE_WAIT: begin
-                    if (disabled && (ptc_percent == 192'd0) &&
-                        (fan_percent == {4{8'd30}}) &&
-                        (solenoid_percent == 8'd0)) begin
-                        queue_response(1'b1, CMD_DISABLE, STATUS_OK,
-                            {6'd0, watchdog_timeout, disabled},
-                            state_hash16, 8'd0, 8'd0, 1'b0, 80'd0);
-                        state <= ST_IDLE;
-                    end
-                end
-
-                ST_TEMP_READ_WAIT: begin
-                    if (temperature_read_done) begin
-                        if (temperature_bus_error) begin
-                            queue_response(1'b0, CMD_GET_TEMPERATURES,
-                                STATUS_TEMP_BUS, 8'd0, state_hash16,
-                                8'd0, 8'd0, 1'b0, 80'd0);
-                            state <= ST_IDLE;
-                        end else begin
-                            temperature_tx_start <= 1'b1;
-                            temperature_tx_force_ff <= 1'b0;
-                            state <= ST_TEMP_TX_WAIT;
-                        end
-                    end
-                end
-
-                ST_TEMP_TX_WAIT: begin
-                    if (temperature_tx_done) begin
-                        command_inflight <= 1'b0;
-                        state <= ST_IDLE;
-                    end
-                end
-
-                default: state <= ST_IDLE;
-            endcase
-        end
-    end
-
-    wire unused = ^request_crc16 ^ watchdog_expiry_due;
-endmodule

+ 0 - 215
src/rtl/prod2u_p4_normal_v3_output_state.v

@@ -1,215 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_normal_v3_output_state (
-    input  wire         clk,
-    input  wire         rst_n,
-    input  wire         force_safe,
-    input  wire         snapshot_valid,
-    output wire         snapshot_ready,
-    input  wire [271:0] snapshot_payload,
-    input  wire         commit_authorize,
-    output reg          result_valid,
-    output reg          result_accepted,
-    output reg          commit_pulse,
-    output wire [191:0] ptc_percent,
-    output wire [31:0]  fan_percent,
-    output wire [7:0]   solenoid_percent,
-    output reg  [15:0]  state_hash16
-);
-    localparam [15:0] SAFE_STATE_HASH16 = 16'he177;
-    localparam [1:0] RAIL_INVALID = 2'b00;
-    localparam [1:0] RAIL_ZERO = 2'b01;
-    localparam [1:0] RAIL_HUNDRED = 2'b10;
-
-    reg scan_busy;
-    reg candidate_pending;
-    reg [4:0] scan_index;
-    reg invalid_seen;
-    reg [15:0] candidate_hash;
-    reg [167:0] ptc_percent_7;
-    reg [27:0] fan_percent_7;
-    reg [1:0] solenoid_rail;
-    reg [167:0] candidate_ptc_7;
-    reg [27:0] candidate_fan_7;
-    reg [1:0] candidate_solenoid_rail;
-    reg [7:0] scan_byte;
-    wire scan_byte_invalid;
-    wire [15:0] candidate_hash_next;
-    integer i;
-    genvar output_index;
-
-    function [1:0] encode_binary_rail;
-        input [7:0] value;
-        begin
-            case (value)
-                8'd0: encode_binary_rail = RAIL_ZERO;
-                8'd100: encode_binary_rail = RAIL_HUNDRED;
-                default: encode_binary_rail = RAIL_INVALID;
-            endcase
-        end
-    endfunction
-
-    function [7:0] decode_binary_rail;
-        input [1:0] rail;
-        begin
-            decode_binary_rail = (rail == RAIL_HUNDRED) ? 8'd100 : 8'd0;
-        end
-    endfunction
-
-    assign snapshot_ready = !scan_busy && !candidate_pending;
-    assign solenoid_percent = decode_binary_rail(solenoid_rail);
-    assign scan_byte_invalid = (scan_index <= 5'd29) && (scan_byte > 8'd100);
-
-    always @(*) begin
-        case (scan_index)
-            5'd2: scan_byte = {1'b0, candidate_ptc_7[0 +: 7]};
-            5'd3: scan_byte = {1'b0, candidate_ptc_7[7 +: 7]};
-            5'd4: scan_byte = {1'b0, candidate_ptc_7[14 +: 7]};
-            5'd5: scan_byte = {1'b0, candidate_ptc_7[21 +: 7]};
-            5'd6: scan_byte = {1'b0, candidate_ptc_7[28 +: 7]};
-            5'd7: scan_byte = {1'b0, candidate_ptc_7[35 +: 7]};
-            5'd8: scan_byte = {1'b0, candidate_ptc_7[42 +: 7]};
-            5'd9: scan_byte = {1'b0, candidate_ptc_7[49 +: 7]};
-            5'd10: scan_byte = {1'b0, candidate_ptc_7[56 +: 7]};
-            5'd11: scan_byte = {1'b0, candidate_ptc_7[63 +: 7]};
-            5'd12: scan_byte = {1'b0, candidate_ptc_7[70 +: 7]};
-            5'd13: scan_byte = {1'b0, candidate_ptc_7[77 +: 7]};
-            5'd14: scan_byte = {1'b0, candidate_ptc_7[84 +: 7]};
-            5'd15: scan_byte = {1'b0, candidate_ptc_7[91 +: 7]};
-            5'd16: scan_byte = {1'b0, candidate_ptc_7[98 +: 7]};
-            5'd17: scan_byte = {1'b0, candidate_ptc_7[105 +: 7]};
-            5'd18: scan_byte = {1'b0, candidate_ptc_7[112 +: 7]};
-            5'd19: scan_byte = {1'b0, candidate_ptc_7[119 +: 7]};
-            5'd20: scan_byte = {1'b0, candidate_ptc_7[126 +: 7]};
-            5'd21: scan_byte = {1'b0, candidate_ptc_7[133 +: 7]};
-            5'd22: scan_byte = {1'b0, candidate_ptc_7[140 +: 7]};
-            5'd23: scan_byte = {1'b0, candidate_ptc_7[147 +: 7]};
-            5'd24: scan_byte = {1'b0, candidate_ptc_7[154 +: 7]};
-            5'd25: scan_byte = {1'b0, candidate_ptc_7[161 +: 7]};
-            5'd26: scan_byte = {1'b0, candidate_fan_7[0 +: 7]};
-            5'd27: scan_byte = {1'b0, candidate_fan_7[7 +: 7]};
-            5'd28: scan_byte = {1'b0, candidate_fan_7[14 +: 7]};
-            5'd29: scan_byte = {1'b0, candidate_fan_7[21 +: 7]};
-            5'd30: scan_byte = decode_binary_rail(candidate_solenoid_rail);
-            default: scan_byte = 8'd0;
-        endcase
-    end
-
-    function snapshot_capture_invalid;
-        input [271:0] payload;
-        integer value_index;
-        reg [7:0] value;
-        begin
-            snapshot_capture_invalid =
-                (payload[7:0] != 8'h2a) || (payload[15:8] != 8'h00);
-            for (value_index = 2; value_index <= 29; value_index = value_index + 1) begin
-                if (payload[value_index * 8 + 7]) begin
-                    snapshot_capture_invalid = 1'b1;
-                end
-            end
-            value = payload[30 * 8 +: 8];
-            if ((value != 8'd0) && (value != 8'd100)) begin
-                snapshot_capture_invalid = 1'b1;
-            end
-        end
-    endfunction
-
-    generate
-        for (output_index = 0; output_index < 24; output_index = output_index + 1) begin : g_ptc_output
-            assign ptc_percent[output_index * 8 +: 8] =
-                {1'b0, ptc_percent_7[output_index * 7 +: 7]};
-        end
-        for (output_index = 0; output_index < 4; output_index = output_index + 1) begin : g_fan_output
-            assign fan_percent[output_index * 8 +: 8] =
-                {1'b0, fan_percent_7[output_index * 7 +: 7]};
-        end
-    endgenerate
-
-    binary921_crc16 u_state_hash (
-        .crc_in(candidate_hash),
-        .data(scan_byte),
-        .crc_out(candidate_hash_next)
-    );
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            scan_busy <= 1'b0;
-            candidate_pending <= 1'b0;
-            scan_index <= 5'd0;
-            invalid_seen <= 1'b0;
-            candidate_hash <= 16'hffff;
-            result_valid <= 1'b0;
-            result_accepted <= 1'b0;
-            commit_pulse <= 1'b0;
-            ptc_percent_7 <= 168'd0;
-            fan_percent_7 <= {4{7'd30}};
-            solenoid_rail <= RAIL_ZERO;
-            candidate_ptc_7 <= 168'd0;
-            candidate_fan_7 <= 28'd0;
-            candidate_solenoid_rail <= RAIL_ZERO;
-            state_hash16 <= SAFE_STATE_HASH16;
-        end else begin
-            result_valid <= 1'b0;
-            commit_pulse <= 1'b0;
-
-            if (force_safe) begin
-                if (scan_busy || snapshot_valid) begin
-                    result_valid <= 1'b1;
-                end
-                scan_busy <= 1'b0;
-                candidate_pending <= 1'b0;
-                scan_index <= 5'd0;
-                invalid_seen <= 1'b0;
-                candidate_hash <= 16'hffff;
-                result_accepted <= 1'b0;
-                ptc_percent_7 <= 168'd0;
-                fan_percent_7 <= {4{7'd30}};
-                solenoid_rail <= RAIL_ZERO;
-                state_hash16 <= SAFE_STATE_HASH16;
-            end else if (candidate_pending && commit_authorize) begin
-                candidate_pending <= 1'b0;
-                commit_pulse <= 1'b1;
-                ptc_percent_7 <= candidate_ptc_7;
-                fan_percent_7 <= candidate_fan_7;
-                solenoid_rail <= candidate_solenoid_rail;
-                state_hash16 <= candidate_hash;
-            end else if (snapshot_valid && snapshot_ready) begin
-                scan_busy <= 1'b1;
-                scan_index <= 5'd2;
-                invalid_seen <= snapshot_capture_invalid(snapshot_payload);
-                for (i = 0; i < 24; i = i + 1) begin
-                    candidate_ptc_7[i * 7 +: 7] <=
-                        snapshot_payload[(2 + i) * 8 +: 7];
-                end
-                for (i = 0; i < 4; i = i + 1) begin
-                    candidate_fan_7[i * 7 +: 7] <=
-                        snapshot_payload[(26 + i) * 8 +: 7];
-                end
-                candidate_solenoid_rail <=
-                    encode_binary_rail(snapshot_payload[30 * 8 +: 8]);
-                candidate_hash <= 16'hffff;
-            end else if (scan_busy) begin
-                if (scan_byte_invalid) begin
-                    invalid_seen <= 1'b1;
-                end
-                if (scan_index >= 5'd2 && scan_index <= 5'd30) begin
-                    candidate_hash <= candidate_hash_next;
-                end
-
-                if (scan_index == 5'd30) begin
-                    scan_busy <= 1'b0;
-                    scan_index <= 5'd0;
-                    result_valid <= 1'b1;
-                    if (!invalid_seen && !scan_byte_invalid) begin
-                        result_accepted <= 1'b1;
-                        candidate_pending <= 1'b1;
-                    end else begin
-                        result_accepted <= 1'b0;
-                    end
-                end else begin
-                    scan_index <= scan_index + 5'd1;
-                end
-            end
-        end
-    end
-endmodule

+ 0 - 256
src/rtl/prod2u_p4_normal_v3_rx.v

@@ -1,256 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_normal_v3_rx #(
-    parameter integer CLK_HZ = 25000000,
-    parameter integer INTER_BYTE_TIMEOUT_MS = 2
-) (
-    input  wire         clk,
-    input  wire         rst_n,
-    input  wire         rx_valid,
-    output wire         rx_ready,
-    input  wire [7:0]   rx_data,
-    output reg          request_valid,
-    input  wire         request_ready,
-    output wire [7:0]   request_type,
-    output wire [5:0]   request_length,
-    output wire [271:0] request_payload,
-    output reg  [15:0]  request_crc16,
-    output reg          fast_jog_valid,
-    output reg  [1:0]   fast_jog_axis,
-    output reg          fast_jog_dir,
-    output reg  [15:0]  fast_jog_steps,
-    output reg  [15:0]  crc_error_count,
-    output reg  [15:0]  timeout_count,
-    output reg  [15:0]  format_error_count
-);
-    localparam [7:0] MAGIC0 = 8'ha5;
-    localparam [7:0] MAGIC1 = 8'h5a;
-    localparam [7:0] VERSION = 8'h02;
-    localparam [7:0] PROFILE_ID = 8'h04;
-    localparam [7:0] HOST_CMD = 8'h05;
-    localparam [7:0] HOST_BATCH_CMD = 8'h07;
-    localparam [7:0] MOTION_CMD = 8'h11;
-    localparam [7:0] MOTION_JOG = 8'h35;
-
-    localparam [2:0] ST_MAGIC0 = 3'd0;
-    localparam [2:0] ST_MAGIC1 = 3'd1;
-    localparam [2:0] ST_BODY = 3'd2;
-    localparam [2:0] ST_CRC_LO = 3'd3;
-    localparam [2:0] ST_CRC_HI = 3'd4;
-
-    localparam integer TIMEOUT_CYCLES_CALC = (CLK_HZ / 1000) * INTER_BYTE_TIMEOUT_MS;
-    localparam integer TIMEOUT_CYCLES = (TIMEOUT_CYCLES_CALC > 0) ? TIMEOUT_CYCLES_CALC : 1;
-    localparam integer TIMEOUT_COUNTER_BITS =
-        (TIMEOUT_CYCLES > 1) ? $clog2(TIMEOUT_CYCLES) : 1;
-    localparam [TIMEOUT_COUNTER_BITS-1:0] TIMEOUT_COUNTER_ZERO =
-        {TIMEOUT_COUNTER_BITS{1'b0}};
-    localparam [TIMEOUT_COUNTER_BITS-1:0] TIMEOUT_COUNTER_ONE =
-        {{(TIMEOUT_COUNTER_BITS-1){1'b0}}, 1'b1};
-    localparam [TIMEOUT_COUNTER_BITS-1:0] TIMEOUT_CYCLE_COUNT =
-        TIMEOUT_CYCLES[TIMEOUT_COUNTER_BITS-1:0];
-    localparam [TIMEOUT_COUNTER_BITS-1:0] TIMEOUT_LIMIT =
-        TIMEOUT_CYCLE_COUNT - TIMEOUT_COUNTER_ONE;
-
-    reg [2:0] state;
-    reg [5:0] body_index;
-    reg [TIMEOUT_COUNTER_BITS-1:0] timeout_counter;
-    reg [15:0] crc;
-    wire [15:0] crc_next;
-    reg [7:0] received_crc_lo;
-    reg [7:0] candidate_type;
-    reg [5:0] candidate_length;
-    reg [271:0] candidate_payload;
-    reg [7:0] request_type_reg;
-    reg [5:0] request_length_reg;
-    reg [271:0] request_payload_reg;
-
-    wire candidate_is_fast_jog =
-        (candidate_type == MOTION_CMD) &&
-        (candidate_length == 6'd8) &&
-        (candidate_payload[7:0] == MOTION_JOG) &&
-        (candidate_payload[15:8] <= 8'd1) &&
-        (candidate_payload[23:16] <= 8'd1) &&
-        (candidate_payload[31:24] <= 8'd3) &&
-        (candidate_payload[63:48] == 16'd0);
-
-    assign rx_ready = rst_n;
-    assign request_type = request_type_reg;
-    assign request_length = request_length_reg;
-    assign request_payload = request_payload_reg;
-
-    binary921_crc16 u_crc (
-        .crc_in(crc),
-        .data(rx_data),
-        .crc_out(crc_next)
-    );
-
-    function [7:0] required_payload_length;
-        input [7:0] frame_type;
-        begin
-            case (frame_type)
-                HOST_CMD: required_payload_length = 8'd4;
-                HOST_BATCH_CMD: required_payload_length = 8'd34;
-                MOTION_CMD: required_payload_length = 8'd8;
-                default: required_payload_length = 8'd0;
-            endcase
-        end
-    endfunction
-
-    function [15:0] saturating_increment16;
-        input [15:0] value;
-        begin
-            if (value == 16'hffff) begin
-                saturating_increment16 = value;
-            end else begin
-                saturating_increment16 = value + 16'd1;
-            end
-        end
-    endfunction
-
-    task reset_parser_from_byte;
-        input [7:0] value;
-        begin
-            if (value == MAGIC0) begin
-                state <= ST_MAGIC1;
-            end else begin
-                state <= ST_MAGIC0;
-            end
-            body_index <= 6'd0;
-            timeout_counter <= TIMEOUT_COUNTER_ZERO;
-            crc <= 16'hffff;
-        end
-    endtask
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            state <= ST_MAGIC0;
-            body_index <= 6'd0;
-            timeout_counter <= TIMEOUT_COUNTER_ZERO;
-            crc <= 16'hffff;
-            received_crc_lo <= 8'd0;
-            candidate_type <= 8'd0;
-            candidate_length <= 6'd0;
-            candidate_payload <= 272'd0;
-            request_type_reg <= 8'd0;
-            request_length_reg <= 6'd0;
-            request_payload_reg <= 272'd0;
-            request_valid <= 1'b0;
-            request_crc16 <= 16'd0;
-            fast_jog_valid <= 1'b0;
-            fast_jog_axis <= 2'd0;
-            fast_jog_dir <= 1'b0;
-            fast_jog_steps <= 16'd0;
-            crc_error_count <= 16'd0;
-            timeout_count <= 16'd0;
-            format_error_count <= 16'd0;
-        end else begin
-            fast_jog_valid <= 1'b0;
-
-            if (request_valid && request_ready) begin
-                request_valid <= 1'b0;
-            end
-
-            if (rx_valid && rx_ready) begin
-                timeout_counter <= TIMEOUT_COUNTER_ZERO;
-                case (state)
-                    ST_MAGIC0: begin
-                        if (rx_data == MAGIC0) begin
-                            state <= ST_MAGIC1;
-                        end
-                    end
-
-                    ST_MAGIC1: begin
-                        if (rx_data == MAGIC1) begin
-                            state <= ST_BODY;
-                            body_index <= 6'd0;
-                            crc <= 16'hffff;
-                            candidate_type <= 8'd0;
-                            candidate_length <= 6'd0;
-                            candidate_payload <= 272'd0;
-                        end else if (rx_data != MAGIC0) begin
-                            state <= ST_MAGIC0;
-                        end
-                    end
-
-                    ST_BODY: begin
-                        if ((body_index == 6'd0 && rx_data != VERSION) ||
-                            (body_index == 6'd1 && rx_data != PROFILE_ID) ||
-                            (body_index == 6'd2 &&
-                             required_payload_length(rx_data) == 8'd0) ||
-                            (body_index >= 6'd3 && body_index <= 6'd10 &&
-                             rx_data != 8'd0) ||
-                            (body_index == 6'd11 &&
-                             rx_data != required_payload_length(candidate_type))) begin
-                            format_error_count <=
-                                saturating_increment16(format_error_count);
-                            reset_parser_from_byte(rx_data);
-                        end else begin
-                            crc <= crc_next;
-                            if (body_index == 6'd2) begin
-                                candidate_type <= rx_data;
-                            end else if (body_index == 6'd11) begin
-                                candidate_length <= rx_data[5:0];
-                            end else if (body_index >= 6'd12) begin
-                                candidate_payload[
-                                    (body_index - 6'd12) * 8 +: 8
-                                ] <= rx_data;
-                            end
-
-                            if (body_index >= 6'd12 &&
-                                (body_index - 6'd12) ==
-                                (candidate_length - 6'd1)) begin
-                                state <= ST_CRC_LO;
-                                body_index <= 6'd0;
-                            end else begin
-                                body_index <= body_index + 6'd1;
-                            end
-                        end
-                    end
-
-                    ST_CRC_LO: begin
-                        received_crc_lo <= rx_data;
-                        state <= ST_CRC_HI;
-                    end
-
-                    ST_CRC_HI: begin
-                        if ({rx_data, received_crc_lo} != crc) begin
-                            crc_error_count <=
-                                saturating_increment16(crc_error_count);
-                            reset_parser_from_byte(rx_data);
-                        end else begin
-                            if (candidate_is_fast_jog) begin
-                                fast_jog_valid <= 1'b1;
-                                fast_jog_axis <= candidate_payload[9:8];
-                                fast_jog_dir <= candidate_payload[16];
-                                fast_jog_steps <= candidate_payload[47:32];
-                            end else if (!request_valid || request_ready) begin
-                                request_type_reg <= candidate_type;
-                                request_length_reg <= candidate_length;
-                                request_payload_reg <= candidate_payload;
-                                request_crc16 <= crc;
-                                request_valid <= 1'b1;
-                            end
-                            state <= ST_MAGIC0;
-                            body_index <= 6'd0;
-                            crc <= 16'hffff;
-                        end
-                    end
-
-                    default: state <= ST_MAGIC0;
-                endcase
-            end else if (state != ST_MAGIC0) begin
-                if (timeout_counter >= TIMEOUT_LIMIT) begin
-                    state <= ST_MAGIC0;
-                    body_index <= 6'd0;
-                    crc <= 16'hffff;
-                    timeout_counter <= TIMEOUT_COUNTER_ZERO;
-                    timeout_count <= saturating_increment16(timeout_count);
-                end else begin
-                    timeout_counter <= timeout_counter + TIMEOUT_COUNTER_ONE;
-                end
-            end else begin
-                timeout_counter <= TIMEOUT_COUNTER_ZERO;
-            end
-        end
-    end
-endmodule

+ 0 - 134
src/rtl/prod2u_p4_normal_v3_tx.v

@@ -1,134 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_normal_v3_tx (
-    input  wire         clk,
-    input  wire         rst_n,
-    input  wire         frame_valid,
-    output wire         frame_ready,
-    input  wire [7:0]   frame_type,
-    input  wire [7:0]   frame_payload_len,
-    input  wire [143:0] frame_payload,
-    input  wire         temperature_start,
-    input  wire         temperature_force_ff,
-    output wire         temperature_rd_req,
-    output wire [4:0]   temperature_rd_addr,
-    input  wire         temperature_rd_valid,
-    input  wire [7:0]   temperature_rd_data,
-    output wire         temperature_done,
-    output wire         tx_valid,
-    input  wire         tx_ready,
-    output wire [7:0]   tx_data
-);
-    localparam [1:0] OWNER_IDLE = 2'd0;
-    localparam [1:0] OWNER_STANDARD = 2'd1;
-    localparam [1:0] OWNER_TEMPERATURE = 2'd2;
-
-    (* keep = "true", syn_encoding = "sequential", fsm_encoding = "none" *)
-    reg [1:0] owner;
-    reg temperature_pending;
-    reg temperature_pending_force_ff;
-
-    wire standard_start = (owner == OWNER_IDLE) && frame_valid;
-    wire temperature_short_start =
-        (owner == OWNER_IDLE) && !frame_valid && temperature_pending;
-
-    wire serializer_busy;
-    wire serializer_done;
-    wire serializer_tx_valid;
-    wire [7:0] serializer_tx_data;
-    wire serializer_tx_ready =
-        (owner == OWNER_STANDARD) && tx_ready;
-
-    wire temperature_tx_valid;
-    wire [7:0] temperature_tx_data;
-    wire temperature_tx_ready =
-        (owner == OWNER_TEMPERATURE) && tx_ready;
-    wire temperature_busy;
-    wire temperature_short_done;
-
-    assign frame_ready = (owner == OWNER_STANDARD) && serializer_done;
-    assign temperature_done = temperature_short_done;
-    assign tx_valid = (owner == OWNER_STANDARD) ? serializer_tx_valid :
-        ((owner == OWNER_TEMPERATURE) ? temperature_tx_valid : 1'b0);
-    assign tx_data = (owner == OWNER_STANDARD) ? serializer_tx_data :
-        ((owner == OWNER_TEMPERATURE) ? temperature_tx_data : 8'd0);
-
-    binary921_frame_tx #(
-        .MAX_PAYLOAD_BYTES(18),
-        .LATCH_PAYLOAD(0),
-        .VERSION(8'h02)
-    ) u_frame (
-        .clk(clk),
-        .rst_n(rst_n),
-        .start(standard_start),
-        .profile_id(8'h04),
-        .frame_type(frame_type),
-        .frame_seq(32'd0),
-        .timestamp_tick(32'd0),
-        .payload_len(frame_payload_len),
-        .payload(frame_payload),
-        .busy(serializer_busy),
-        .done(serializer_done),
-        .tx_valid(serializer_tx_valid),
-        .tx_data(serializer_tx_data),
-        .tx_ready(serializer_tx_ready)
-    );
-
-    prod2u_p4_temperature_short_tx u_temperature_short_tx (
-        .clk(clk),
-        .rst_n(rst_n),
-        .start(temperature_short_start),
-        .force_ff(temperature_pending_force_ff),
-        .rd_req(temperature_rd_req),
-        .rd_addr(temperature_rd_addr),
-        .rd_valid(temperature_rd_valid),
-        .rd_data(temperature_rd_data),
-        .tx_valid(temperature_tx_valid),
-        .tx_ready(temperature_tx_ready),
-        .tx_data(temperature_tx_data),
-        .busy(temperature_busy),
-        .done(temperature_short_done)
-    );
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            owner <= OWNER_IDLE;
-            temperature_pending <= 1'b0;
-            temperature_pending_force_ff <= 1'b0;
-        end else begin
-            if (temperature_short_start) begin
-                temperature_pending <= 1'b0;
-            end
-            if (temperature_start) begin
-                temperature_pending <= 1'b1;
-                temperature_pending_force_ff <= temperature_force_ff;
-            end
-
-            case (owner)
-                OWNER_IDLE: begin
-                    if (standard_start) begin
-                        owner <= OWNER_STANDARD;
-                    end else if (temperature_short_start) begin
-                        owner <= OWNER_TEMPERATURE;
-                    end
-                end
-
-                OWNER_STANDARD: begin
-                    if (serializer_done) begin
-                        owner <= OWNER_IDLE;
-                    end
-                end
-
-                OWNER_TEMPERATURE: begin
-                    if (temperature_short_done) begin
-                        owner <= OWNER_IDLE;
-                    end
-                end
-
-                default: owner <= OWNER_IDLE;
-            endcase
-        end
-    end
-
-    wire unused = serializer_busy ^ temperature_busy;
-endmodule

+ 0 - 68
src/rtl/prod2u_p4_normal_v3_watchdog.v

@@ -1,68 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_normal_v3_watchdog #(
-    parameter integer CLK_HZ = 25000000,
-    parameter integer WATCHDOG_SECONDS = 5
-) (
-    input  wire clk,
-    input  wire rst_n,
-    input  wire arm,
-    input  wire refresh,
-    input  wire disable_cmd,
-    output reg  disabled,
-    output reg  armed,
-    output reg  watchdog_timeout,
-    output wire expiry_due,
-    output wire force_safe
-);
-    localparam integer WATCHDOG_CYCLES = CLK_HZ * WATCHDOG_SECONDS;
-    localparam integer COUNTER_BITS = (WATCHDOG_CYCLES <= 1) ? 1 : $clog2(WATCHDOG_CYCLES + 1);
-    localparam [COUNTER_BITS-1:0] WATCHDOG_CYCLE_COUNT =
-        WATCHDOG_CYCLES[COUNTER_BITS-1:0];
-    localparam [COUNTER_BITS-1:0] WATCHDOG_LIMIT =
-        WATCHDOG_CYCLE_COUNT - {{(COUNTER_BITS-1){1'b0}}, 1'b1};
-    reg [COUNTER_BITS-1:0] counter;
-    wire expiry_boundary = armed && !disabled && !watchdog_timeout &&
-        (counter >= WATCHDOG_LIMIT);
-
-    assign expiry_due = rst_n && !disable_cmd && expiry_boundary;
-    // Timeout is status after the expiry edge, not a persistent command gate.
-    // The expiry pulse restores safe outputs once; a later valid snapshot can
-    // commit and re-arm the watchdog without requiring an intervening DISABLE.
-    assign force_safe = disable_cmd || expiry_due;
-
-    generate
-        if (WATCHDOG_CYCLES < 1) begin : g_watchdog_interval_must_be_positive
-            prod2u_p4_normal_v3_watchdog_interval_must_be_positive u_interval_error();
-        end
-    endgenerate
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            counter <= {COUNTER_BITS{1'b0}};
-            disabled <= 1'b1;
-            armed <= 1'b0;
-            watchdog_timeout <= 1'b0;
-        end else begin
-            if (disable_cmd) begin
-                counter <= {COUNTER_BITS{1'b0}};
-                disabled <= 1'b1;
-                armed <= 1'b0;
-                watchdog_timeout <= 1'b0;
-            end else if (expiry_boundary) begin
-                disabled <= 1'b1;
-                armed <= 1'b0;
-                watchdog_timeout <= 1'b1;
-            end else if (arm) begin
-                counter <= {COUNTER_BITS{1'b0}};
-                disabled <= 1'b0;
-                armed <= 1'b1;
-                watchdog_timeout <= 1'b0;
-            end else if (refresh && armed && !disabled && !watchdog_timeout) begin
-                counter <= {COUNTER_BITS{1'b0}};
-            end else if (armed && !disabled && !watchdog_timeout) begin
-                counter <= counter + {{(COUNTER_BITS-1){1'b0}}, 1'b1};
-            end
-        end
-    end
-endmodule

+ 0 - 80
src/rtl/prod2u_p4_response_scheduler.v

@@ -1,80 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_response_scheduler (
-    input  wire         clk,
-    input  wire         rst_n,
-    input  wire         command_valid,
-    input  wire [63:0]  command_ack_payload,
-    input  wire         followup_valid,
-    input  wire [7:0]   followup_frame_type,
-    input  wire [79:0]  followup_payload,
-    output reg          command_done,
-    output wire         tx_valid,
-    input  wire         tx_ready,
-    output reg  [7:0]   tx_frame_type,
-    output reg  [7:0]   tx_payload_len,
-    output reg  [143:0] tx_payload
-);
-    localparam [1:0] STATE_IDLE = 2'd0;
-    localparam [1:0] STATE_ACK = 2'd1;
-    localparam [1:0] STATE_FOLLOWUP = 2'd2;
-    localparam [1:0] STATE_WAIT_CLEAR = 2'd3;
-
-    reg [1:0] state;
-
-    assign tx_valid = command_valid &&
-        ((state == STATE_ACK) || (state == STATE_FOLLOWUP));
-
-    always @(*) begin
-        tx_frame_type = 8'h00;
-        tx_payload_len = 8'd0;
-        tx_payload = 144'd0;
-        if (state == STATE_ACK) begin
-            tx_frame_type = 8'h06;
-            tx_payload_len = 8'd8;
-            tx_payload[63:0] = command_ack_payload;
-        end else if (state == STATE_FOLLOWUP) begin
-            tx_frame_type = followup_frame_type;
-            tx_payload_len = 8'd10;
-            tx_payload[79:0] = followup_payload;
-        end
-    end
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            state <= STATE_IDLE;
-            command_done <= 1'b0;
-        end else begin
-            command_done <= 1'b0;
-            case (state)
-                STATE_IDLE: begin
-                    if (command_valid) state <= STATE_ACK;
-                end
-                STATE_ACK: begin
-                    if (!command_valid) begin
-                        state <= STATE_IDLE;
-                    end else if (tx_ready) begin
-                        if (followup_valid) begin
-                            state <= STATE_FOLLOWUP;
-                        end else begin
-                            state <= STATE_WAIT_CLEAR;
-                            command_done <= 1'b1;
-                        end
-                    end
-                end
-                STATE_FOLLOWUP: begin
-                    if (!command_valid) begin
-                        state <= STATE_IDLE;
-                    end else if (tx_ready) begin
-                        state <= STATE_WAIT_CLEAR;
-                        command_done <= 1'b1;
-                    end
-                end
-                STATE_WAIT_CLEAR: begin
-                    if (!command_valid) state <= STATE_IDLE;
-                end
-                default: state <= STATE_IDLE;
-            endcase
-        end
-    end
-endmodule

+ 0 - 149
src/rtl/prod2u_p4_temperature_short_tx.v

@@ -1,149 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_temperature_short_tx (
-    input  wire       clk,
-    input  wire       rst_n,
-    input  wire       start,
-    input  wire       force_ff,
-    output reg        rd_req,
-    output reg  [4:0] rd_addr,
-    input  wire       rd_valid,
-    input  wire [7:0] rd_data,
-    output reg        tx_valid,
-    input  wire       tx_ready,
-    output reg  [7:0] tx_data,
-    output reg        busy,
-    output reg        done
-);
-    localparam [1:0] ST_IDLE = 2'd0;
-    localparam [1:0] ST_SEND = 2'd1;
-    localparam [1:0] ST_WAIT_READ = 2'd2;
-
-    (* keep = "true", syn_encoding = "sequential", fsm_encoding = "none" *)
-    reg [1:0] state;
-    reg force_ff_latched;
-    reg [5:0] byte_index;
-    reg [15:0] crc;
-
-    wire [15:0] crc_after_byte = crc16_byte(crc, tx_data);
-
-    function [15:0] crc16_byte;
-        input [15:0] crc_in;
-        input [7:0] value_in;
-        reg [15:0] value;
-        integer bit_index;
-        begin
-            value = crc_in ^ {value_in, 8'h00};
-            for (bit_index = 0; bit_index < 8; bit_index = bit_index + 1) begin
-                if (value[15]) value = (value << 1) ^ 16'h1021;
-                else value = value << 1;
-            end
-            crc16_byte = value;
-        end
-    endfunction
-
-    function [7:0] header_byte;
-        input [5:0] index;
-        begin
-            case (index)
-                6'd0: header_byte = 8'ha5;
-                6'd1: header_byte = 8'h5a;
-                6'd2: header_byte = 8'h02;
-                6'd3: header_byte = 8'h04;
-                6'd4: header_byte = 8'h10;
-                default: header_byte = 8'h1b;
-            endcase
-        end
-    endfunction
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            state <= ST_IDLE;
-            force_ff_latched <= 1'b0;
-            byte_index <= 6'd0;
-            crc <= 16'hffff;
-            rd_req <= 1'b0;
-            rd_addr <= 5'd0;
-            tx_valid <= 1'b0;
-            tx_data <= 8'd0;
-            busy <= 1'b0;
-            done <= 1'b0;
-        end else begin
-            rd_req <= 1'b0;
-            done <= 1'b0;
-
-            case (state)
-                ST_IDLE: begin
-                    tx_valid <= 1'b0;
-                    if (start) begin
-                        force_ff_latched <= force_ff;
-                        byte_index <= 6'd0;
-                        crc <= 16'hffff;
-                        tx_data <= 8'ha5;
-                        tx_valid <= 1'b1;
-                        busy <= 1'b1;
-                        state <= ST_SEND;
-                    end
-                end
-
-                ST_SEND: begin
-                    if (tx_valid && tx_ready) begin
-                        if ((byte_index >= 6'd2) && (byte_index <= 6'd32)) begin
-                            crc <= crc_after_byte;
-                        end
-
-                        if (byte_index < 6'd5) begin
-                            byte_index <= byte_index + 6'd1;
-                            tx_data <= header_byte(byte_index + 6'd1);
-                        end else if (byte_index == 6'd5) begin
-                            byte_index <= 6'd6;
-                            if (force_ff_latched) begin
-                                tx_data <= 8'hff;
-                            end else begin
-                                tx_valid <= 1'b0;
-                                rd_addr <= 5'd0;
-                                rd_req <= 1'b1;
-                                state <= ST_WAIT_READ;
-                            end
-                        end else if (byte_index < 6'd32) begin
-                            byte_index <= byte_index + 6'd1;
-                            if (force_ff_latched) begin
-                                tx_data <= 8'hff;
-                            end else begin
-                                tx_valid <= 1'b0;
-                                rd_addr <= byte_index[4:0] - 5'd5;
-                                rd_req <= 1'b1;
-                                state <= ST_WAIT_READ;
-                            end
-                        end else if (byte_index == 6'd32) begin
-                            byte_index <= 6'd33;
-                            tx_data <= crc_after_byte[7:0];
-                        end else if (byte_index == 6'd33) begin
-                            byte_index <= 6'd34;
-                            tx_data <= crc[15:8];
-                        end else begin
-                            tx_valid <= 1'b0;
-                            busy <= 1'b0;
-                            done <= 1'b1;
-                            state <= ST_IDLE;
-                        end
-                    end
-                end
-
-                ST_WAIT_READ: begin
-                    if (rd_valid) begin
-                        tx_data <= rd_data;
-                        tx_valid <= 1'b1;
-                        state <= ST_SEND;
-                    end
-                end
-
-                default: begin
-                    tx_valid <= 1'b0;
-                    busy <= 1'b0;
-                    state <= ST_IDLE;
-                end
-            endcase
-        end
-    end
-endmodule

+ 0 - 199
src/rtl/prod2u_p4_temperature_store.v

@@ -1,199 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_temperature_store (
-    input  wire       clk,
-    input  wire       rst_n,
-    input  wire       wr_en,
-    input  wire [4:0] wr_addr,
-    input  wire [7:0] wr_data,
-    input  wire       rd_req,
-    input  wire [4:0] rd_addr,
-    output reg        rd_valid,
-    output wire [7:0] rd_data
-);
-    reg rd_invalid;
-
-`ifdef FORMAL
-    reg [7:0] memory [0:31];
-    reg [7:0] formal_rd_data;
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            rd_valid <= 1'b0;
-            rd_invalid <= 1'b0;
-            formal_rd_data <= 8'd0;
-        end else begin
-            rd_valid <= rd_req;
-            rd_invalid <= rd_req && (rd_addr > 5'd26);
-            if (wr_en && (wr_addr <= 5'd26)) begin
-                memory[wr_addr] <= wr_data;
-            end
-            if (rd_req && (rd_addr <= 5'd26)) begin
-                formal_rd_data <= memory[rd_addr];
-            end
-        end
-    end
-
-    assign rd_data = rd_invalid ? 8'hff : formal_rd_data;
-`else
-    wire [8:0] write_data_unused;
-    /* verilator lint_off UNUSEDSIGNAL */
-    wire [8:0] read_data;
-    /* verilator lint_on UNUSEDSIGNAL */
-    wire write_enable = wr_en && (wr_addr <= 5'd26);
-
-    EF2_LOGIC_BRAM #(
-        .DATA_WIDTH_A (9),
-        .DATA_WIDTH_B (9),
-        .ADDR_WIDTH_A (10),
-        .ADDR_WIDTH_B (10),
-        .DATA_DEPTH_A (1024),
-        .DATA_DEPTH_B (1024),
-        .BYTE_ENABLE  (0),
-        .BYTE_A       (1),
-        .BYTE_B       (1),
-        .MODE         ("DP"),
-        .REGMODE_A    ("NOREG"),
-        .REGMODE_B    ("NOREG"),
-        .WRITEMODE_A  ("NORMAL"),
-        .WRITEMODE_B  ("NORMAL"),
-        .RESETMODE    ("ASYNC"),
-        .DEBUGGABLE   ("NO"),
-        .PACKABLE     ("NO"),
-        .FORCE_KEEP   ("OFF"),
-        .INIT_FILE    ("NONE"),
-        .FILL_ALL     ("NONE"),
-        .IMPLEMENT    ("9K")
-    ) temperature_memory (
-        .doa   (write_data_unused),
-        .dob   (read_data),
-        .dia   ({1'b0, wr_data}),
-        .dib   (9'd0),
-        .cea   (write_enable),
-        .ocea  (1'b1),
-        .clka  (clk),
-        .wea   (write_enable),
-        .rsta  (1'b0),
-        .ceb   (rd_req),
-        .oceb  (1'b1),
-        .clkb  (clk),
-        .web   (1'b0),
-        .rstb  (1'b0),
-        .bea   (1'b1),
-        .beb   (1'b1),
-        .addra ({5'd0, wr_addr}),
-        .addrb ({5'd0, rd_addr})
-    );
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            rd_valid <= 1'b0;
-            rd_invalid <= 1'b0;
-        end else begin
-            rd_valid <= rd_req;
-            rd_invalid <= rd_req && (rd_addr > 5'd26);
-        end
-    end
-
-    assign rd_data = rd_invalid ? 8'hff : read_data[7:0];
-`endif
-endmodule
-
-// synthesis translate_off
-/* verilator lint_off DECLFILENAME */
-/* verilator lint_off UNUSEDSIGNAL */
-/* verilator lint_off UNUSEDPARAM */
-module prod2u_p4_temperature_bram_sim (
-    input  wire       clk,
-    input  wire       wr_en,
-    input  wire [9:0] wr_addr,
-    input  wire [7:0] wr_data,
-    input  wire       rd_req,
-    input  wire [9:0] rd_addr,
-    output reg  [7:0] rd_data
-);
-    reg [8:0] memory [0:1023];
-
-    always @(posedge clk) begin
-        if (wr_en) begin
-            memory[wr_addr] <= {1'b0, wr_data};
-        end
-        if (rd_req) begin
-            rd_data <= memory[rd_addr][7:0];
-        end
-    end
-endmodule
-
-module EF2_LOGIC_BRAM #(
-    parameter DATA_WIDTH_A = 9,
-    parameter DATA_WIDTH_B = 9,
-    parameter ADDR_WIDTH_A = 10,
-    parameter ADDR_WIDTH_B = 10,
-    parameter DATA_DEPTH_A = 1024,
-    parameter DATA_DEPTH_B = 1024,
-    parameter BYTE_ENABLE = 0,
-    parameter BYTE_A = 1,
-    parameter BYTE_B = 1,
-    parameter MODE = "DP",
-    parameter REGMODE_A = "NOREG",
-    parameter REGMODE_B = "NOREG",
-    parameter WRITEMODE_A = "NORMAL",
-    parameter WRITEMODE_B = "NORMAL",
-    parameter RESETMODE = "ASYNC",
-    parameter DEBUGGABLE = "NO",
-    parameter PACKABLE = "NO",
-    parameter FORCE_KEEP = "OFF",
-    parameter INIT_FILE = "NONE",
-    parameter FILL_ALL = "NONE",
-    parameter IMPLEMENT = "9K"
-) (
-    output wire [8:0] doa,
-    output wire [8:0] dob,
-    input  wire [8:0] dia,
-    input  wire [8:0] dib,
-    input  wire       cea,
-    input  wire       ocea,
-    input  wire       clka,
-    input  wire       wea,
-    input  wire       rsta,
-    input  wire       ceb,
-    input  wire       oceb,
-    input  wire       clkb,
-    input  wire       web,
-    input  wire       rstb,
-    input  wire       bea,
-    input  wire       beb,
-    input  wire [9:0] addra,
-    input  wire [9:0] addrb
-);
-    wire [7:0] sim_read_data;
-    wire unused = &{
-        1'b0,
-        dib,
-        ocea,
-        rsta,
-        oceb,
-        clkb,
-        web,
-        rstb,
-        bea,
-        beb
-    };
-
-    prod2u_p4_temperature_bram_sim simulation_memory (
-        .clk     (clka),
-        .wr_en   (cea && wea),
-        .wr_addr (addra),
-        .wr_data (dia[7:0]),
-        .rd_req  (ceb),
-        .rd_addr (addrb),
-        .rd_data (sim_read_data)
-    );
-
-    assign doa = 9'd0;
-    assign dob = {1'b0, sim_read_data};
-endmodule
-/* verilator lint_on UNUSEDPARAM */
-/* verilator lint_on UNUSEDSIGNAL */
-/* verilator lint_on DECLFILENAME */
-// synthesis translate_on

+ 7 - 12
tests/README.md

@@ -1,15 +1,10 @@
-# Verification Layers
+# Verification Tree
 
-The active verification tree covers only Prod2U P4 Normal v3.
+The active target list is `config/prod2u_p4_verification_targets_v1.json`.
 
-- `tests/sim/`: directed Icarus/Verilator RTL simulations.
-- `tests/cocotb/`: Python-driven core and top-level cosimulation.
-- `tests/formal/`: JOG timing/reload, protocol, output, and non-motor watchdog properties.
-- `tests/unit/`: host protocol, model, package, resource and receipt contracts.
-- `tests/fixtures/`: deliberately bad inputs used to prove detectors fail closed.
+- `tests/sim/` contains the current Icarus RTL smoke tests.
+- `tests/cocotb/` contains the real UART-bit top-level scenario and its simulation-only timing wrapper.
+- `tests/formal/` contains the minimal current frame and motor contracts.
+- `tests/unit/` contains project configuration, generation, protocol, harness, CDC, TD-file, and layout tests.
 
-The active motor contract is intentionally unprotected: only opcode `0x35` drives X/Y, `1..65535` steps execute without a cap at fixed 1000 step/s, and ACK follows the first STEP rise. Limit inputs, DISABLE, and watchdog expiry do not stop a motor; formal checks must not reintroduce those retired gates.
-
-The fast-JOG targets are `prod2u_p4_normal_v3_rx_fast_jog_tb`, `prod2u_p4_fast_jog_core_tb`, `prod2u_p4_fast_jog_top`, and `prod2u_p4_fast_jog_path`. Together they cover the held ordinary slot, non-IDLE core states, TX backpressure, latest-wins ACK storage, full setup/phase reload, exact raw nonzero `u16` counts, and X/Y isolation.
-
-Missing tools are reported as blocked; a missing test, detector gap or counterexample is a failure. Offline checks and TD builds never imply that a board was programmed or moved.
+The test environment is virtual only. No test opens a serial port, JTAG, programmer, driver installer, or physical thermal loop.

+ 0 - 167
tests/cocotb/prod2u_p4_ct7428_slave.v

@@ -1,167 +0,0 @@
-`timescale 1ns/1ps
-
-// Simulation-only CT7428 responder for repeated on-demand scans.
-module prod2u_p4_ct7428_slave (
-    input  wire       start_scan,
-    input  wire       temp_scl,
-    input  wire       temp_sda,
-    input  wire       mixed_nack,
-    input  wire [4:0] nack_slot,
-    output reg        sda_drive_low,
-    output reg        scan_active,
-    output reg  [3:0] scan_count,
-    output reg        transaction_error,
-    output reg  [4:0] address_49_count,
-    output reg  [4:0] address_48_count,
-    output reg  [4:0] address_4b_count,
-    output reg  [5:0] read_ack_count,
-    output reg  [5:0] read_nack_count
-);
-    integer slot;
-    reg [7:0] observed;
-    reg first_ack;
-    reg final_ack;
-    reg mixed_nack_latched;
-    reg [4:0] nack_slot_latched;
-
-    function [6:0] slot_address;
-        input integer value;
-        begin
-            if (value < 9) slot_address = 7'h49;
-            else if (value < 18) slot_address = 7'h48;
-            else slot_address = 7'h4b;
-        end
-    endfunction
-
-    function [15:0] slot_data;
-        input integer value;
-        begin
-            slot_data = value << 7;
-        end
-    endfunction
-
-    task wait_for_start;
-        begin : find_start
-            forever begin
-                @(negedge temp_sda);
-                if (temp_scl) disable find_start;
-            end
-        end
-    endtask
-
-    task wait_for_stop;
-        begin : find_stop
-            forever begin
-                @(posedge temp_sda);
-                if (temp_scl) disable find_stop;
-            end
-        end
-    endtask
-
-    task capture_master_byte;
-        output [7:0] value;
-        integer bit_index;
-        begin
-            value = 8'd0;
-            for (bit_index = 7; bit_index >= 0; bit_index = bit_index - 1) begin
-                @(posedge temp_scl);
-                value[bit_index] = temp_sda;
-                @(negedge temp_scl);
-            end
-        end
-    endtask
-
-    task drive_ack;
-        input acknowledge;
-        begin
-            sda_drive_low = acknowledge;
-            @(posedge temp_scl);
-            @(negedge temp_scl);
-            sda_drive_low = 1'b0;
-        end
-    endtask
-
-    task drive_word;
-        input [15:0] value;
-        output acknowledged_first;
-        output acknowledged_final;
-        integer byte_index;
-        integer bit_index;
-        reg [7:0] byte_value;
-        begin
-            acknowledged_first = 1'b0;
-            acknowledged_final = 1'b0;
-            for (byte_index = 1; byte_index >= 0; byte_index = byte_index - 1) begin
-                byte_value = byte_index ? value[15:8] : value[7:0];
-                for (bit_index = 7; bit_index >= 0; bit_index = bit_index - 1) begin
-                    sda_drive_low = ~byte_value[bit_index];
-                    @(posedge temp_scl);
-                    @(negedge temp_scl);
-                end
-                sda_drive_low = 1'b0;
-                @(posedge temp_scl);
-                if (byte_index) acknowledged_first = ~temp_sda;
-                else acknowledged_final = ~temp_sda;
-                @(negedge temp_scl);
-            end
-        end
-    endtask
-
-    initial begin
-        sda_drive_low = 1'b0;
-        scan_active = 1'b0;
-        scan_count = 4'd0;
-        transaction_error = 1'b0;
-        address_49_count = 5'd0;
-        address_48_count = 5'd0;
-        address_4b_count = 5'd0;
-        read_ack_count = 6'd0;
-        read_nack_count = 6'd0;
-        forever begin
-            @(posedge start_scan);
-            scan_active = 1'b1;
-            transaction_error = 1'b0;
-            address_49_count = 5'd0;
-            address_48_count = 5'd0;
-            address_4b_count = 5'd0;
-            read_ack_count = 6'd0;
-            read_nack_count = 6'd0;
-            mixed_nack_latched = mixed_nack;
-            nack_slot_latched = nack_slot;
-
-            for (slot = 0; slot < 27; slot = slot + 1) begin
-                wait_for_start();
-                capture_master_byte(observed);
-                if (observed !== {slot_address(slot), 1'b0}) transaction_error = 1'b1;
-                drive_ack(1'b1);
-                capture_master_byte(observed);
-                if (observed !== (slot % 9)) transaction_error = 1'b1;
-                drive_ack(1'b1);
-                wait_for_stop();
-
-                wait_for_start();
-                capture_master_byte(observed);
-                if (observed !== {slot_address(slot), 1'b1}) transaction_error = 1'b1;
-                drive_ack(!(mixed_nack_latched && slot == nack_slot_latched));
-                if (mixed_nack_latched && slot == nack_slot_latched) begin
-                    wait_for_stop();
-                end else begin
-                    drive_word(slot_data(slot), first_ack, final_ack);
-                    if (!first_ack || final_ack) transaction_error = 1'b1;
-                    if (first_ack) read_ack_count = read_ack_count + 1'b1;
-                    if (!final_ack) read_nack_count = read_nack_count + 1'b1;
-                    wait_for_stop();
-                end
-
-                if (slot_address(slot) == 7'h49)
-                    address_49_count = address_49_count + 1'b1;
-                else if (slot_address(slot) == 7'h48)
-                    address_48_count = address_48_count + 1'b1;
-                else
-                    address_4b_count = address_4b_count + 1'b1;
-            end
-            scan_count = scan_count + 1'b1;
-            scan_active = 1'b0;
-        end
-    end
-endmodule

+ 0 - 96
tests/cocotb/prod2u_p4_fast_jog_top.v

@@ -1,96 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_fast_jog_top;
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg rx_valid = 1'b0;
-    reg [7:0] rx_data = 8'd0;
-    wire rx_ready;
-    reg frame_ready = 1'b0;
-
-    wire request_valid;
-    wire request_ready;
-    wire [7:0] request_type;
-    wire [5:0] request_length;
-    wire [271:0] request_payload;
-    wire [15:0] request_crc16;
-    wire fast_jog_valid;
-    wire [1:0] fast_jog_axis;
-    wire fast_jog_dir;
-    wire [15:0] fast_jog_steps;
-    wire [15:0] crc_error_count;
-    wire [15:0] timeout_count;
-    wire [15:0] format_error_count;
-
-    wire frame_valid;
-    wire [7:0] frame_type;
-    wire [7:0] frame_payload_len;
-    wire [143:0] frame_payload;
-    wire [191:0] ptc_percent;
-    wire [31:0] fan_percent;
-    wire [7:0] solenoid_percent;
-    wire [15:0] state_hash16;
-    wire [2:0] step_out;
-    wire [2:0] dir_out;
-    wire en_n;
-    wire disabled;
-    wire watchdog_timeout;
-
-    prod2u_p4_normal_v3_rx #(
-        .CLK_HZ(1000),
-        .INTER_BYTE_TIMEOUT_MS(64)
-    ) u_rx (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_valid(rx_valid),
-        .rx_ready(rx_ready),
-        .rx_data(rx_data),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(request_crc16),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(fast_jog_axis),
-        .fast_jog_dir(fast_jog_dir),
-        .fast_jog_steps(fast_jog_steps),
-        .crc_error_count(crc_error_count),
-        .timeout_count(timeout_count),
-        .format_error_count(format_error_count)
-    );
-
-    prod2u_p4_normal_v3_core #(
-        .CLK_HZ(128),
-        .WATCHDOG_SECONDS(1),
-        .DIR_SETUP_CYCLES(8),
-        .STEP_HALF_CYCLES(2)
-    ) u_core (
-        .clk(clk),
-        .rst_n(rst_n),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(request_crc16),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(fast_jog_axis),
-        .fast_jog_dir(fast_jog_dir),
-        .fast_jog_steps(fast_jog_steps),
-        .frame_valid(frame_valid),
-        .frame_ready(frame_ready),
-        .frame_type(frame_type),
-        .frame_payload_len(frame_payload_len),
-        .frame_payload(frame_payload),
-        .ptc_percent(ptc_percent),
-        .fan_percent(fan_percent),
-        .solenoid_percent(solenoid_percent),
-        .state_hash16(state_hash16),
-        .step_out(step_out),
-        .dir_out(dir_out),
-        .en_n(en_n),
-        .disabled(disabled),
-        .watchdog_timeout(watchdog_timeout)
-    );
-endmodule

+ 0 - 90
tests/cocotb/prod2u_p4_normal_v3_ack_only_top.v

@@ -1,90 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_normal_v3_ack_only_top;
-    reg sys_clk = 1'b0;
-    reg host_uart_rx = 1'b1;
-    reg x_limit_raw = 1'b0;
-    reg y_limit_raw = 1'b0;
-    reg force_sda_low = 1'b0;
-    reg mixed_nack = 1'b0;
-    reg [4:0] nack_slot = 5'd10;
-    wire host_uart_tx;
-    wire [23:0] ptc_pwm_out;
-    wire [3:0] fan_pwm_out;
-    wire solenoid_out;
-    wire motor_en_n;
-    wire x_step;
-    wire x_dir;
-    wire y_step;
-    wire y_dir;
-    wire z_step;
-    wire z_dir;
-    wire slave_sda_drive_low;
-    tri1 temp_scl;
-    tri1 temp_sda;
-
-    assign temp_sda = (slave_sda_drive_low || force_sda_low) ? 1'b0 : 1'bz;
-
-    wire sys_rst_n_debug = u_dut.sys_rst_n;
-    wire disabled_debug = u_dut.disabled;
-    wire watchdog_timeout_debug = u_dut.watchdog_timeout;
-    wire [191:0] ptc_percent_debug = u_dut.ptc_percent;
-    wire [31:0] fan_percent_debug = u_dut.fan_percent;
-    wire [7:0] solenoid_percent_debug = u_dut.solenoid_percent;
-    wire [15:0] state_hash16_debug = u_dut.state_hash16;
-    wire [15:0] x_remaining_debug =
-        u_dut.u_core.u_motors.u_x_axis.remaining_steps;
-    wire [15:0] y_remaining_debug =
-        u_dut.u_core.u_motors.u_y_axis.remaining_steps;
-    wire temperature_powerup_ready_debug = u_dut.temperature_powerup_ready;
-    wire temperature_read_start_debug = u_dut.temperature_read_start;
-    wire temperature_i2c_busy_debug = u_dut.temperature_i2c_busy;
-
-    prod2u_p4_normal_v3_top #(
-        .CLK_HZ(10000),
-        .HOST_UART_CLKS_PER_BIT(4),
-        .POR_CYCLES(4),
-        .INTER_BYTE_TIMEOUT_MS(8),
-        .PTC_STEP_CLKS(1),
-        .FAN_STEP_CLKS(1),
-        .SOLENOID_ACTIVE_HIGH(1)
-    ) u_dut (
-        .sys_clk(sys_clk),
-        .host_uart_rx(host_uart_rx),
-        .host_uart_tx(host_uart_tx),
-        .ptc_pwm_out(ptc_pwm_out),
-        .fan_pwm_out(fan_pwm_out),
-        .solenoid_out(solenoid_out),
-        .motor_en_n(motor_en_n),
-        .x_step(x_step),
-        .x_dir(x_dir),
-        .y_step(y_step),
-        .y_dir(y_dir),
-        .z_step(z_step),
-        .z_dir(z_dir),
-        .x_limit_raw(x_limit_raw),
-        .y_limit_raw(y_limit_raw),
-        .temp_scl(temp_scl),
-        .temp_sda(temp_sda)
-    );
-
-    defparam u_dut.u_temperature_i2c.HALF_PERIOD_CLKS = 4;
-    defparam u_dut.u_temperature_i2c.TIMEOUT_CLKS = 2000;
-
-    prod2u_p4_ct7428_slave u_ct7428_slave (
-        .start_scan(temperature_read_start_debug),
-        .temp_scl(temp_scl),
-        .temp_sda(temp_sda),
-        .mixed_nack(mixed_nack),
-        .nack_slot(nack_slot),
-        .sda_drive_low(slave_sda_drive_low),
-        .scan_active(),
-        .scan_count(),
-        .transaction_error(),
-        .address_49_count(),
-        .address_48_count(),
-        .address_4b_count(),
-        .read_ack_count(),
-        .read_nack_count()
-    );
-endmodule

+ 0 - 58
tests/cocotb/run_prod2u_p4_fast_jog_top.py

@@ -1,58 +0,0 @@
-#!/usr/bin/env python3
-"""Run the RX/core fast-JOG cocotb RED tests."""
-
-from __future__ import annotations
-
-import os
-from pathlib import Path
-import xml.etree.ElementTree as ET
-
-
-ROOT = Path(__file__).resolve().parents[2]
-TEST_DIR = Path(__file__).resolve().parent
-TEMP_ROOT = Path(os.environ.get("TEMP", ROOT / "tmp"))
-BUILD_DIR = TEMP_ROOT / "cocotb" / "prod2u_p4_fast_jog_top"
-RESULTS_XML = BUILD_DIR / "results.xml"
-
-
-def rtl_sources() -> list[Path]:
-    return sorted(path for path in (ROOT / "src" / "rtl").glob("*.v") if path.is_file())
-
-
-def results_xml_has_failures(results: Path) -> bool:
-    root = ET.parse(results).getroot()
-    return bool(
-        root.findall(".//failure")
-        or root.findall(".//error")
-        or sum(int(node.attrib.get("failures", "0")) for node in root.findall(".//testsuite"))
-        or sum(int(node.attrib.get("errors", "0")) for node in root.findall(".//testsuite"))
-        or int(root.attrib.get("failures", "0"))
-        or int(root.attrib.get("errors", "0"))
-    )
-
-
-def main() -> int:
-    from cocotb_tools.runner import get_runner
-
-    runner = get_runner("icarus")
-    runner.build(
-        sources=[*rtl_sources(), TEST_DIR / "prod2u_p4_fast_jog_top.v"],
-        hdl_toplevel="prod2u_p4_fast_jog_top",
-        build_dir=BUILD_DIR,
-        always=True,
-        verbose=False,
-    )
-    results = Path(
-        runner.test(
-            hdl_toplevel="prod2u_p4_fast_jog_top",
-            test_module="test_prod2u_p4_fast_jog_top",
-            build_dir=BUILD_DIR,
-            test_dir=TEST_DIR,
-            results_xml=str(RESULTS_XML),
-        )
-    )
-    return 1 if not results.is_file() or results_xml_has_failures(results) else 0
-
-
-if __name__ == "__main__":
-    raise SystemExit(main())

+ 0 - 64
tests/cocotb/run_prod2u_p4_normal_v3_ack_only_top_e2e.py

@@ -1,64 +0,0 @@
-#!/usr/bin/env python3
-"""Run the Normal-v3 ACK-only top-level cocotb test."""
-
-from __future__ import annotations
-
-import os
-from pathlib import Path
-import xml.etree.ElementTree as ET
-
-
-ROOT = Path(__file__).resolve().parents[2]
-TEST_DIR = Path(__file__).resolve().parent
-TEMP_ROOT = Path(os.environ.get("TEMP", ROOT / "tmp"))
-BUILD_DIR = TEMP_ROOT / "cocotb" / "prod2u_p4_normal_v3_ack_only_top_e2e"
-RESULTS_XML = BUILD_DIR / "results.xml"
-
-
-def rtl_sources() -> list[Path]:
-    sources = sorted((ROOT / "src" / "rtl").glob("*.v"))
-    sources.append(ROOT / "src" / "top" / "prod2u_p4_normal_v3_top.v")
-    return [path for path in sources if path.is_file()]
-
-
-def results_xml_has_failures(results: Path) -> bool:
-    root = ET.parse(results).getroot()
-    return bool(
-        root.findall(".//failure")
-        or root.findall(".//error")
-        or sum(int(node.attrib.get("failures", "0")) for node in root.findall(".//testsuite"))
-        or sum(int(node.attrib.get("errors", "0")) for node in root.findall(".//testsuite"))
-        or int(root.attrib.get("failures", "0"))
-        or int(root.attrib.get("errors", "0"))
-    )
-
-
-def main() -> int:
-    from cocotb_tools.runner import get_runner
-
-    runner = get_runner("icarus")
-    runner.build(
-        sources=[
-            *rtl_sources(),
-            TEST_DIR / "prod2u_p4_ct7428_slave.v",
-            TEST_DIR / "prod2u_p4_normal_v3_ack_only_top.v",
-        ],
-        hdl_toplevel="prod2u_p4_normal_v3_ack_only_top",
-        build_dir=BUILD_DIR,
-        always=True,
-        verbose=False,
-    )
-    results = Path(
-        runner.test(
-            hdl_toplevel="prod2u_p4_normal_v3_ack_only_top",
-            test_module="test_prod2u_p4_normal_v3_ack_only_top_e2e",
-            build_dir=BUILD_DIR,
-            test_dir=TEST_DIR,
-            results_xml=str(RESULTS_XML),
-        )
-    )
-    return 1 if not results.is_file() or results_xml_has_failures(results) else 0
-
-
-if __name__ == "__main__":
-    raise SystemExit(main())

+ 0 - 241
tests/cocotb/test_prod2u_p4_fast_jog_top.py

@@ -1,241 +0,0 @@
-"""RED tests for the independent RX-to-axis JOG fast path."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-import cocotb
-from cocotb.clock import Clock
-from cocotb.triggers import ClockCycles, FallingEdge, ReadOnly, RisingEdge
-
-
-ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(ROOT / "tools"))
-
-import prod2u_p4_protocol as protocol  # noqa: E402
-
-
-HOST_ACK = int(protocol.FrameType.HOST_ACK)
-GET_STATUS = int(protocol.CommandId.GET_STATUS)
-SET_SNAPSHOT = int(protocol.CommandId.SET_OUTPUT_SNAPSHOT)
-JOG = int(protocol.MotionOpcode.JOG)
-
-
-async def start_and_reset(dut) -> None:
-    cocotb.start_soon(Clock(dut.clk, 10, unit="ns").start())
-    dut.rst_n.value = 0
-    dut.rx_valid.value = 0
-    dut.rx_data.value = 0
-    dut.frame_ready.value = 0
-    await ClockCycles(dut.clk, 5)
-    dut.rst_n.value = 1
-    await ClockCycles(dut.clk, 5)
-
-
-async def send_frame_bytes(dut, frame: bytes) -> None:
-    for byte in frame:
-        for _ in range(256):
-            await FallingEdge(dut.clk)
-            if int(dut.rx_ready.value):
-                break
-        else:
-            raise AssertionError("RX stopped accepting bytes while a fast JOG was pending")
-        dut.rx_data.value = byte
-        dut.rx_valid.value = 1
-        await RisingEdge(dut.clk)
-        await FallingEdge(dut.clk)
-        dut.rx_valid.value = 0
-
-
-async def wait_until(dut, predicate, cycles: int, message: str) -> None:
-    for _ in range(cycles):
-        await RisingEdge(dut.clk)
-        await ReadOnly()
-        if predicate():
-            return
-    raise AssertionError(message)
-
-
-async def step_monitor(dut, observed: dict[str, int | bool]) -> None:
-    previous_x = 0
-    previous_y = 0
-    while True:
-        await RisingEdge(dut.clk)
-        await ReadOnly()
-        x_step = int(dut.step_out.value) & 1
-        y_step = (int(dut.step_out.value) >> 1) & 1
-        if x_step and not previous_x:
-            observed["x_rises"] = int(observed["x_rises"]) + 1
-        if y_step and not previous_y:
-            observed["y_rises"] = int(observed["y_rises"]) + 1
-        if x_step and y_step:
-            observed["overlap"] = True
-        previous_x = x_step
-        previous_y = y_step
-
-
-async def ack_monitor(dut, commands: list[int]) -> None:
-    while True:
-        await FallingEdge(dut.clk)
-        await ReadOnly()
-        if (
-            int(dut.frame_valid.value)
-            and int(dut.frame_ready.value)
-            and int(dut.frame_type.value) == HOST_ACK
-        ):
-            commands.append((int(dut.frame_payload.value) >> 8) & 0xFF)
-
-
-def build_snapshot() -> bytes:
-    return protocol.build_output_snapshot(
-        ptc_percent=[10] * 24,
-        fan_percent=[30] * 4,
-        solenoid=0,
-        xyz=(255, 1, 77),
-    )
-
-
-def build_jog(axis: int, direction: int, steps: int) -> bytes:
-    return protocol.build_motor_jog(
-        axis=axis,
-        raw_dir=direction,
-        speed_code=3,
-        steps=steps,
-    )
-
-
-@cocotb.test()
-async def fast_jog_runs_while_old_response_is_stalled(dut) -> None:
-    await start_and_reset(dut)
-    observed: dict[str, int | bool] = {
-        "x_rises": 0,
-        "y_rises": 0,
-        "overlap": False,
-    }
-    acks: list[int] = []
-    cocotb.start_soon(step_monitor(dut, observed))
-    cocotb.start_soon(ack_monitor(dut, acks))
-
-    await send_frame_bytes(
-        dut,
-        protocol.build_host_command(command=protocol.CommandId.GET_STATUS),
-    )
-    await wait_until(
-        dut,
-        lambda: int(dut.frame_valid.value) == 1,
-        64,
-        "GET_STATUS response did not enter the stalled TX slot",
-    )
-    assert int(dut.frame_type.value) == HOST_ACK
-    assert ((int(dut.frame_payload.value) >> 8) & 0xFF) == GET_STATUS
-    assert int(dut.request_ready.value) == 0
-
-    await send_frame_bytes(
-        dut,
-        protocol.build_host_command(command=protocol.CommandId.GET_STATUS),
-    )
-    await wait_until(
-        dut,
-        lambda: int(dut.request_valid.value) == 1
-        and int(dut.request_ready.value) == 0,
-        32,
-        "second ordinary request did not remain pending behind the old response",
-    )
-
-    await send_frame_bytes(dut, build_jog(axis=0, direction=1, steps=6))
-    await wait_until(
-        dut,
-        lambda: int(observed["x_rises"]) >= 1,
-        32,
-        "fast X JOG was blocked by command_inflight/TX backpressure",
-    )
-    assert ((int(dut.frame_payload.value) >> 8) & 0xFF) == GET_STATUS
-
-    await wait_until(
-        dut,
-        lambda: int(observed["x_rises"]) == 6,
-        256,
-        "X motion did not finish while TX remained stalled",
-    )
-    assert acks == []
-
-    await FallingEdge(dut.clk)
-    dut.frame_ready.value = 1
-    await wait_until(
-        dut,
-        lambda: JOG in acks,
-        512,
-        "pending JOG ACK did not drain after TX resumed",
-    )
-    assert acks[0] == GET_STATUS
-
-
-@cocotb.test()
-async def fast_jog_runs_while_core_is_non_idle(dut) -> None:
-    await start_and_reset(dut)
-    observed: dict[str, int | bool] = {
-        "x_rises": 0,
-        "y_rises": 0,
-        "overlap": False,
-    }
-    cocotb.start_soon(step_monitor(dut, observed))
-
-    await send_frame_bytes(dut, build_snapshot())
-    await wait_until(
-        dut,
-        lambda: int(dut.request_ready.value) == 0,
-        16,
-        "snapshot did not make the normal core path non-IDLE",
-    )
-    await send_frame_bytes(dut, build_jog(axis=1, direction=0, steps=3))
-    await wait_until(
-        dut,
-        lambda: int(observed["y_rises"]) == 3,
-        192,
-        "fast Y JOG was blocked by the normal snapshot state machine",
-    )
-    assert int(observed["x_rises"]) == 0
-
-
-@cocotb.test()
-async def x_ack_then_y_jog_runs_with_axis_overlap(dut) -> None:
-    await start_and_reset(dut)
-    dut.frame_ready.value = 1
-    observed: dict[str, int | bool] = {
-        "x_rises": 0,
-        "y_rises": 0,
-        "overlap": False,
-    }
-    acks: list[int] = []
-    cocotb.start_soon(step_monitor(dut, observed))
-    cocotb.start_soon(ack_monitor(dut, acks))
-
-    await send_frame_bytes(dut, build_jog(axis=0, direction=0, steps=40))
-    await wait_until(
-        dut,
-        lambda: len(acks) >= 1,
-        128,
-        "X JOG ACK did not follow the first X STEP",
-    )
-    assert acks[0] == JOG
-    assert int(observed["x_rises"]) >= 1
-
-    await send_frame_bytes(dut, build_jog(axis=1, direction=1, steps=6))
-    await wait_until(
-        dut,
-        lambda: len(acks) >= 2,
-        128,
-        "Y JOG ACK did not follow the first Y STEP",
-    )
-    assert acks[1] == JOG
-    assert int(observed["y_rises"]) >= 1
-
-    await wait_until(
-        dut,
-        lambda: int(observed["x_rises"]) == 40
-        and int(observed["y_rises"]) == 6,
-        512,
-        "X/Y independent pulse counts did not complete",
-    )
-    assert bool(observed["overlap"]), "X/Y STEP waveforms never overlapped"

+ 0 - 366
tests/cocotb/test_prod2u_p4_normal_v3_ack_only_top_e2e.py

@@ -1,366 +0,0 @@
-"""UART end-to-end checks for the unguarded independent JOG image."""
-
-from __future__ import annotations
-
-import sys
-from pathlib import Path
-
-import cocotb
-from cocotb.clock import Clock
-from cocotb.queue import Queue
-from cocotb.triggers import (
-    ClockCycles,
-    ReadOnly,
-    RisingEdge,
-    SimTimeoutError,
-    with_timeout,
-)
-
-
-ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(ROOT / "tools"))
-
-import prod2u_p4_protocol as protocol  # noqa: E402
-
-
-UART_CLKS_PER_BIT = 4
-FRAME_TIMEOUT_US = 5000
-TEMPERATURE_BYTE_TIMEOUT_US = 200
-QUIET_CYCLES = 128
-TEMPERATURE_FRAME_LEN = 35
-
-GOLDEN_DISABLE = bytes.fromhex("A55A02040500000000000000000426000000C4AE")
-GOLDEN_GET_STATUS = bytes.fromhex("A55A02040500000000000000000424000000AC43")
-GOLDEN_GET_TEMPERATURES = bytes.fromhex(
-    "A55A020405000000000000000004280000009E0C"
-)
-GOLDEN_GET_MOTOR_STATUS = bytes.fromhex(
-    "A55A0204110000000000000000083700000000000000347F"
-)
-GOLDEN_MARK_CLOSED = bytes.fromhex(
-    "A55A0204110000000000000000083600010000000000477D"
-)
-GOLDEN_LEGACY_TEMPERATURE_REQUEST = bytes.fromhex(
-    "A55A020405000000000000000004290000002A7A"
-)
-GOLDEN_X_JOG_65535 = bytes.fromhex(
-    "A55A02041100000000000000000835000003FFFF0000809A"
-)
-GOLDEN_X_JOG_801_REVERSE = bytes.fromhex(
-    "A55A02041100000000000000000835000103210300004A43"
-)
-GOLDEN_Y_JOG_800 = bytes.fromhex(
-    "A55A02041100000000000000000835010003200300003FC8"
-)
-
-
-async def send_uart_frame(dut, frame: bytes) -> None:
-    await RisingEdge(dut.sys_clk)
-    for byte in frame:
-        dut.host_uart_rx.value = 0
-        await ClockCycles(dut.sys_clk, UART_CLKS_PER_BIT)
-        for bit in range(8):
-            dut.host_uart_rx.value = (byte >> bit) & 1
-            await ClockCycles(dut.sys_clk, UART_CLKS_PER_BIT)
-        dut.host_uart_rx.value = 1
-        await ClockCycles(dut.sys_clk, UART_CLKS_PER_BIT)
-
-
-async def uart_byte_monitor(dut, output: Queue) -> None:
-    previous = 1
-    while True:
-        await RisingEdge(dut.sys_clk)
-        await ReadOnly()
-        if not dut.host_uart_tx.value.is_resolvable:
-            previous = 1
-            continue
-        current = int(dut.host_uart_tx.value)
-        if previous and not current:
-            await ClockCycles(
-                dut.sys_clk,
-                UART_CLKS_PER_BIT + (UART_CLKS_PER_BIT // 2),
-            )
-            value = 0
-            for bit in range(8):
-                await ReadOnly()
-                assert dut.host_uart_tx.value.is_resolvable
-                value |= int(dut.host_uart_tx.value) << bit
-                await ClockCycles(dut.sys_clk, UART_CLKS_PER_BIT)
-            output.put_nowait(value)
-            previous = 1
-        else:
-            previous = current
-
-
-async def step_monitor(dut, observed: dict[str, int | bool]) -> None:
-    previous_x = 0
-    previous_y = 0
-    while True:
-        await RisingEdge(dut.sys_clk)
-        await ReadOnly()
-        x_value = int(dut.x_step.value)
-        y_value = int(dut.y_step.value)
-        if x_value and not previous_x:
-            observed["x_rises"] = int(observed["x_rises"]) + 1
-        if y_value and not previous_y:
-            observed["y_rises"] = int(observed["y_rises"]) + 1
-        if x_value and y_value:
-            observed["overlap"] = True
-        previous_x = x_value
-        previous_y = y_value
-
-
-async def next_uart_byte(queue: Queue, timeout_us: int = FRAME_TIMEOUT_US) -> int:
-    return await with_timeout(queue.get(), timeout_us, "us")
-
-
-async def read_uart_frame(queue: Queue) -> protocol.P4Frame:
-    raw = bytearray()
-    for _ in range(protocol.HEADER_LEN):
-        raw.append(await next_uart_byte(queue))
-    assert raw[:2] == protocol.MAGIC, f"unexpected UART prefix {raw.hex()}"
-    for _ in range(raw[13] + protocol.CRC_LEN):
-        raw.append(await next_uart_byte(queue))
-    return protocol.decode_frame(bytes(raw))
-
-
-async def read_temperature_frame(dut, queue: Queue) -> bytes:
-    raw = bytearray()
-    try:
-        for _ in range(TEMPERATURE_FRAME_LEN):
-            raw.append(
-                await next_uart_byte(queue, TEMPERATURE_BYTE_TIMEOUT_US)
-            )
-    except SimTimeoutError as exc:
-        raise AssertionError(
-            "temperature UART timeout "
-            f"raw={raw.hex()} "
-            f"read_state={int(dut.u_dut.u_temperature_read.state.value)} "
-            f"i2c_state={int(dut.u_dut.u_temperature_i2c.state.value)} "
-            f"i2c_error={int(dut.u_dut.u_temperature_i2c.response_error.value)} "
-            f"scl={dut.temp_scl.value} sda={dut.temp_sda.value} "
-            f"scl_low={int(dut.u_dut.temperature_scl_drive_low.value)} "
-            f"sda_low={int(dut.u_dut.temperature_sda_drive_low.value)} "
-            f"read_done={int(dut.u_dut.temperature_read_done.value)} "
-            f"bus_error={int(dut.u_dut.temperature_bus_error.value)} "
-            f"scan_active={int(dut.u_ct7428_slave.scan_active.value)} "
-            f"scan_count={int(dut.u_ct7428_slave.scan_count.value)} "
-            f"transaction_error={int(dut.u_ct7428_slave.transaction_error.value)}"
-        ) from exc
-    return protocol.decode_temperature_response(bytes(raw))
-
-
-async def send_and_read_ack(dut, queue: Queue, request: bytes) -> protocol.HostAck:
-    await send_uart_frame(dut, request)
-    frame = await read_uart_frame(queue)
-    assert frame.frame_type == protocol.FrameType.HOST_ACK
-    return protocol.decode_host_ack(frame)
-
-
-async def send_and_read_temperatures(dut, queue: Queue, request: bytes) -> bytes:
-    await send_uart_frame(dut, request)
-    return await read_temperature_frame(dut, queue)
-
-
-async def assert_uart_quiet(dut, queue: Queue, label: str) -> None:
-    await ClockCycles(dut.sys_clk, QUIET_CYCLES)
-    assert queue.qsize() == 0, f"unexpected follow-up bytes after {label}"
-
-
-def assert_request_goldens() -> None:
-    assert protocol.build_host_command(command=protocol.CommandId.GET_STATUS) == (
-        GOLDEN_GET_STATUS
-    )
-    assert protocol.build_host_command(command=protocol.CommandId.DISABLE) == (
-        GOLDEN_DISABLE
-    )
-    assert protocol.build_get_temperatures() == GOLDEN_GET_TEMPERATURES
-    assert protocol.build_get_motor_status() == GOLDEN_GET_MOTOR_STATUS
-    assert protocol.build_mark_closed(axis=0, close_dir=1) == GOLDEN_MARK_CLOSED
-    assert protocol.build_motor_jog(
-        axis=0, raw_dir=0, speed_code=3, steps=0xFFFF
-    ) == GOLDEN_X_JOG_65535
-    assert protocol.build_motor_jog(
-        axis=0, raw_dir=1, speed_code=3, steps=801
-    ) == GOLDEN_X_JOG_801_REVERSE
-    assert protocol.build_motor_jog(
-        axis=1, raw_dir=0, speed_code=3, steps=800
-    ) == GOLDEN_Y_JOG_800
-
-
-async def read_motion_status(dut, queue: Queue) -> bytes:
-    ack = await send_and_read_ack(dut, queue, GOLDEN_GET_MOTOR_STATUS)
-    assert ack.ok is True
-    assert ack.command == protocol.MotionOpcode.GET_MOTOR_STATUS
-    assert ack.response_type == protocol.FrameType.MOTION_STATUS
-    frame = await read_uart_frame(queue)
-    assert frame.frame_type == protocol.FrameType.MOTION_STATUS
-    return frame.payload
-
-
-@cocotb.test()
-async def ack_only_uart_contract(dut) -> None:
-    assert_request_goldens()
-    cocotb.start_soon(Clock(dut.sys_clk, 10, unit="ns").start())
-    received: Queue = Queue()
-    observed: dict[str, int | bool] = {
-        "x_rises": 0,
-        "y_rises": 0,
-        "overlap": False,
-    }
-    cocotb.start_soon(uart_byte_monitor(dut, received))
-    cocotb.start_soon(step_monitor(dut, observed))
-
-    for _ in range(32):
-        await RisingEdge(dut.sys_clk)
-        if int(dut.sys_rst_n_debug.value):
-            break
-    assert int(dut.sys_rst_n_debug.value) == 1
-    assert int(dut.motor_en_n.value) == 0
-    await ClockCycles(dut.sys_clk, 128)
-    assert received.qsize() == 0
-
-    early_temperatures = await send_and_read_temperatures(
-        dut,
-        received,
-        GOLDEN_GET_TEMPERATURES,
-    )
-    assert early_temperatures == b"\xff" * 27
-    assert int(dut.u_ct7428_slave.scan_count.value) == 0
-    await assert_uart_quiet(dut, received, "early temperature response")
-
-    await with_timeout(
-        RisingEdge(dut.temperature_powerup_ready_debug),
-        FRAME_TIMEOUT_US,
-        "us",
-    )
-
-    temperatures = await send_and_read_temperatures(
-        dut,
-        received,
-        GOLDEN_GET_TEMPERATURES,
-    )
-    assert temperatures == bytes(range(27))
-    assert int(dut.u_ct7428_slave.scan_count.value) == 1
-    assert int(dut.u_ct7428_slave.transaction_error.value) == 0
-    assert int(dut.u_ct7428_slave.address_49_count.value) == 9
-    assert int(dut.u_ct7428_slave.address_48_count.value) == 9
-    assert int(dut.u_ct7428_slave.address_4b_count.value) == 9
-    assert int(dut.u_ct7428_slave.read_ack_count.value) == 27
-    assert int(dut.u_ct7428_slave.read_nack_count.value) == 27
-
-    dut.mixed_nack.value = 1
-    dut.nack_slot.value = 10
-    mixed_temperatures = await send_and_read_temperatures(
-        dut,
-        received,
-        GOLDEN_GET_TEMPERATURES,
-    )
-    expected_mixed = bytearray(range(27))
-    expected_mixed[10] = 0xFF
-    assert mixed_temperatures == bytes(expected_mixed)
-    assert int(dut.u_ct7428_slave.scan_count.value) == 2
-    assert int(dut.u_ct7428_slave.transaction_error.value) == 0
-    assert int(dut.u_ct7428_slave.address_49_count.value) == 9
-    assert int(dut.u_ct7428_slave.address_48_count.value) == 9
-    assert int(dut.u_ct7428_slave.address_4b_count.value) == 9
-    assert int(dut.u_ct7428_slave.read_ack_count.value) == 26
-    assert int(dut.u_ct7428_slave.read_nack_count.value) == 26
-    dut.mixed_nack.value = 0
-
-    dut.force_sda_low.value = 1
-    bus_error_ack = await send_and_read_ack(
-        dut,
-        received,
-        GOLDEN_GET_TEMPERATURES,
-    )
-    assert bus_error_ack.ok is False
-    assert bus_error_ack.command == protocol.CommandId.GET_TEMPERATURES
-    assert bus_error_ack.status == protocol.StatusCode.TEMPERATURE_BUS_ERROR
-    dut.force_sda_low.value = 0
-    await assert_uart_quiet(dut, received, "temperature bus error ACK")
-
-    status_ack = await send_and_read_ack(dut, received, GOLDEN_GET_STATUS)
-    assert status_ack.ok is True
-    assert status_ack.status == protocol.StatusCode.OK
-
-    for request, command in (
-        (GOLDEN_LEGACY_TEMPERATURE_REQUEST, 0x29),
-        (GOLDEN_MARK_CLOSED, protocol.MotionOpcode.MARK_CLOSED),
-    ):
-        ack = await send_and_read_ack(dut, received, request)
-        assert ack.ok is False
-        assert int(ack.command) == int(command)
-        assert ack.status == protocol.StatusCode.UNSUPPORTED_IN_PROFILE
-
-    initial_status = await read_motion_status(dut, received)
-    assert initial_status[0] & 0x03 == 0x02
-    assert initial_status[1:3] == b"\x00\x00"
-    assert initial_status[3:9] == b"\xff" * 6
-    assert initial_status[9] == 0
-
-    dut.x_limit_raw.value = 1
-    before_x = int(observed["x_rises"])
-    x_ack = await send_and_read_ack(dut, received, GOLDEN_X_JOG_65535)
-    assert x_ack.ok is True
-    assert int(observed["x_rises"]) > before_x
-    assert int(dut.x_remaining_debug.value) == 0xFFFF
-    assert int(dut.x_dir.value) == 0
-    assert int(dut.motor_en_n.value) == 0
-
-    dut.y_limit_raw.value = 1
-    before_y = int(observed["y_rises"])
-    x_before_y = int(observed["x_rises"])
-    y_ack = await send_and_read_ack(dut, received, GOLDEN_Y_JOG_800)
-    assert y_ack.ok is True
-    assert int(observed["y_rises"]) > before_y
-    assert int(observed["x_rises"]) > x_before_y
-    assert bool(observed["overlap"])
-    assert int(dut.y_remaining_debug.value) == 800
-    assert int(dut.y_dir.value) == 0
-
-    snapshot = protocol.build_output_snapshot(
-        ptc_percent=[7] * 24,
-        fan_percent=[35] * 4,
-        solenoid=100,
-        xyz=(17, 222, 99),
-    )
-    x_dir_before = int(dut.x_dir.value)
-    y_dir_before = int(dut.y_dir.value)
-    snapshot_ack = await send_and_read_ack(dut, received, snapshot)
-    assert snapshot_ack.ok is True
-    assert snapshot_ack.result_flags == 0x01
-    assert int(dut.x_dir.value) == x_dir_before
-    assert int(dut.y_dir.value) == y_dir_before
-    assert int(dut.solenoid_percent_debug.value) == 100
-
-    before_replacement = int(observed["x_rises"])
-    replacement_ack = await send_and_read_ack(
-        dut, received, GOLDEN_X_JOG_801_REVERSE
-    )
-    assert replacement_ack.ok is True
-    assert int(observed["x_rises"]) > before_replacement
-    assert int(dut.x_dir.value) == 1
-    assert int(dut.x_remaining_debug.value) == 801
-
-    before_disable = (
-        int(observed["x_rises"]),
-        int(observed["y_rises"]),
-    )
-    disable_ack = await send_and_read_ack(dut, received, GOLDEN_DISABLE)
-    assert disable_ack.ok is True
-    assert int(dut.disabled_debug.value) == 1
-    assert int(dut.motor_en_n.value) == 0
-    assert int(dut.ptc_percent_debug.value) == 0
-    assert int(dut.fan_percent_debug.value) == int.from_bytes(bytes((30,)) * 4, "little")
-    assert int(dut.solenoid_percent_debug.value) == 0
-    await ClockCycles(dut.sys_clk, 30000)
-    assert int(observed["x_rises"]) > before_disable[0]
-    assert int(observed["y_rises"]) > before_disable[1]
-
-    final_status = await read_motion_status(dut, received)
-    assert final_status[0] & 0x03 == 0x02
-    assert final_status[1:3] == b"\x00\x00"
-    assert final_status[3:9] == b"\xff" * 6
-    assert final_status[9] == 0
-    await assert_uart_quiet(dut, received, "final MOTION_STATUS")

Разница между файлами не показана из-за своего большого размера
+ 5 - 21
tests/formal/README.md


+ 0 - 21
tests/formal/prod2u_p4_axis_cdc_structure.sby

@@ -1,21 +0,0 @@
-[tasks]
-prove
-cover
-
-[options]
-prove: mode prove
-prove: depth 24
-cover: mode cover
-cover: depth 24
-
-[engines]
-prove: abc pdr
-cover: smtbmc yices
-
-[script]
-read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_axis_cdc_structure_formal.v
-prep -top prod2u_p4_axis_cdc_structure_formal
-
-[files]
-../../src/rtl/prod2u_p4_axis_executor.v
-prod2u_p4_axis_cdc_structure_formal.v

+ 0 - 36
tests/formal/prod2u_p4_axis_cdc_structure_formal.v

@@ -1,36 +0,0 @@
-`timescale 1ns/1ps
-`default_nettype none
-
-module prod2u_p4_axis_cdc_structure_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    (* anyseq *) reg command_start;
-    (* anyseq *) reg command_dir;
-    (* anyseq *) reg [15:0] command_steps;
-    (* anyseq *) reg legacy_limit;
-    wire step_a, dir_a, started_a;
-    wire step_b, dir_b, started_b;
-
-    prod2u_p4_axis_executor #(.DIR_SETUP_CYCLES(2), .STEP_HALF_CYCLES(2)) a (
-        .clk(clk), .rst_n(rst_n), .command_start(command_start),
-        .command_dir(command_dir), .command_steps(command_steps),
-        .step_out(step_a), .dir_out(dir_a), .started_pulse(started_a)
-    );
-    prod2u_p4_axis_executor #(.DIR_SETUP_CYCLES(2), .STEP_HALF_CYCLES(2)) b (
-        .clk(clk), .rst_n(rst_n), .command_start(command_start),
-        .command_dir(command_dir), .command_steps(command_steps),
-        .step_out(step_b), .dir_out(dir_b), .started_pulse(started_b)
-    );
-
-    always @(posedge clk) begin
-        rst_n <= 1'b1;
-        if (rst_n) begin
-            assert(step_a == step_b);
-            assert(dir_a == dir_b);
-            assert(started_a == started_b);
-        end
-        cover(rst_n && legacy_limit && started_a);
-    end
-endmodule
-
-`default_nettype wire

+ 0 - 21
tests/formal/prod2u_p4_axis_force_jog_limit_ignore.sby

@@ -1,21 +0,0 @@
-[tasks]
-prove
-cover
-
-[options]
-prove: mode prove
-prove: depth 32
-cover: mode cover
-cover: depth 32
-
-[engines]
-prove: abc pdr
-cover: smtbmc yices
-
-[script]
-read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_axis_force_jog_limit_ignore_formal.v
-prep -top prod2u_p4_axis_force_jog_limit_ignore_formal
-
-[files]
-../../src/rtl/prod2u_p4_axis_executor.v
-prod2u_p4_axis_force_jog_limit_ignore_formal.v

+ 0 - 39
tests/formal/prod2u_p4_axis_force_jog_limit_ignore_formal.v

@@ -1,39 +0,0 @@
-`timescale 1ns/1ps
-`default_nettype none
-
-module prod2u_p4_axis_force_jog_limit_ignore_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    reg past_valid = 1'b0;
-    (* anyseq *) reg command_start;
-    (* anyseq *) reg command_dir;
-    (* anyseq *) reg [15:0] command_steps;
-    (* anyseq *) reg legacy_limit_a;
-    (* anyseq *) reg legacy_limit_b;
-    wire step_a, dir_a, started_a;
-    wire step_b, dir_b, started_b;
-
-    prod2u_p4_axis_executor #(.DIR_SETUP_CYCLES(3), .STEP_HALF_CYCLES(2)) a (
-        .clk(clk), .rst_n(rst_n), .command_start(command_start),
-        .command_dir(command_dir), .command_steps(command_steps),
-        .step_out(step_a), .dir_out(dir_a), .started_pulse(started_a)
-    );
-    prod2u_p4_axis_executor #(.DIR_SETUP_CYCLES(3), .STEP_HALF_CYCLES(2)) b (
-        .clk(clk), .rst_n(rst_n), .command_start(command_start),
-        .command_dir(command_dir), .command_steps(command_steps),
-        .step_out(step_b), .dir_out(dir_b), .started_pulse(started_b)
-    );
-
-    always @(posedge clk) begin
-        rst_n <= 1'b1;
-        past_valid <= 1'b1;
-        if (rst_n) begin
-            assert(step_a == step_b);
-            assert(dir_a == dir_b);
-            assert(started_a == started_b);
-        end
-        cover(rst_n && (legacy_limit_a != legacy_limit_b) && started_a);
-    end
-endmodule
-
-`default_nettype wire

+ 0 - 21
tests/formal/prod2u_p4_axis_force_jog_replace.sby

@@ -1,21 +0,0 @@
-[tasks]
-bmc
-cover
-
-[options]
-bmc: mode bmc
-bmc: depth 32
-cover: mode cover
-cover: depth 32
-
-[engines]
-bmc: smtbmc yices
-cover: smtbmc yices
-
-[script]
-read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_axis_force_jog_replace_formal.v
-prep -top prod2u_p4_axis_force_jog_replace_formal
-
-[files]
-../../src/rtl/prod2u_p4_axis_executor.v
-prod2u_p4_axis_force_jog_replace_formal.v

+ 0 - 44
tests/formal/prod2u_p4_axis_force_jog_replace_formal.v

@@ -1,44 +0,0 @@
-`timescale 1ns/1ps
-`default_nettype none
-
-module prod2u_p4_axis_force_jog_replace_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    reg past_valid = 1'b0;
-    (* anyseq *) reg command_start;
-    (* anyseq *) reg command_dir;
-    (* anyseq *) reg [15:0] command_steps;
-    wire step_out;
-    wire dir_out;
-    wire started_pulse;
-
-    prod2u_p4_axis_executor #(
-        .DIR_SETUP_CYCLES(3),
-        .STEP_HALF_CYCLES(2)
-    ) dut (
-        .clk(clk), .rst_n(rst_n),
-        .command_start(command_start), .command_dir(command_dir),
-        .command_steps(command_steps), .step_out(step_out),
-        .dir_out(dir_out), .started_pulse(started_pulse)
-    );
-
-    always @(posedge clk) begin
-        rst_n <= 1'b1;
-        past_valid <= 1'b1;
-
-        if (rst_n) begin
-            assert(!started_pulse || step_out);
-        end
-        if (past_valid && $past(rst_n) && $past(command_start)) begin
-            assert(!step_out);
-            assert(!started_pulse);
-            assert(dir_out == $past(command_dir));
-        end
-
-        cover(past_valid && $past(step_out) && $past(command_start) &&
-            !step_out && (dir_out == $past(command_dir)));
-        cover(rst_n && started_pulse && step_out);
-    end
-endmodule
-
-`default_nettype wire

+ 0 - 21
tests/formal/prod2u_p4_axis_safety.sby

@@ -1,21 +0,0 @@
-[tasks]
-prove
-cover
-
-[options]
-prove: mode prove
-prove: depth 32
-cover: mode cover
-cover: depth 32
-
-[engines]
-prove: abc pdr
-cover: smtbmc yices
-
-[script]
-read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_axis_safety_formal.v
-prep -top prod2u_p4_axis_safety_formal
-
-[files]
-../../src/rtl/prod2u_p4_axis_executor.v
-prod2u_p4_axis_safety_formal.v

+ 0 - 169
tests/formal/prod2u_p4_axis_safety_formal.v

@@ -1,169 +0,0 @@
-`timescale 1ns/1ps
-`default_nettype none
-
-module prod2u_p4_axis_safety_formal;
-    localparam integer DUT_DIR_SETUP_CYCLES = 3;
-    localparam integer DUT_STEP_HALF_CYCLES = 2;
-
-    localparam integer SPEC_DIR_SETUP_CYCLES = DUT_DIR_SETUP_CYCLES;
-    localparam integer SPEC_STEP_HALF_CYCLES = DUT_STEP_HALF_CYCLES;
-
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    (* anyseq *) reg command_start;
-    (* anyseq *) reg command_dir;
-    (* anyseq *) reg [15:0] command_steps;
-    wire step_out;
-    wire dir_out;
-    wire started_pulse;
-    wire [1:0] dut_motion_phase;
-    wire [31:0] dut_phase_counter;
-    wire [15:0] dut_remaining_steps;
-
-    // Independent observable oracle. It deliberately does not mirror the
-    // production four-state encoding: setup, high, and low use mutually
-    // exclusive countdowns plus an explicit STEP register.
-    reg spec_active = 1'b0;
-    reg spec_step = 1'b0;
-    reg spec_dir = 1'b0;
-    reg spec_started = 1'b0;
-    reg [15:0] spec_steps_left = 16'd0;
-    reg [1:0] spec_setup_left = 2'd0;
-    reg [1:0] spec_high_left = 2'd0;
-    reg [1:0] spec_low_left = 2'd0;
-    reg saw_ffff_command = 1'b0;
-    reg saw_three_command = 1'b0;
-    reg [1:0] three_rises = 2'd0;
-    reg previous_step = 1'b0;
-
-    prod2u_p4_axis_executor #(
-        .DIR_SETUP_CYCLES(DUT_DIR_SETUP_CYCLES),
-        .STEP_HALF_CYCLES(DUT_STEP_HALF_CYCLES)
-    ) dut (
-        .clk(clk), .rst_n(rst_n),
-        .command_start(command_start), .command_dir(command_dir),
-        .command_steps(command_steps), .step_out(step_out),
-        .dir_out(dir_out), .started_pulse(started_pulse),
-        .formal_motion_phase(dut_motion_phase),
-        .formal_phase_counter(dut_phase_counter),
-        .formal_remaining_steps(dut_remaining_steps)
-    );
-
-    always @(posedge clk) begin
-        rst_n <= 1'b1;
-        previous_step <= step_out;
-        if (rst_n && command_start) begin
-            // RAW_U16_TRUSTED_HOST_NO_CPLD_CAP: zero is rejected by the host.
-            assume(command_steps != 16'd0);
-        end
-
-        if (!rst_n) begin
-            spec_active <= 1'b0;
-            spec_step <= 1'b0;
-            spec_dir <= 1'b0;
-            spec_started <= 1'b0;
-            spec_steps_left <= 16'd0;
-            spec_setup_left <= 2'd0;
-            spec_high_left <= 2'd0;
-            spec_low_left <= 2'd0;
-            saw_ffff_command <= 1'b0;
-            saw_three_command <= 1'b0;
-            three_rises <= 2'd0;
-            previous_step <= 1'b0;
-        end else begin
-            spec_started <= 1'b0;
-            if (saw_three_command && step_out && !previous_step) begin
-                three_rises <= three_rises + 1'b1;
-            end
-            if (command_start) begin
-                spec_step <= 1'b0;
-                spec_dir <= command_dir;
-                spec_steps_left <= command_steps;
-                spec_high_left <= 2'd0;
-                spec_low_left <= 2'd0;
-                saw_ffff_command <= (command_steps == 16'hffff);
-                saw_three_command <= (command_steps == 16'd3);
-                three_rises <= 2'd0;
-                spec_active <= 1'b1;
-                spec_setup_left <= SPEC_DIR_SETUP_CYCLES;
-            end else if (spec_active) begin
-                if (spec_setup_left != 0) begin
-                    if (spec_setup_left == 1) begin
-                        spec_setup_left <= 2'd0;
-                        spec_step <= 1'b1;
-                        spec_high_left <= SPEC_STEP_HALF_CYCLES;
-                        spec_started <= 1'b1;
-                    end else begin
-                        spec_setup_left <= spec_setup_left - 1'b1;
-                    end
-                end else if (spec_step) begin
-                    if (spec_high_left == 1) begin
-                        spec_step <= 1'b0;
-                        spec_high_left <= 2'd0;
-                        spec_low_left <= SPEC_STEP_HALF_CYCLES;
-                    end else begin
-                        spec_high_left <= spec_high_left - 1'b1;
-                    end
-                end else if (spec_low_left != 0) begin
-                    if (spec_low_left == 1) begin
-                        spec_low_left <= 2'd0;
-                        if (spec_steps_left <= 16'd1) begin
-                            spec_active <= 1'b0;
-                            spec_steps_left <= 16'd0;
-                        end else begin
-                            spec_steps_left <= spec_steps_left - 16'd1;
-                            spec_step <= 1'b1;
-                            spec_high_left <= SPEC_STEP_HALF_CYCLES;
-                        end
-                    end else begin
-                        spec_low_left <= spec_low_left - 1'b1;
-                    end
-                end
-            end
-        end
-
-        if (!rst_n) begin
-            assert(!step_out);
-            assert(!started_pulse);
-        end else begin
-            assert(step_out == spec_step);
-            assert(dir_out == spec_dir);
-            assert(started_pulse == spec_started);
-            assert(!started_pulse || step_out);
-            assert(dut_remaining_steps == spec_steps_left);
-            if (!spec_active) begin
-                assert(dut_motion_phase == 2'd0);
-                assert(dut_phase_counter == 32'd0);
-                assert(spec_setup_left == 2'd0);
-                assert(!spec_step);
-                assert(spec_high_left == 2'd0);
-                assert(spec_low_left == 2'd0);
-            end else if (spec_setup_left != 2'd0) begin
-                assert(dut_motion_phase == 2'd1);
-                assert(dut_phase_counter == (spec_setup_left - 1'b1));
-                assert(!spec_step);
-                assert(spec_high_left == 2'd0);
-                assert(spec_low_left == 2'd0);
-            end else if (spec_step) begin
-                assert(dut_motion_phase == 2'd2);
-                assert(dut_phase_counter == (spec_high_left - 1'b1));
-                assert(spec_high_left != 2'd0);
-                assert(spec_low_left == 2'd0);
-            end else if (spec_low_left != 2'd0) begin
-                assert(dut_motion_phase == 2'd3);
-                assert(dut_phase_counter == (spec_low_left - 1'b1));
-                assert(spec_high_left == 2'd0);
-            end else begin
-                assert(1'b0);
-            end
-        end
-
-        cover(rst_n && started_pulse && step_out);
-        cover(rst_n && command_start && step_out);
-        cover(rst_n && saw_ffff_command && started_pulse);
-        cover(rst_n && saw_three_command && !spec_active &&
-            (three_rises == 2'd3));
-    end
-endmodule
-
-`default_nettype wire

+ 0 - 27
tests/formal/prod2u_p4_core_disable_motor_safety.sby

@@ -1,27 +0,0 @@
-[tasks]
-bmc
-cover
-
-[options]
-bmc: mode bmc
-bmc: depth 192
-cover: mode cover
-cover: depth 192
-
-[engines]
-bmc: smtbmc yices
-cover: smtbmc yices
-
-[script]
-read_verilog -formal binary921_crc16.v prod2u_p4_normal_v3_output_state.v prod2u_p4_normal_v3_watchdog.v prod2u_p4_axis_executor.v prod2u_p4_motor_hub.v prod2u_p4_response_scheduler.v prod2u_p4_normal_v3_core.v prod2u_p4_core_disable_motor_safety_formal.v
-prep -top prod2u_p4_core_disable_motor_safety_formal
-
-[files]
-../../src/rtl/binary921_crc16.v
-../../src/rtl/prod2u_p4_normal_v3_output_state.v
-../../src/rtl/prod2u_p4_normal_v3_watchdog.v
-../../src/rtl/prod2u_p4_axis_executor.v
-../../src/rtl/prod2u_p4_motor_hub.v
-../../src/rtl/prod2u_p4_response_scheduler.v
-../../src/rtl/prod2u_p4_normal_v3_core.v
-prod2u_p4_core_disable_motor_safety_formal.v

+ 0 - 247
tests/formal/prod2u_p4_core_disable_motor_safety_formal.v

@@ -1,247 +0,0 @@
-`timescale 1ns/1ps
-`default_nettype none
-
-module prod2u_p4_core_disable_motor_safety_formal;
-    localparam [7:0] FT_HOST_CMD = 8'h05;
-    localparam [7:0] FT_HOST_BATCH_CMD = 8'h07;
-    localparam [7:0] FT_MOTION_CMD = 8'h11;
-
-    localparam [3:0] PH_JOG_SEND = 4'd0;
-    localparam [3:0] PH_WAIT_FIRST_STEP = 4'd1;
-    localparam [3:0] PH_SNAPSHOT_SEND = 4'd2;
-    localparam [3:0] PH_WAIT_SNAPSHOT = 4'd3;
-    localparam [3:0] PH_DISABLE_SEND = 4'd4;
-    localparam [3:0] PH_WAIT_SAFE = 4'd5;
-    localparam [3:0] PH_WAIT_POST_DISABLE_STEP = 4'd6;
-    localparam [3:0] PH_DONE = 4'd7;
-
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    reg [3:0] phase = PH_JOG_SEND;
-    reg previous_x_step = 1'b0;
-    reg [271:0] request_payload;
-
-    wire request_valid = (phase == PH_SNAPSHOT_SEND) ||
-        (phase == PH_DISABLE_SEND);
-    wire fast_jog_valid = (phase == PH_JOG_SEND);
-    wire [7:0] request_type = (phase == PH_SNAPSHOT_SEND) ?
-        FT_HOST_BATCH_CMD : ((phase == PH_DISABLE_SEND) ?
-        FT_HOST_CMD : FT_MOTION_CMD);
-    wire [5:0] request_length = (phase == PH_SNAPSHOT_SEND) ?
-        6'd34 : ((phase == PH_DISABLE_SEND) ? 6'd4 : 6'd8);
-    wire request_ready;
-    wire [191:0] ptc_percent;
-    wire [31:0] fan_percent;
-    wire [7:0] solenoid_percent;
-    wire [15:0] state_hash16;
-    wire [2:0] step_out;
-    wire [2:0] dir_out;
-    wire en_n;
-    wire disabled;
-    wire watchdog_timeout;
-    wire [1:0] reference_started;
-    wire [2:0] reference_step_out;
-    wire [2:0] reference_dir_out;
-    wire frame_valid;
-    wire [7:0] frame_type;
-    wire [7:0] frame_payload_len;
-    wire [143:0] frame_payload;
-    reg first_step_seen = 1'b0;
-    reg jog_ack_seen = 1'b0;
-
-    always @(*) begin
-        request_payload = 272'd0;
-        case (phase)
-            PH_JOG_SEND: begin
-                request_payload[7:0] = 8'h35;
-                request_payload[15:8] = 8'd0;
-                request_payload[23:16] = 8'd1;
-                request_payload[31:24] = 8'd3;
-                request_payload[47:32] = 16'hffff;
-            end
-
-            PH_SNAPSHOT_SEND: begin
-                request_payload[7:0] = 8'h2a;
-                request_payload[15:8] = 8'd0;
-                request_payload[23:16] = 8'd55;
-                request_payload[26 * 8 +: 8] = 8'd40;
-                request_payload[27 * 8 +: 8] = 8'd41;
-                request_payload[28 * 8 +: 8] = 8'd42;
-                request_payload[29 * 8 +: 8] = 8'd43;
-                request_payload[30 * 8 +: 8] = 8'd100;
-            end
-
-            PH_DISABLE_SEND: begin
-                request_payload[7:0] = 8'h26;
-            end
-
-            default: begin
-                request_payload = 272'd0;
-            end
-        endcase
-    end
-
-    prod2u_p4_normal_v3_core #(
-        .CLK_HZ(1),
-        .WATCHDOG_SECONDS(64),
-        .DIR_SETUP_CYCLES(2),
-        .STEP_HALF_CYCLES(2)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(16'h3501),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(2'd0),
-        .fast_jog_dir(1'b1),
-        .fast_jog_steps(16'hffff),
-        .frame_valid(frame_valid),
-        .frame_ready(1'b1),
-        .frame_type(frame_type),
-        .frame_payload_len(frame_payload_len),
-        .frame_payload(frame_payload),
-        .ptc_percent(ptc_percent),
-        .fan_percent(fan_percent),
-        .solenoid_percent(solenoid_percent),
-        .state_hash16(state_hash16),
-        .step_out(step_out),
-        .dir_out(dir_out),
-        .en_n(en_n),
-        .disabled(disabled),
-        .watchdog_timeout(watchdog_timeout)
-    );
-
-    prod2u_p4_motor_hub #(
-        .DIR_SETUP_CYCLES(2),
-        .STEP_HALF_CYCLES(2)
-    ) reference_motors (
-        .clk(clk),
-        .rst_n(rst_n),
-        .jog_start(fast_jog_valid),
-        .jog_axis(2'd0),
-        .jog_dir(1'b1),
-        .jog_steps(16'hffff),
-        .axis_started_pulse(reference_started),
-        .step_out(reference_step_out),
-        .dir_out(reference_dir_out)
-    );
-
-    always @(posedge clk) begin
-        rst_n <= 1'b1;
-        previous_x_step <= step_out[0];
-
-        if (!rst_n) begin
-            phase <= PH_JOG_SEND;
-            previous_x_step <= 1'b0;
-            first_step_seen <= 1'b0;
-            jog_ack_seen <= 1'b0;
-        end else begin
-            assert(en_n == 1'b0);
-            assert(step_out == reference_step_out);
-            assert(dir_out == reference_dir_out);
-            assert(step_out[2] == 1'b0);
-            assert(dir_out[2] == 1'b0);
-
-            if (reference_started[0]) begin
-                first_step_seen <= 1'b1;
-            end
-
-            if (!jog_ack_seen && !first_step_seen) begin
-                assert(!frame_valid);
-            end
-            if (!jog_ack_seen && frame_valid) begin
-                assert(first_step_seen);
-                assert(frame_type == 8'h06);
-                assert(frame_payload_len == 8'd8);
-                assert(frame_payload[7:0] == 8'h01);
-                assert(frame_payload[15:8] == 8'h35);
-                assert(frame_payload[23:16] == 8'h00);
-                jog_ack_seen <= 1'b1;
-            end
-
-            case (phase)
-                PH_JOG_SEND: begin
-                    assert(disabled);
-                    assert(!watchdog_timeout);
-                    phase <= PH_WAIT_FIRST_STEP;
-                end
-
-                PH_WAIT_FIRST_STEP: begin
-                    assert(disabled);
-                    assert(!watchdog_timeout);
-                    if (step_out[0]) begin
-                        assert(dir_out[0]);
-                        phase <= PH_SNAPSHOT_SEND;
-                    end
-                end
-
-                PH_SNAPSHOT_SEND: begin
-                    assert(disabled);
-                    assert(!watchdog_timeout);
-                    if (request_valid && request_ready) begin
-                        phase <= PH_WAIT_SNAPSHOT;
-                    end
-                end
-
-                PH_WAIT_SNAPSHOT: begin
-                    assert(!watchdog_timeout);
-                    if (request_ready && !disabled &&
-                        (ptc_percent[7:0] == 8'd55) &&
-                        (fan_percent == {8'd43, 8'd42, 8'd41, 8'd40}) &&
-                        (solenoid_percent == 8'd100)) begin
-                        phase <= PH_DISABLE_SEND;
-                    end
-                end
-
-                PH_DISABLE_SEND: begin
-                    assert(!disabled);
-                    assert(!watchdog_timeout);
-                    if (request_valid && request_ready) begin
-                        phase <= PH_WAIT_SAFE;
-                    end
-                end
-
-                PH_WAIT_SAFE: begin
-                    if (disabled) begin
-                        assert(!watchdog_timeout);
-                        assert(state_hash16 == 16'he177);
-                        assert(ptc_percent == 192'd0);
-                        assert(fan_percent == {4{8'd30}});
-                        assert(solenoid_percent == 8'd0);
-                        phase <= PH_WAIT_POST_DISABLE_STEP;
-                    end
-                end
-
-                PH_WAIT_POST_DISABLE_STEP: begin
-                    assert(disabled);
-                    assert(!watchdog_timeout);
-                    assert(state_hash16 == 16'he177);
-                    assert(ptc_percent == 192'd0);
-                    assert(fan_percent == {4{8'd30}});
-                    assert(solenoid_percent == 8'd0);
-                    if (step_out[0] && !previous_x_step) begin
-                        phase <= PH_DONE;
-                    end
-                end
-
-                default: begin
-                    assert(phase == PH_DONE);
-                    assert(disabled);
-                    assert(!watchdog_timeout);
-                    assert(state_hash16 == 16'he177);
-                    assert(ptc_percent == 192'd0);
-                    assert(fan_percent == {4{8'd30}});
-                    assert(solenoid_percent == 8'd0);
-                end
-            endcase
-
-            cover(phase == PH_DONE);
-        end
-    end
-endmodule
-
-`default_nettype wire

+ 0 - 27
tests/formal/prod2u_p4_core_watchdog_race.sby

@@ -1,27 +0,0 @@
-[tasks]
-bmc
-cover
-
-[options]
-bmc: mode bmc
-bmc: depth 192
-cover: mode cover
-cover: depth 192
-
-[engines]
-bmc: smtbmc yices
-cover: smtbmc yices
-
-[script]
-read_verilog -formal binary921_crc16.v prod2u_p4_normal_v3_output_state.v prod2u_p4_normal_v3_watchdog.v prod2u_p4_axis_executor.v prod2u_p4_motor_hub.v prod2u_p4_response_scheduler.v prod2u_p4_normal_v3_core.v prod2u_p4_core_watchdog_race_formal.v
-prep -top prod2u_p4_core_watchdog_race_formal
-
-[files]
-../../src/rtl/binary921_crc16.v
-../../src/rtl/prod2u_p4_normal_v3_output_state.v
-../../src/rtl/prod2u_p4_normal_v3_watchdog.v
-../../src/rtl/prod2u_p4_axis_executor.v
-../../src/rtl/prod2u_p4_motor_hub.v
-../../src/rtl/prod2u_p4_response_scheduler.v
-../../src/rtl/prod2u_p4_normal_v3_core.v
-prod2u_p4_core_watchdog_race_formal.v

+ 0 - 329
tests/formal/prod2u_p4_core_watchdog_race_formal.v

@@ -1,329 +0,0 @@
-`timescale 1ns/1ps
-`default_nettype none
-
-module prod2u_p4_core_watchdog_race_formal;
-    localparam [7:0] FT_HOST_BATCH_CMD = 8'h07;
-    localparam [7:0] FT_MOTION_CMD = 8'h11;
-
-    localparam [3:0] PH_UNARMED_STATUS_SEND = 4'd0;
-    localparam [3:0] PH_WAIT_UNARMED_STATUS = 4'd1;
-    localparam [3:0] PH_SNAPSHOT_SEND = 4'd2;
-    localparam [3:0] PH_WAIT_ARMED = 4'd3;
-    localparam [3:0] PH_JOG_SEND = 4'd4;
-    localparam [3:0] PH_WAIT_JOG = 4'd5;
-    localparam [3:0] PH_EARLY_STATUS_SEND = 4'd6;
-    localparam [3:0] PH_WAIT_EARLY_STATUS = 4'd7;
-    localparam [3:0] PH_WAIT_EXPIRY = 4'd8;
-    localparam [3:0] PH_CHECK_TIMEOUT = 4'd9;
-    localparam [3:0] PH_WAIT_RACE_RESPONSE = 4'd10;
-    localparam [3:0] PH_TIMEOUT_STATUS_SEND = 4'd11;
-    localparam [3:0] PH_WAIT_TIMEOUT_STATUS = 4'd12;
-    localparam [3:0] PH_WAIT_POST_TIMEOUT_STEP = 4'd13;
-    localparam [3:0] PH_DONE = 4'd14;
-
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    reg [3:0] phase = PH_UNARMED_STATUS_SEND;
-    reg previous_x_step = 1'b0;
-    reg saw_jog_step = 1'b0;
-    reg shadow_tracking = 1'b0;
-    reg [271:0] request_payload;
-    reg request_valid;
-
-    wire shadow_arm = request_valid && request_ready &&
-        (phase == PH_EARLY_STATUS_SEND);
-    wire shadow_refresh = request_valid && request_ready &&
-        (phase == PH_WAIT_EXPIRY);
-    wire shadow_disabled;
-    wire shadow_armed;
-    wire shadow_watchdog_timeout;
-    wire shadow_expiry_due;
-    wire [7:0] request_type = (phase == PH_SNAPSHOT_SEND) ?
-        FT_HOST_BATCH_CMD : FT_MOTION_CMD;
-    wire [5:0] request_length = (phase == PH_SNAPSHOT_SEND) ?
-        6'd34 : 6'd8;
-    wire request_ready;
-    wire fast_jog_valid = (phase == PH_JOG_SEND);
-    wire [191:0] ptc_percent;
-    wire [31:0] fan_percent;
-    wire [7:0] solenoid_percent;
-    wire [15:0] state_hash16;
-    wire [2:0] step_out;
-    wire [2:0] dir_out;
-    wire en_n;
-    wire disabled;
-    wire watchdog_timeout;
-    wire [1:0] reference_started;
-    wire [2:0] reference_step_out;
-    wire [2:0] reference_dir_out;
-
-    always @(*) begin
-        request_valid = 1'b0;
-        case (phase)
-            PH_UNARMED_STATUS_SEND,
-            PH_SNAPSHOT_SEND,
-            PH_EARLY_STATUS_SEND,
-            PH_TIMEOUT_STATUS_SEND: request_valid = 1'b1;
-            PH_WAIT_EXPIRY: request_valid = shadow_expiry_due;
-            default: request_valid = 1'b0;
-        endcase
-    end
-
-    always @(*) begin
-        request_payload = 272'd0;
-        case (phase)
-            PH_SNAPSHOT_SEND: begin
-                request_payload[7:0] = 8'h2a;
-                request_payload[15:8] = 8'd0;
-                request_payload[23:16] = 8'd61;
-                request_payload[26 * 8 +: 8] = 8'd44;
-                request_payload[27 * 8 +: 8] = 8'd45;
-                request_payload[28 * 8 +: 8] = 8'd46;
-                request_payload[29 * 8 +: 8] = 8'd47;
-                request_payload[30 * 8 +: 8] = 8'd100;
-            end
-
-            PH_JOG_SEND: begin
-                request_payload[7:0] = 8'h35;
-                request_payload[15:8] = 8'd0;
-                request_payload[23:16] = 8'd1;
-                request_payload[31:24] = 8'd3;
-                request_payload[47:32] = 16'hffff;
-            end
-
-            default: begin
-                request_payload[7:0] = 8'h37;
-            end
-        endcase
-    end
-
-    prod2u_p4_normal_v3_core #(
-        .CLK_HZ(1),
-        .WATCHDOG_SECONDS(64),
-        .DIR_SETUP_CYCLES(2),
-        .STEP_HALF_CYCLES(2)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(16'h3701),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(2'd0),
-        .fast_jog_dir(1'b1),
-        .fast_jog_steps(16'hffff),
-        .frame_valid(),
-        .frame_ready(1'b1),
-        .frame_type(),
-        .frame_payload_len(),
-        .frame_payload(),
-        .ptc_percent(ptc_percent),
-        .fan_percent(fan_percent),
-        .solenoid_percent(solenoid_percent),
-        .state_hash16(state_hash16),
-        .step_out(step_out),
-        .dir_out(dir_out),
-        .en_n(en_n),
-        .disabled(disabled),
-        .watchdog_timeout(watchdog_timeout)
-    );
-
-    prod2u_p4_motor_hub #(
-        .DIR_SETUP_CYCLES(2),
-        .STEP_HALF_CYCLES(2)
-    ) reference_motors (
-        .clk(clk),
-        .rst_n(rst_n),
-        .jog_start(fast_jog_valid),
-        .jog_axis(2'd0),
-        .jog_dir(1'b1),
-        .jog_steps(16'hffff),
-        .axis_started_pulse(reference_started),
-        .step_out(reference_step_out),
-        .dir_out(reference_dir_out)
-    );
-
-    prod2u_p4_normal_v3_watchdog #(
-        .CLK_HZ(1),
-        .WATCHDOG_SECONDS(64)
-    ) shadow_watchdog (
-        .clk(clk),
-        .rst_n(rst_n),
-        .arm(shadow_arm),
-        .refresh(shadow_refresh),
-        .disable_cmd(1'b0),
-        .disabled(shadow_disabled),
-        .armed(shadow_armed),
-        .watchdog_timeout(shadow_watchdog_timeout),
-        .expiry_due(shadow_expiry_due),
-        .force_safe()
-    );
-
-    always @(*) begin
-        if (rst_n && (phase == PH_WAIT_EXPIRY) && shadow_expiry_due) begin
-            assert(request_ready);
-            assert(request_valid);
-        end
-    end
-
-    always @(posedge clk) begin
-        rst_n <= 1'b1;
-        previous_x_step <= step_out[0];
-        if (step_out[0]) begin
-            saw_jog_step <= 1'b1;
-        end
-
-        if (!rst_n) begin
-            phase <= PH_UNARMED_STATUS_SEND;
-            previous_x_step <= 1'b0;
-            saw_jog_step <= 1'b0;
-            shadow_tracking <= 1'b0;
-        end else begin
-            assert(en_n == 1'b0);
-            assert(step_out == reference_step_out);
-            assert(dir_out == reference_dir_out);
-            assert(step_out[2] == 1'b0);
-            assert(dir_out[2] == 1'b0);
-            if (shadow_tracking) begin
-                assert(disabled == shadow_disabled);
-                assert(watchdog_timeout == shadow_watchdog_timeout);
-            end
-
-            case (phase)
-                PH_UNARMED_STATUS_SEND: begin
-                    assert(disabled);
-                    if (request_valid && request_ready) begin
-                        phase <= PH_WAIT_UNARMED_STATUS;
-                    end
-                end
-
-                PH_WAIT_UNARMED_STATUS: begin
-                    assert(disabled);
-                    assert(!watchdog_timeout);
-                    if (request_ready) begin
-                        phase <= PH_SNAPSHOT_SEND;
-                    end
-                end
-
-                PH_SNAPSHOT_SEND: begin
-                    assert(disabled);
-                    if (request_valid && request_ready) begin
-                        phase <= PH_WAIT_ARMED;
-                    end
-                end
-
-                PH_WAIT_ARMED: begin
-                    assert(!watchdog_timeout);
-                    if (request_ready && !disabled &&
-                        (ptc_percent[7:0] == 8'd61) &&
-                        (fan_percent == {8'd47, 8'd46, 8'd45, 8'd44}) &&
-                        (solenoid_percent == 8'd100)) begin
-                        phase <= PH_JOG_SEND;
-                    end
-                end
-
-                PH_JOG_SEND: begin
-                    assert(!disabled);
-                    assert(!watchdog_timeout);
-                    phase <= PH_WAIT_JOG;
-                end
-
-                PH_WAIT_JOG: begin
-                    assert(!disabled);
-                    assert(!watchdog_timeout);
-                    if (saw_jog_step && request_ready) begin
-                        phase <= PH_EARLY_STATUS_SEND;
-                    end
-                end
-
-                PH_EARLY_STATUS_SEND: begin
-                    assert(!disabled);
-                    assert(!watchdog_timeout);
-                    if (request_valid && request_ready) begin
-                        shadow_tracking <= 1'b1;
-                        phase <= PH_WAIT_EARLY_STATUS;
-                    end
-                end
-
-                PH_WAIT_EARLY_STATUS: begin
-                    assert(!disabled);
-                    assert(!watchdog_timeout);
-                    if (request_ready) begin
-                        phase <= PH_WAIT_EXPIRY;
-                    end
-                end
-
-                PH_WAIT_EXPIRY: begin
-                    assert(request_ready);
-                    assert(shadow_armed);
-                    assert(!disabled);
-                    assert(!watchdog_timeout);
-                    if (shadow_expiry_due) begin
-                        phase <= PH_CHECK_TIMEOUT;
-                    end
-                end
-
-                PH_CHECK_TIMEOUT: begin
-                    assert(disabled);
-                    assert(watchdog_timeout);
-                    assert(!shadow_armed);
-                    assert(state_hash16 == 16'he177);
-                    assert(ptc_percent == 192'd0);
-                    assert(fan_percent == {4{8'd30}});
-                    assert(solenoid_percent == 8'd0);
-                    phase <= PH_WAIT_RACE_RESPONSE;
-                end
-
-                PH_WAIT_RACE_RESPONSE: begin
-                    assert(disabled);
-                    assert(watchdog_timeout);
-                    assert(!shadow_armed);
-                    if (request_ready) begin
-                        phase <= PH_TIMEOUT_STATUS_SEND;
-                    end
-                end
-
-                PH_TIMEOUT_STATUS_SEND: begin
-                    assert(disabled);
-                    assert(watchdog_timeout);
-                    assert(!shadow_armed);
-                    if (request_valid && request_ready) begin
-                        phase <= PH_WAIT_TIMEOUT_STATUS;
-                    end
-                end
-
-                PH_WAIT_TIMEOUT_STATUS: begin
-                    assert(disabled);
-                    assert(watchdog_timeout);
-                    assert(!shadow_armed);
-                    if (request_ready) begin
-                        phase <= PH_WAIT_POST_TIMEOUT_STEP;
-                    end
-                end
-
-                PH_WAIT_POST_TIMEOUT_STEP: begin
-                    assert(disabled);
-                    assert(watchdog_timeout);
-                    assert(!shadow_armed);
-                    if (step_out[0] && !previous_x_step) begin
-                        phase <= PH_DONE;
-                    end
-                end
-
-                default: begin
-                    assert(phase == PH_DONE);
-                    assert(disabled);
-                    assert(watchdog_timeout);
-                    assert(!shadow_armed);
-                end
-            endcase
-
-            cover(phase == PH_DONE);
-        end
-    end
-endmodule
-
-`default_nettype wire

+ 0 - 48
tests/formal/prod2u_p4_fast_jog_path.sby

@@ -1,48 +0,0 @@
-[tasks]
-prove_path
-cover_path
-bmc_rx_path
-cover_rx_path
-prove_production_timing
-
-[options]
-prove_path: mode prove
-prove_path: depth 64
-cover_path: mode cover
-cover_path: depth 64
-bmc_rx_path: mode bmc
-bmc_rx_path: depth 64
-cover_rx_path: mode cover
-cover_rx_path: depth 64
-prove_production_timing: mode prove
-prove_production_timing: depth 64
-
-[engines]
-prove_path: abc pdr
-cover_path: smtbmc yices
-bmc_rx_path: smtbmc yices
-cover_rx_path: smtbmc yices
-prove_production_timing: abc pdr
-
-[script]
-prove_path: read_verilog -formal binary921_crc16.v prod2u_p4_normal_v3_output_state.v prod2u_p4_normal_v3_watchdog.v prod2u_p4_axis_executor.v prod2u_p4_motor_hub.v prod2u_p4_response_scheduler.v prod2u_p4_normal_v3_core.v prod2u_p4_fast_jog_path_formal.v
-cover_path: read_verilog -formal binary921_crc16.v prod2u_p4_normal_v3_output_state.v prod2u_p4_normal_v3_watchdog.v prod2u_p4_axis_executor.v prod2u_p4_motor_hub.v prod2u_p4_response_scheduler.v prod2u_p4_normal_v3_core.v prod2u_p4_fast_jog_path_formal.v
-bmc_rx_path: read_verilog -formal binary921_crc16.v prod2u_p4_normal_v3_rx.v prod2u_p4_fast_jog_path_formal.v
-cover_rx_path: read_verilog -formal binary921_crc16.v prod2u_p4_normal_v3_rx.v prod2u_p4_fast_jog_path_formal.v
-prove_production_timing: read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_fast_jog_path_formal.v
-prove_path: prep -top prod2u_p4_fast_jog_path_formal
-cover_path: prep -top prod2u_p4_fast_jog_path_formal
-bmc_rx_path: prep -top prod2u_p4_fast_jog_rx_formal
-cover_rx_path: prep -top prod2u_p4_fast_jog_rx_formal
-prove_production_timing: prep -top prod2u_p4_fast_jog_production_timing_formal
-
-[files]
-../../src/rtl/binary921_crc16.v
-../../src/rtl/prod2u_p4_normal_v3_output_state.v
-../../src/rtl/prod2u_p4_normal_v3_watchdog.v
-../../src/rtl/prod2u_p4_axis_executor.v
-../../src/rtl/prod2u_p4_motor_hub.v
-../../src/rtl/prod2u_p4_response_scheduler.v
-../../src/rtl/prod2u_p4_normal_v3_core.v
-../../src/rtl/prod2u_p4_normal_v3_rx.v
-prod2u_p4_fast_jog_path_formal.v

+ 0 - 627
tests/formal/prod2u_p4_fast_jog_path_formal.v

@@ -1,627 +0,0 @@
-`timescale 1ns/1ps
-`default_nettype none
-
-// Independent observable axis model. The implementation uses a four-state
-// phase machine; this oracle instead uses explicit setup/high/low countdowns.
-module prod2u_p4_fast_jog_axis_oracle #(
-    parameter integer DIR_SETUP_CYCLES = 3,
-    parameter integer STEP_HALF_CYCLES = 2
-) (
-    input  wire        clk,
-    input  wire        rst_n,
-    input  wire        command_start,
-    input  wire        command_dir,
-    input  wire [15:0] command_steps,
-    output reg         step_out,
-    output reg         dir_out,
-    output reg         started_pulse,
-    output reg         active,
-    output reg  [15:0] steps_left
-);
-    reg [15:0] setup_left;
-    reg [15:0] high_left;
-    reg [15:0] low_left;
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            step_out <= 1'b0;
-            dir_out <= 1'b0;
-            started_pulse <= 1'b0;
-            active <= 1'b0;
-            steps_left <= 16'd0;
-            setup_left <= 16'd0;
-            high_left <= 16'd0;
-            low_left <= 16'd0;
-        end else begin
-            started_pulse <= 1'b0;
-            if (command_start) begin
-                step_out <= 1'b0;
-                dir_out <= command_dir;
-                active <= 1'b1;
-                steps_left <= command_steps;
-                setup_left <= DIR_SETUP_CYCLES;
-                high_left <= 16'd0;
-                low_left <= 16'd0;
-            end else if (active) begin
-                if (setup_left != 16'd0) begin
-                    if (setup_left == 16'd1) begin
-                        setup_left <= 16'd0;
-                        step_out <= 1'b1;
-                        high_left <= STEP_HALF_CYCLES;
-                        started_pulse <= 1'b1;
-                    end else begin
-                        setup_left <= setup_left - 16'd1;
-                    end
-                end else if (step_out) begin
-                    if (high_left == 16'd1) begin
-                        step_out <= 1'b0;
-                        high_left <= 16'd0;
-                        low_left <= STEP_HALF_CYCLES;
-                    end else begin
-                        high_left <= high_left - 16'd1;
-                    end
-                end else if (low_left != 16'd0) begin
-                    if (low_left == 16'd1) begin
-                        low_left <= 16'd0;
-                        if (steps_left == 16'd1) begin
-                            active <= 1'b0;
-                            steps_left <= 16'd0;
-                        end else begin
-                            steps_left <= steps_left - 16'd1;
-                            step_out <= 1'b1;
-                            high_left <= STEP_HALF_CYCLES;
-                        end
-                    end else begin
-                        low_left <= low_left - 16'd1;
-                    end
-                end
-            end
-        end
-    end
-endmodule
-
-// End-to-end core proof with deliberately short periods. A legal fast JOG is
-// compared against two independent axis oracles while an unrelated ordinary
-// command and TX backpressure are unconstrained. Any dependency on
-// request_ready, the core state, command_inflight, or frame_ready breaks the
-// observable equivalence.
-module prod2u_p4_fast_jog_path_formal;
-    localparam integer FORMAL_DIR_SETUP_CYCLES = 3;
-    localparam integer FORMAL_STEP_HALF_CYCLES = 2;
-
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    reg past_valid = 1'b0;
-
-    (* anyseq *) reg ordinary_request_valid;
-    (* anyseq *) reg ordinary_request_is_snapshot;
-    (* anyseq *) reg frame_ready;
-    (* anyseq *) reg fast_jog_valid;
-    (* anyseq *) reg [1:0] fast_jog_axis;
-    (* anyseq *) reg fast_jog_dir;
-    (* anyseq *) reg [15:0] fast_jog_steps;
-
-    wire request_ready;
-    wire frame_valid;
-    wire [7:0] frame_type;
-    wire [7:0] frame_payload_len;
-    wire [143:0] frame_payload;
-    wire [191:0] ptc_percent;
-    wire [31:0] fan_percent;
-    wire [7:0] solenoid_percent;
-    wire [15:0] state_hash16;
-    wire [2:0] step_out;
-    wire [2:0] dir_out;
-    wire en_n;
-    wire disabled;
-    wire watchdog_timeout;
-    wire [2:0] dut_state;
-
-    wire x_spec_step;
-    wire x_spec_dir;
-    wire x_spec_started;
-    wire x_spec_active;
-    wire [15:0] x_spec_steps_left;
-    wire y_spec_step;
-    wire y_spec_dir;
-    wire y_spec_started;
-    wire y_spec_active;
-    wire [15:0] y_spec_steps_left;
-
-    reg [2:0] previous_step = 3'd0;
-    reg saw_tx_blocked_fast = 1'b0;
-    reg blocked_fast_axis = 1'b0;
-    reg saw_nonidle_fast = 1'b0;
-    reg nonidle_fast_axis = 1'b0;
-    reg saw_ffff_fast = 1'b0;
-    reg x_two_active = 1'b0;
-    reg [1:0] x_two_rises = 2'd0;
-    reg x_two_complete = 1'b0;
-
-    // GET_STATUS occupies the response scheduler; a valid snapshot reaches
-    // the non-IDLE validate/commit states without creating a motor command.
-    reg [271:0] snapshot_request_payload;
-    integer snapshot_index;
-    always @* begin
-        snapshot_request_payload = 272'd0;
-        snapshot_request_payload[7:0] = 8'h2a;
-        for (snapshot_index = 0; snapshot_index < 24;
-             snapshot_index = snapshot_index + 1) begin
-            snapshot_request_payload[(snapshot_index + 2) * 8 +: 8] = 8'd10;
-        end
-        for (snapshot_index = 0; snapshot_index < 4;
-             snapshot_index = snapshot_index + 1) begin
-            snapshot_request_payload[(snapshot_index + 26) * 8 +: 8] = 8'd30;
-        end
-    end
-    wire [7:0] ordinary_request_type =
-        ordinary_request_is_snapshot ? 8'h07 : 8'h05;
-    wire [5:0] ordinary_request_length =
-        ordinary_request_is_snapshot ? 6'd34 : 6'd4;
-    wire [271:0] ordinary_payload = ordinary_request_is_snapshot ?
-        snapshot_request_payload : {264'd0, 8'h24};
-
-    prod2u_p4_normal_v3_core #(
-        .CLK_HZ(4),
-        .WATCHDOG_SECONDS(2),
-        .DIR_SETUP_CYCLES(FORMAL_DIR_SETUP_CYCLES),
-        .STEP_HALF_CYCLES(FORMAL_STEP_HALF_CYCLES)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .request_valid(ordinary_request_valid),
-        .request_ready(request_ready),
-        .request_type(ordinary_request_type),
-        .request_length(ordinary_request_length),
-        .request_payload(ordinary_payload),
-        .request_crc16(16'h1234),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(fast_jog_axis),
-        .fast_jog_dir(fast_jog_dir),
-        .fast_jog_steps(fast_jog_steps),
-        .frame_valid(frame_valid),
-        .frame_ready(frame_ready),
-        .frame_type(frame_type),
-        .frame_payload_len(frame_payload_len),
-        .frame_payload(frame_payload),
-        .ptc_percent(ptc_percent),
-        .fan_percent(fan_percent),
-        .solenoid_percent(solenoid_percent),
-        .state_hash16(state_hash16),
-        .step_out(step_out),
-        .dir_out(dir_out),
-        .en_n(en_n),
-        .disabled(disabled),
-        .watchdog_timeout(watchdog_timeout),
-        .formal_state(dut_state)
-    );
-
-    prod2u_p4_fast_jog_axis_oracle #(
-        .DIR_SETUP_CYCLES(FORMAL_DIR_SETUP_CYCLES),
-        .STEP_HALF_CYCLES(FORMAL_STEP_HALF_CYCLES)
-    ) x_oracle (
-        .clk(clk),
-        .rst_n(rst_n),
-        .command_start(fast_jog_valid && (fast_jog_axis == 2'd0)),
-        .command_dir(fast_jog_dir),
-        .command_steps(fast_jog_steps),
-        .step_out(x_spec_step),
-        .dir_out(x_spec_dir),
-        .started_pulse(x_spec_started),
-        .active(x_spec_active),
-        .steps_left(x_spec_steps_left)
-    );
-
-    prod2u_p4_fast_jog_axis_oracle #(
-        .DIR_SETUP_CYCLES(FORMAL_DIR_SETUP_CYCLES),
-        .STEP_HALF_CYCLES(FORMAL_STEP_HALF_CYCLES)
-    ) y_oracle (
-        .clk(clk),
-        .rst_n(rst_n),
-        .command_start(fast_jog_valid && (fast_jog_axis == 2'd1)),
-        .command_dir(fast_jog_dir),
-        .command_steps(fast_jog_steps),
-        .step_out(y_spec_step),
-        .dir_out(y_spec_dir),
-        .started_pulse(y_spec_started),
-        .active(y_spec_active),
-        .steps_left(y_spec_steps_left)
-    );
-
-    always @(posedge clk) begin
-        past_valid <= 1'b1;
-        rst_n <= 1'b1;
-        previous_step <= step_out;
-
-        if (rst_n && fast_jog_valid) begin
-            assume(fast_jog_axis <= 2'd1);
-            // RAW_U16_TRUSTED_HOST_NO_CPLD_CAP: the host owns zero rejection.
-            assume(fast_jog_steps != 16'd0);
-        end
-
-        if (!rst_n) begin
-            saw_tx_blocked_fast <= 1'b0;
-            blocked_fast_axis <= 1'b0;
-            saw_nonidle_fast <= 1'b0;
-            nonidle_fast_axis <= 1'b0;
-            saw_ffff_fast <= 1'b0;
-            x_two_active <= 1'b0;
-            x_two_rises <= 2'd0;
-            x_two_complete <= 1'b0;
-        end else begin
-            if (frame_valid && !frame_ready && fast_jog_valid) begin
-                saw_tx_blocked_fast <= 1'b1;
-                blocked_fast_axis <= fast_jog_axis[0];
-            end
-            if (fast_jog_valid && (dut_state != 3'd0)) begin
-                saw_nonidle_fast <= 1'b1;
-                nonidle_fast_axis <= fast_jog_axis[0];
-            end
-            if (fast_jog_valid && (fast_jog_steps == 16'hffff)) begin
-                saw_ffff_fast <= 1'b1;
-            end
-
-            if (fast_jog_valid && (fast_jog_axis == 2'd0)) begin
-                x_two_active <= (fast_jog_steps == 16'd2);
-                x_two_rises <= 2'd0;
-                x_two_complete <= 1'b0;
-            end else if (x_two_active) begin
-                if (step_out[0] && !previous_step[0]) begin
-                    x_two_rises <= x_two_rises + 1'b1;
-                end
-                if (!x_spec_active && (x_two_rises == 2'd2)) begin
-                    x_two_active <= 1'b0;
-                    x_two_complete <= 1'b1;
-                end
-            end
-        end
-
-        if (rst_n) begin
-            assert(step_out[0] == x_spec_step);
-            assert(dir_out[0] == x_spec_dir);
-            assert(step_out[1] == y_spec_step);
-            assert(dir_out[1] == y_spec_dir);
-            assert(!step_out[2]);
-            assert(!dir_out[2]);
-            assert(!en_n);
-            assert(!x_spec_started || x_spec_step);
-            assert(!y_spec_started || y_spec_step);
-        end
-
-        cover(saw_tx_blocked_fast &&
-            step_out[blocked_fast_axis] &&
-            !previous_step[blocked_fast_axis]);
-        cover(saw_nonidle_fast &&
-            step_out[nonidle_fast_axis] &&
-            !previous_step[nonidle_fast_axis]);
-        cover(rst_n && step_out[0] && step_out[1]);
-        cover(saw_ffff_fast && (step_out[0] || step_out[1]));
-        cover(x_two_complete);
-    end
-
-    wire unused = request_ready ^ frame_type[0] ^ frame_payload_len[0] ^
-        frame_payload[0] ^ ptc_percent[0] ^ fan_percent[0] ^
-        solenoid_percent[0] ^ state_hash16[0] ^ disabled ^
-        watchdog_timeout ^ x_spec_steps_left[0] ^ y_spec_steps_left[0] ^
-        dut_state[0] ^ past_valid;
-endmodule
-
-// A complete CRC-correct JOG must use the RX fast exit even while an older
-// ordinary request is held. Axis, direction, speed, and steps remain symbolic;
-// the classifier intentionally has no assumption on the raw 16-bit steps.
-module prod2u_p4_fast_jog_rx_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    reg [6:0] stream_index = 7'd0;
-    reg [15:0] harness_crc = 16'hffff;
-    reg held_request_seen = 1'b0;
-    reg fast_event_seen = 1'b0;
-    reg fast_event_previous = 1'b0;
-    reg [7:0] held_request_type = 8'd0;
-    reg [5:0] held_request_length = 6'd0;
-    reg [271:0] held_request_payload = 272'd0;
-    reg [15:0] held_request_crc16 = 16'd0;
-
-    (* anyconst *) reg [1:0] jog_axis;
-    (* anyconst *) reg jog_dir;
-    (* anyconst *) reg [1:0] jog_speed;
-    (* anyconst *) reg [15:0] jog_steps;
-
-    wire first_frame = (stream_index <= 7'd19);
-    wire second_frame = (stream_index >= 7'd22) &&
-        (stream_index <= 7'd45);
-    wire drive_valid = rst_n && (first_frame || second_frame);
-    wire [6:0] local_index = second_frame ?
-        (stream_index - 7'd22) : stream_index;
-    wire [6:0] crc_low_index = second_frame ? 7'd22 : 7'd18;
-    wire [6:0] crc_high_index = second_frame ? 7'd23 : 7'd19;
-    reg [7:0] drive_data;
-    wire [15:0] harness_crc_next;
-
-    wire rx_ready;
-    wire request_valid;
-    wire [7:0] request_type;
-    wire [5:0] request_length;
-    wire [271:0] request_payload;
-    wire [15:0] request_crc16;
-    wire fast_jog_valid;
-    wire [1:0] fast_jog_axis;
-    wire fast_jog_dir;
-    wire [15:0] fast_jog_steps;
-    wire [15:0] crc_error_count;
-    wire [15:0] timeout_count;
-    wire [15:0] format_error_count;
-
-    binary921_crc16 u_harness_crc (
-        .crc_in(harness_crc),
-        .data(drive_data),
-        .crc_out(harness_crc_next)
-    );
-
-    prod2u_p4_normal_v3_rx #(
-        .CLK_HZ(1000),
-        .INTER_BYTE_TIMEOUT_MS(2)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_valid(drive_valid),
-        .rx_ready(rx_ready),
-        .rx_data(drive_data),
-        .request_valid(request_valid),
-        .request_ready(1'b0),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(request_crc16),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(fast_jog_axis),
-        .fast_jog_dir(fast_jog_dir),
-        .fast_jog_steps(fast_jog_steps),
-        .crc_error_count(crc_error_count),
-        .timeout_count(timeout_count),
-        .format_error_count(format_error_count)
-    );
-
-    always @* begin
-        if (local_index == 7'd0) begin
-            drive_data = 8'ha5;
-        end else if (local_index == 7'd1) begin
-            drive_data = 8'h5a;
-        end else if (local_index == 7'd2) begin
-            drive_data = 8'h02;
-        end else if (local_index == 7'd3) begin
-            drive_data = 8'h04;
-        end else if (local_index == 7'd4) begin
-            drive_data = second_frame ? 8'h11 : 8'h05;
-        end else if (local_index >= 7'd5 && local_index <= 7'd12) begin
-            drive_data = 8'd0;
-        end else if (local_index == 7'd13) begin
-            drive_data = second_frame ? 8'd8 : 8'd4;
-        end else if (local_index < crc_low_index) begin
-            if (!second_frame) begin
-                case (local_index)
-                    7'd14: drive_data = 8'h24;
-                    default: drive_data = 8'd0;
-                endcase
-            end else begin
-                case (local_index)
-                    7'd14: drive_data = 8'h35;
-                    7'd15: drive_data = {6'd0, jog_axis};
-                    7'd16: drive_data = {7'd0, jog_dir};
-                    7'd17: drive_data = {6'd0, jog_speed};
-                    7'd18: drive_data = jog_steps[7:0];
-                    7'd19: drive_data = jog_steps[15:8];
-                    default: drive_data = 8'd0;
-                endcase
-            end
-        end else if (local_index == crc_low_index) begin
-            drive_data = harness_crc[7:0];
-        end else begin
-            drive_data = harness_crc[15:8];
-        end
-    end
-
-    always @(posedge clk) begin
-        assume(jog_axis <= 2'd1);
-        rst_n <= 1'b1;
-        fast_event_previous <= fast_jog_valid;
-
-        if (!rst_n) begin
-            stream_index <= 7'd0;
-            harness_crc <= 16'hffff;
-            held_request_seen <= 1'b0;
-            fast_event_seen <= 1'b0;
-            fast_event_previous <= 1'b0;
-            held_request_type <= 8'd0;
-            held_request_length <= 6'd0;
-            held_request_payload <= 272'd0;
-            held_request_crc16 <= 16'd0;
-        end else begin
-            assert(rx_ready);
-            assert(crc_error_count == 16'd0);
-            assert(timeout_count == 16'd0);
-            assert(format_error_count == 16'd0);
-
-            if (stream_index < 7'd50) begin
-                stream_index <= stream_index + 1'b1;
-            end
-            if (drive_valid && (local_index >= 7'd2) &&
-                (local_index < crc_low_index)) begin
-                harness_crc <= harness_crc_next;
-            end else if (drive_valid && (local_index == crc_high_index)) begin
-                harness_crc <= 16'hffff;
-            end
-
-            if (request_valid && !held_request_seen) begin
-                held_request_seen <= 1'b1;
-                held_request_type <= request_type;
-                held_request_length <= request_length;
-                held_request_payload <= request_payload;
-                held_request_crc16 <= request_crc16;
-                assert(request_type == 8'h05);
-                assert(request_length == 6'd4);
-                assert(request_payload == {240'd0, 32'h00000024});
-            end
-            if (held_request_seen) begin
-                assert(request_valid);
-                assert(request_type == held_request_type);
-                assert(request_length == held_request_length);
-                assert(request_payload == held_request_payload);
-                assert(request_crc16 == held_request_crc16);
-            end
-
-            if (fast_jog_valid) begin
-                assert(!fast_event_previous);
-                assert(!fast_event_seen);
-                assert(held_request_seen);
-                assert(fast_jog_axis == jog_axis);
-                assert(fast_jog_dir == jog_dir);
-                assert(fast_jog_steps == jog_steps);
-                fast_event_seen <= 1'b1;
-            end
-            if (stream_index >= 7'd48) begin
-                assert(held_request_seen);
-                assert(fast_event_seen);
-            end
-        end
-
-        cover(fast_event_seen && held_request_seen);
-    end
-endmodule
-
-// The small-parameter proof above supplies the independent countdown oracle.
-// This production instance proves the exact reload constants and every local
-// transition, which establishes 25,000 setup clocks and 12,500 clocks for each
-// STEP level without unrolling those full intervals.
-module prod2u_p4_fast_jog_production_timing_formal;
-    localparam integer PRODUCTION_DIR_SETUP_CYCLES = 25000;
-    localparam integer PRODUCTION_STEP_HALF_CYCLES = 12500;
-
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    (* anyseq *) reg fast_jog_valid;
-    (* anyseq *) reg fast_jog_dir;
-    (* anyseq *) reg [15:0] fast_jog_steps;
-    reg past_valid = 1'b0;
-
-    wire dut_step;
-    wire dut_dir;
-    wire dut_started;
-    wire [1:0] dut_motion_phase;
-    wire [31:0] dut_phase_counter;
-    wire [15:0] dut_remaining_steps;
-
-    prod2u_p4_axis_executor #(
-        .DIR_SETUP_CYCLES(PRODUCTION_DIR_SETUP_CYCLES),
-        .STEP_HALF_CYCLES(PRODUCTION_STEP_HALF_CYCLES)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .command_start(fast_jog_valid),
-        .command_dir(fast_jog_dir),
-        .command_steps(fast_jog_steps),
-        .step_out(dut_step),
-        .dir_out(dut_dir),
-        .started_pulse(dut_started),
-        .formal_motion_phase(dut_motion_phase),
-        .formal_phase_counter(dut_phase_counter),
-        .formal_remaining_steps(dut_remaining_steps)
-    );
-
-    always @(posedge clk) begin
-        past_valid <= 1'b1;
-        rst_n <= 1'b1;
-        if (rst_n && fast_jog_valid) begin
-            assume(fast_jog_steps != 16'd0);
-        end
-
-        if (!rst_n) begin
-            assert(!dut_step);
-            assert(!dut_started);
-        end
-
-        if (past_valid && $past(rst_n)) begin
-            if ($past(fast_jog_valid)) begin
-                assert(dut_motion_phase == 2'd1);
-                assert(dut_phase_counter == 32'd24999);
-                assert(dut_remaining_steps == $past(fast_jog_steps));
-                assert(dut_dir == $past(fast_jog_dir));
-                assert(!dut_step);
-                assert(!dut_started);
-            end else begin
-                case ($past(dut_motion_phase))
-                    2'd0: begin
-                        assert(dut_motion_phase == 2'd0);
-                        assert(dut_phase_counter == 32'd0);
-                        assert(dut_remaining_steps == 16'd0);
-                        assert(!dut_step);
-                        assert(!dut_started);
-                    end
-
-                    2'd1: begin
-                        if ($past(dut_phase_counter) != 32'd0) begin
-                            assert(dut_motion_phase == 2'd1);
-                            assert(dut_phase_counter ==
-                                $past(dut_phase_counter) - 1'b1);
-                            assert(!dut_step);
-                            assert(!dut_started);
-                        end else begin
-                            assert(dut_motion_phase == 2'd2);
-                            assert(dut_phase_counter == 32'd12499);
-                            assert(dut_step);
-                            assert(dut_started);
-                        end
-                        assert(dut_remaining_steps ==
-                            $past(dut_remaining_steps));
-                        assert(dut_dir == $past(dut_dir));
-                    end
-
-                    2'd2: begin
-                        if ($past(dut_phase_counter) != 32'd0) begin
-                            assert(dut_motion_phase == 2'd2);
-                            assert(dut_phase_counter ==
-                                $past(dut_phase_counter) - 1'b1);
-                            assert(dut_step);
-                        end else begin
-                            assert(dut_motion_phase == 2'd3);
-                            assert(dut_phase_counter == 32'd12499);
-                            assert(!dut_step);
-                        end
-                        assert(dut_remaining_steps ==
-                            $past(dut_remaining_steps));
-                        assert(dut_dir == $past(dut_dir));
-                        assert(!dut_started);
-                    end
-
-                    2'd3: begin
-                        if ($past(dut_phase_counter) != 32'd0) begin
-                            assert(dut_motion_phase == 2'd3);
-                            assert(dut_phase_counter ==
-                                $past(dut_phase_counter) - 1'b1);
-                            assert(dut_remaining_steps ==
-                                $past(dut_remaining_steps));
-                            assert(!dut_step);
-                        end else if ($past(dut_remaining_steps) == 16'd1) begin
-                            assert(dut_motion_phase == 2'd0);
-                            assert(dut_phase_counter == 32'd0);
-                            assert(dut_remaining_steps == 16'd0);
-                            assert(!dut_step);
-                        end else begin
-                            assert(dut_motion_phase == 2'd2);
-                            assert(dut_phase_counter == 32'd12499);
-                            assert(dut_remaining_steps ==
-                                $past(dut_remaining_steps) - 1'b1);
-                            assert(dut_step);
-                        end
-                        assert(dut_dir == $past(dut_dir));
-                        assert(!dut_started);
-                    end
-                endcase
-            end
-            assert(!dut_started || dut_step);
-        end
-        cover(rst_n && fast_jog_valid && (fast_jog_steps == 16'hffff));
-    end
-endmodule
-
-`default_nettype wire

+ 0 - 33
tests/formal/prod2u_p4_jog_no_gates.sby

@@ -1,33 +0,0 @@
-[tasks]
-bmc_core
-cover_core
-bmc_hub
-cover_hub
-
-[options]
-bmc_core: mode bmc
-bmc_core: depth 32
-cover_core: mode cover
-cover_core: depth 32
-bmc_hub: mode bmc
-bmc_hub: depth 32
-cover_hub: mode cover
-cover_hub: depth 32
-
-[engines]
-bmc_core: smtbmc yices
-cover_core: smtbmc yices
-bmc_hub: smtbmc yices
-cover_hub: smtbmc yices
-
-[script]
-read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_motor_hub.v prod2u_p4_jog_no_gates_formal.v
-bmc_core: prep -top prod2u_p4_core_jog_no_busy_formal
-cover_core: prep -top prod2u_p4_core_jog_no_busy_formal
-bmc_hub: prep -top prod2u_p4_hub_jog_no_gate_formal
-cover_hub: prep -top prod2u_p4_hub_jog_no_gate_formal
-
-[files]
-../../src/rtl/prod2u_p4_axis_executor.v
-../../src/rtl/prod2u_p4_motor_hub.v
-prod2u_p4_jog_no_gates_formal.v

+ 0 - 72
tests/formal/prod2u_p4_jog_no_gates_formal.v

@@ -1,72 +0,0 @@
-`timescale 1ns/1ps
-`default_nettype none
-
-module prod2u_p4_core_jog_no_busy_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    (* anyseq *) reg jog_start;
-    (* anyseq *) reg [1:0] jog_axis;
-    (* anyseq *) reg jog_dir;
-    (* anyseq *) reg [15:0] jog_steps;
-    (* anyseq *) reg legacy_limit;
-    (* anyseq *) reg legacy_disabled;
-    (* anyseq *) reg legacy_watchdog;
-    wire [1:0] started;
-    wire [2:0] step_out;
-    wire [2:0] dir_out;
-
-    prod2u_p4_motor_hub #(.DIR_SETUP_CYCLES(2), .STEP_HALF_CYCLES(2)) dut (
-        .clk(clk), .rst_n(rst_n), .jog_start(jog_start),
-        .jog_axis(jog_axis), .jog_dir(jog_dir), .jog_steps(jog_steps),
-        .axis_started_pulse(started), .step_out(step_out), .dir_out(dir_out)
-    );
-
-    always @(posedge clk) begin
-        rst_n <= 1'b1;
-        if (rst_n) begin
-            assert(!step_out[2]);
-            assert(!dir_out[2]);
-            assert(!started[0] || step_out[0]);
-            assert(!started[1] || step_out[1]);
-        end
-        cover(rst_n && (legacy_limit || legacy_disabled || legacy_watchdog) &&
-            (|started));
-    end
-endmodule
-
-module prod2u_p4_hub_jog_no_gate_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    (* anyseq *) reg jog_start;
-    (* anyseq *) reg [1:0] jog_axis;
-    (* anyseq *) reg jog_dir;
-    (* anyseq *) reg [15:0] jog_steps;
-    (* anyseq *) reg legacy_gate_a;
-    (* anyseq *) reg legacy_gate_b;
-    wire [1:0] started_a, started_b;
-    wire [2:0] step_a, step_b;
-    wire [2:0] dir_a, dir_b;
-
-    prod2u_p4_motor_hub #(.DIR_SETUP_CYCLES(2), .STEP_HALF_CYCLES(2)) a (
-        .clk(clk), .rst_n(rst_n), .jog_start(jog_start),
-        .jog_axis(jog_axis), .jog_dir(jog_dir), .jog_steps(jog_steps),
-        .axis_started_pulse(started_a), .step_out(step_a), .dir_out(dir_a)
-    );
-    prod2u_p4_motor_hub #(.DIR_SETUP_CYCLES(2), .STEP_HALF_CYCLES(2)) b (
-        .clk(clk), .rst_n(rst_n), .jog_start(jog_start),
-        .jog_axis(jog_axis), .jog_dir(jog_dir), .jog_steps(jog_steps),
-        .axis_started_pulse(started_b), .step_out(step_b), .dir_out(dir_b)
-    );
-
-    always @(posedge clk) begin
-        rst_n <= 1'b1;
-        if (rst_n) begin
-            assert(started_a == started_b);
-            assert(step_a == step_b);
-            assert(dir_a == dir_b);
-        end
-        cover(rst_n && (legacy_gate_a != legacy_gate_b) && (|started_a));
-    end
-endmodule
-
-`default_nettype wire

+ 0 - 43
tests/formal/prod2u_p4_motor_hub_axis_isolation.sby

@@ -1,43 +0,0 @@
-[tasks]
-prove_isolation
-cover_isolation
-bmc_overlap
-cover_overlap
-prove_reserved_axis
-cover_reserved_axis
-
-[options]
-prove_isolation: mode prove
-prove_isolation: depth 48
-cover_isolation: mode cover
-cover_isolation: depth 48
-bmc_overlap: mode bmc
-bmc_overlap: depth 48
-cover_overlap: mode cover
-cover_overlap: depth 48
-prove_reserved_axis: mode prove
-prove_reserved_axis: depth 32
-cover_reserved_axis: mode cover
-cover_reserved_axis: depth 32
-
-[engines]
-prove_isolation: abc pdr
-cover_isolation: smtbmc yices
-bmc_overlap: smtbmc yices
-cover_overlap: smtbmc yices
-prove_reserved_axis: abc pdr
-cover_reserved_axis: smtbmc yices
-
-[script]
-read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_motor_hub.v prod2u_p4_motor_hub_axis_isolation_formal.v
-prove_isolation: prep -top prod2u_p4_motor_hub_axis_isolation_formal
-cover_isolation: prep -top prod2u_p4_motor_hub_axis_isolation_formal
-bmc_overlap: prep -top prod2u_p4_motor_hub_peer_overlap_formal
-cover_overlap: prep -top prod2u_p4_motor_hub_peer_overlap_formal
-prove_reserved_axis: prep -top prod2u_p4_motor_hub_reserved_axis_formal
-cover_reserved_axis: prep -top prod2u_p4_motor_hub_reserved_axis_formal
-
-[files]
-../../src/rtl/prod2u_p4_axis_executor.v
-../../src/rtl/prod2u_p4_motor_hub.v
-prod2u_p4_motor_hub_axis_isolation_formal.v

+ 0 - 118
tests/formal/prod2u_p4_motor_hub_axis_isolation_formal.v

@@ -1,118 +0,0 @@
-`timescale 1ns/1ps
-`default_nettype none
-
-module prod2u_p4_motor_hub_axis_isolation_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    (* anyseq *) reg jog_start;
-    (* anyseq *) reg [1:0] jog_axis;
-    (* anyseq *) reg jog_dir;
-    (* anyseq *) reg [15:0] jog_steps;
-
-    wire [1:0] started_actual, started_without_x, started_without_y;
-    wire [2:0] step_actual, step_without_x, step_without_y;
-    wire [2:0] dir_actual, dir_without_x, dir_without_y;
-
-    prod2u_p4_motor_hub #(.DIR_SETUP_CYCLES(2), .STEP_HALF_CYCLES(2)) actual (
-        .clk(clk), .rst_n(rst_n), .jog_start(jog_start),
-        .jog_axis(jog_axis), .jog_dir(jog_dir), .jog_steps(jog_steps),
-        .axis_started_pulse(started_actual),
-        .step_out(step_actual), .dir_out(dir_actual)
-    );
-    prod2u_p4_motor_hub #(.DIR_SETUP_CYCLES(2), .STEP_HALF_CYCLES(2)) without_x (
-        .clk(clk), .rst_n(rst_n),
-        .jog_start(jog_start && (jog_axis != 2'd0)),
-        .jog_axis(jog_axis), .jog_dir(jog_dir), .jog_steps(jog_steps),
-        .axis_started_pulse(started_without_x),
-        .step_out(step_without_x), .dir_out(dir_without_x)
-    );
-    prod2u_p4_motor_hub #(.DIR_SETUP_CYCLES(2), .STEP_HALF_CYCLES(2)) without_y (
-        .clk(clk), .rst_n(rst_n),
-        .jog_start(jog_start && (jog_axis != 2'd1)),
-        .jog_axis(jog_axis), .jog_dir(jog_dir), .jog_steps(jog_steps),
-        .axis_started_pulse(started_without_y),
-        .step_out(step_without_y), .dir_out(dir_without_y)
-    );
-
-    always @(posedge clk) begin
-        rst_n <= 1'b1;
-        if (rst_n) begin
-            assert(step_actual[1] == step_without_x[1]);
-            assert(dir_actual[1] == dir_without_x[1]);
-            assert(started_actual[1] == started_without_x[1]);
-            assert(step_actual[0] == step_without_y[0]);
-            assert(dir_actual[0] == dir_without_y[0]);
-            assert(started_actual[0] == started_without_y[0]);
-            assert(!step_actual[2]);
-            assert(!dir_actual[2]);
-        end
-        cover(rst_n && step_actual[0] && step_actual[1]);
-    end
-endmodule
-
-module prod2u_p4_motor_hub_peer_overlap_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    (* anyseq *) reg jog_start;
-    (* anyseq *) reg [1:0] jog_axis;
-    (* anyseq *) reg jog_dir;
-    (* anyseq *) reg [15:0] jog_steps;
-    wire [1:0] started;
-    wire [2:0] step_out;
-    wire [2:0] dir_out;
-
-    prod2u_p4_motor_hub #(.DIR_SETUP_CYCLES(2), .STEP_HALF_CYCLES(3)) dut (
-        .clk(clk), .rst_n(rst_n), .jog_start(jog_start),
-        .jog_axis(jog_axis), .jog_dir(jog_dir), .jog_steps(jog_steps),
-        .axis_started_pulse(started), .step_out(step_out), .dir_out(dir_out)
-    );
-
-    always @(posedge clk) begin
-        rst_n <= 1'b1;
-        if (rst_n) begin
-            assert(!step_out[2]);
-            assert(!dir_out[2]);
-            assert(!started[0] || step_out[0]);
-            assert(!started[1] || step_out[1]);
-        end
-        cover(rst_n && step_out[0] && step_out[1]);
-    end
-endmodule
-
-module prod2u_p4_motor_hub_reserved_axis_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    (* anyseq *) reg jog_start;
-    (* anyseq *) reg [1:0] jog_axis;
-    (* anyseq *) reg jog_dir;
-    (* anyseq *) reg [15:0] jog_steps;
-    wire [1:0] started_actual, started_reference;
-    wire [2:0] step_actual, step_reference;
-    wire [2:0] dir_actual, dir_reference;
-
-    prod2u_p4_motor_hub #(.DIR_SETUP_CYCLES(2), .STEP_HALF_CYCLES(2)) actual (
-        .clk(clk), .rst_n(rst_n), .jog_start(jog_start),
-        .jog_axis(jog_axis), .jog_dir(jog_dir), .jog_steps(jog_steps),
-        .axis_started_pulse(started_actual),
-        .step_out(step_actual), .dir_out(dir_actual)
-    );
-    prod2u_p4_motor_hub #(.DIR_SETUP_CYCLES(2), .STEP_HALF_CYCLES(2)) reference (
-        .clk(clk), .rst_n(rst_n), .jog_start(1'b0),
-        .jog_axis(jog_axis), .jog_dir(jog_dir), .jog_steps(jog_steps),
-        .axis_started_pulse(started_reference),
-        .step_out(step_reference), .dir_out(dir_reference)
-    );
-
-    always @(posedge clk) begin
-        rst_n <= 1'b1;
-        if (jog_start) assume(jog_axis[1]);
-        if (rst_n) begin
-            assert(started_actual == started_reference);
-            assert(step_actual == step_reference);
-            assert(dir_actual == dir_reference);
-        end
-        cover(rst_n && jog_start && jog_axis[1]);
-    end
-endmodule
-
-`default_nettype wire

+ 0 - 23
tests/formal/prod2u_p4_normal_v3_rx.sby

@@ -1,23 +0,0 @@
-[tasks]
-prove
-cover
-
-[options]
-prove: mode prove
-prove: depth 80
-cover: mode cover
-cover: depth 64
-
-[engines]
-prove: abc pdr
-cover: smtbmc
-
-[script]
-prove: read_verilog -formal binary921_crc16.v prod2u_p4_normal_v3_rx.v prod2u_p4_normal_v3_rx_formal.v
-cover: read_verilog -formal -D PROD2U_P4_FORMAL_COVER_DRIVER binary921_crc16.v prod2u_p4_normal_v3_rx.v prod2u_p4_normal_v3_rx_formal.v
-prep -top prod2u_p4_normal_v3_rx_formal
-
-[files]
-../../src/rtl/binary921_crc16.v
-../../src/rtl/prod2u_p4_normal_v3_rx.v
-prod2u_p4_normal_v3_rx_formal.v

+ 0 - 140
tests/formal/prod2u_p4_normal_v3_rx_formal.v

@@ -1,140 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_normal_v3_rx_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    (* anyseq *) reg rx_valid_anyseq;
-    (* anyseq *) reg [7:0] rx_data_anyseq;
-    (* anyseq *) reg request_ready_anyseq;
-    wire rx_valid;
-    wire [7:0] rx_data;
-    wire request_ready;
-    wire rx_ready;
-    wire request_valid;
-    wire [7:0] request_type;
-    wire [5:0] request_length;
-    wire [271:0] request_payload;
-    wire [15:0] request_crc16;
-    wire fast_jog_valid;
-    wire [1:0] fast_jog_axis;
-    wire fast_jog_dir;
-    wire [15:0] fast_jog_steps;
-    wire [15:0] crc_error_count;
-    wire [15:0] timeout_count;
-    wire [15:0] format_error_count;
-    (* anyconst *) reg [7:0] payload_low_bit;
-    (* anyconst *) reg [3:0] payload_high_bit;
-    reg past_valid = 1'b0;
-    reg [5:0] driver_phase = 6'd0;
-    reg held_request_seen = 1'b0;
-    reg handshake_seen = 1'b0;
-    reg recovery_seen = 1'b0;
-
-    // CRC-valid MOTION_CMD, held for two clocks before it is retired.
-    function [7:0] driver_byte;
-        input [5:0] index;
-        begin
-            case (index)
-                6'd0: driver_byte = 8'ha5;
-                6'd1: driver_byte = 8'h5a;
-                6'd2: driver_byte = 8'h02;
-                6'd3: driver_byte = 8'h04;
-                6'd4: driver_byte = 8'h11;
-                6'd13: driver_byte = 8'h08;
-                6'd14: driver_byte = 8'h37;
-                6'd15: driver_byte = 8'h01;
-                6'd17: driver_byte = 8'h03;
-                6'd18: driver_byte = 8'ha0;
-                6'd22: driver_byte = 8'hf1;
-                6'd23: driver_byte = 8'hc3;
-                default: driver_byte = 8'h00;
-            endcase
-        end
-    endfunction
-
-`ifdef PROD2U_P4_FORMAL_COVER_DRIVER
-    assign rx_valid = rst_n && (driver_phase < 6'd24);
-    assign rx_data = driver_byte(driver_phase);
-    assign request_ready = driver_phase >= 6'd26;
-`else
-    assign rx_valid = rx_valid_anyseq;
-    assign rx_data = rx_data_anyseq;
-    assign request_ready = request_ready_anyseq;
-`endif
-
-    prod2u_p4_normal_v3_rx #(
-        .CLK_HZ(1000),
-        .INTER_BYTE_TIMEOUT_MS(2)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_valid(rx_valid),
-        .rx_ready(rx_ready),
-        .rx_data(rx_data),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(request_crc16),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(fast_jog_axis),
-        .fast_jog_dir(fast_jog_dir),
-        .fast_jog_steps(fast_jog_steps),
-        .crc_error_count(crc_error_count),
-        .timeout_count(timeout_count),
-        .format_error_count(format_error_count)
-    );
-
-    always @(posedge clk) begin
-        past_valid <= 1'b1;
-        rst_n <= 1'b1;
-
-        if (!rst_n) begin
-            driver_phase <= 6'd0;
-            held_request_seen <= 1'b0;
-            handshake_seen <= 1'b0;
-            recovery_seen <= 1'b0;
-        end else begin
-`ifdef PROD2U_P4_FORMAL_COVER_DRIVER
-            if (driver_phase < 6'd28) begin
-                driver_phase <= driver_phase + 6'd1;
-            end
-`endif
-            if (request_valid && !request_ready) begin
-                held_request_seen <= 1'b1;
-            end
-            if (request_valid && request_ready) begin
-                handshake_seen <= 1'b1;
-            end
-            if (handshake_seen && !request_valid && rx_ready) begin
-                recovery_seen <= 1'b1;
-            end
-        end
-
-        if (rst_n) begin
-            assert(rx_ready);
-        end
-
-        if (past_valid && $past(rst_n)) begin
-            if ($past(request_valid && !request_ready)) begin
-                assert(request_valid);
-                assert(rx_ready);
-                assert(request_type == $past(request_type));
-                assert(request_length == $past(request_length));
-                assert(request_crc16 == $past(request_crc16));
-                assert(request_payload[payload_low_bit] ==
-                    $past(request_payload[payload_low_bit]));
-                assert(request_payload[9'd256 + payload_high_bit] ==
-                    $past(request_payload[9'd256 + payload_high_bit]));
-            end
-        end
-
-        cover(held_request_seen);
-        cover(handshake_seen);
-        cover(recovery_seen);
-    end
-
-    wire unused_fast_jog = fast_jog_valid ^ fast_jog_axis[0] ^
-        fast_jog_dir ^ fast_jog_steps[0];
-endmodule

+ 0 - 15
tests/formal/prod2u_p4_normal_v3_rx_payload.sby

@@ -1,15 +0,0 @@
-[options]
-mode bmc
-depth 56
-
-[engines]
-smtbmc
-
-[script]
-read_verilog -formal binary921_crc16.v prod2u_p4_normal_v3_rx.v prod2u_p4_normal_v3_rx_payload_formal.v
-prep -top prod2u_p4_normal_v3_rx_payload_formal
-
-[files]
-../../src/rtl/binary921_crc16.v
-../../src/rtl/prod2u_p4_normal_v3_rx.v
-prod2u_p4_normal_v3_rx_payload_formal.v

+ 0 - 151
tests/formal/prod2u_p4_normal_v3_rx_payload_formal.v

@@ -1,151 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_normal_v3_rx_payload_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    reg [6:0] frame_index = 7'd0;
-    reg request_seen = 1'b0;
-    reg [15:0] harness_crc = 16'hffff;
-    reg expected_payload_bit = 1'b0;
-    (* anyconst *) reg [1:0] command_kind;
-    (* anyconst *) reg [8:0] payload_bit_index;
-    (* anyseq *) reg [7:0] payload_byte;
-
-    wire [7:0] selected_type = (command_kind == 2'd0) ? 8'h05 :
-        (command_kind == 2'd1) ? 8'h07 : 8'h11;
-    wire [5:0] selected_length = (command_kind == 2'd0) ? 6'd4 :
-        (command_kind == 2'd1) ? 6'd34 : 6'd8;
-    wire [6:0] crc_low_index = 7'd14 + selected_length;
-    wire [6:0] crc_high_index = 7'd15 + selected_length;
-    wire [5:0] selected_payload_byte = payload_bit_index[8:3];
-    wire [2:0] selected_payload_bit = payload_bit_index[2:0];
-    wire drive_valid = rst_n && (frame_index <= crc_high_index);
-    reg [7:0] drive_data;
-
-    wire rx_ready;
-    wire request_valid;
-    wire [7:0] request_type;
-    wire [5:0] request_length;
-    wire [271:0] request_payload;
-    wire [15:0] request_crc16;
-    wire fast_jog_valid;
-    wire [1:0] fast_jog_axis;
-    wire fast_jog_dir;
-    wire [15:0] fast_jog_steps;
-    wire [15:0] crc_error_count;
-    wire [15:0] timeout_count;
-    wire [15:0] format_error_count;
-    wire [15:0] harness_crc_next;
-
-    binary921_crc16 u_harness_crc (
-        .crc_in(harness_crc),
-        .data(drive_data),
-        .crc_out(harness_crc_next)
-    );
-
-    prod2u_p4_normal_v3_rx #(
-        .CLK_HZ(1000),
-        .INTER_BYTE_TIMEOUT_MS(2)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_valid(drive_valid),
-        .rx_ready(rx_ready),
-        .rx_data(drive_data),
-        .request_valid(request_valid),
-        .request_ready(1'b1),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(request_crc16),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(fast_jog_axis),
-        .fast_jog_dir(fast_jog_dir),
-        .fast_jog_steps(fast_jog_steps),
-        .crc_error_count(crc_error_count),
-        .timeout_count(timeout_count),
-        .format_error_count(format_error_count)
-    );
-
-    always @* begin
-        if (frame_index == 7'd0) begin
-            drive_data = 8'ha5;
-        end else if (frame_index == 7'd1) begin
-            drive_data = 8'h5a;
-        end else if (frame_index == 7'd2) begin
-            drive_data = 8'h02;
-        end else if (frame_index == 7'd3) begin
-            drive_data = 8'h04;
-        end else if (frame_index == 7'd4) begin
-            drive_data = selected_type;
-        end else if (frame_index >= 7'd5 && frame_index <= 7'd12) begin
-            drive_data = 8'd0;
-        end else if (frame_index == 7'd13) begin
-            drive_data = {2'd0, selected_length};
-        end else if (frame_index < crc_low_index) begin
-            if (command_kind == 2'd0 && frame_index == 7'd14) begin
-                drive_data = 8'h26;
-            end else begin
-                drive_data = payload_byte;
-            end
-        end else if (frame_index == crc_low_index) begin
-            drive_data = harness_crc[7:0];
-        end else begin
-            drive_data = harness_crc[15:8];
-        end
-    end
-
-    always @(posedge clk) begin
-        assume(command_kind < 2'd3);
-        assume(payload_bit_index < 9'd272);
-        if (command_kind == 2'd2 && frame_index == 7'd14) begin
-            assume(payload_byte != 8'h35);
-        end
-        rst_n <= 1'b1;
-
-        if (!rst_n) begin
-            frame_index <= 7'd0;
-            request_seen <= 1'b0;
-            harness_crc <= 16'hffff;
-            expected_payload_bit <= 1'b0;
-        end else begin
-            if (drive_valid) begin
-                assert(rx_ready);
-                frame_index <= frame_index + 7'd1;
-                if (frame_index >= 7'd2 && frame_index < crc_low_index) begin
-                    harness_crc <= harness_crc_next;
-                end
-                if (frame_index >= 7'd14 && frame_index < crc_low_index &&
-                        frame_index == (7'd14 + selected_payload_byte)) begin
-                    expected_payload_bit <= drive_data[selected_payload_bit];
-                end
-            end
-
-            if (request_valid) begin
-                request_seen <= 1'b1;
-                assert(request_type == selected_type);
-                assert(request_length == selected_length);
-                assert(request_crc16 == harness_crc);
-                if (selected_payload_byte < selected_length) begin
-                    assert(request_payload[payload_bit_index] == expected_payload_bit);
-                end else begin
-                    assert(request_payload[payload_bit_index] == 1'b0);
-                end
-                assert(crc_error_count == 16'd0);
-                assert(timeout_count == 16'd0);
-                assert(format_error_count == 16'd0);
-                if (command_kind == 2'd0) begin
-                    assert(request_payload[7:0] == 8'h26);
-                end
-            end
-            assert(!fast_jog_valid);
-
-            if (frame_index >= (crc_high_index + 7'd1)) begin
-                assert(request_valid || request_seen);
-            end
-        end
-    end
-
-    wire unused_request = request_seen ^ fast_jog_axis[0] ^
-        fast_jog_dir ^ fast_jog_steps[0];
-endmodule

+ 0 - 14
tests/formal/prod2u_p4_normal_v3_watchdog_contract.sby

@@ -1,14 +0,0 @@
-[options]
-mode prove
-depth 12
-
-[engines]
-smtbmc
-
-[script]
-read_verilog -formal prod2u_p4_normal_v3_watchdog.v prod2u_p4_normal_v3_watchdog_contract_formal.v
-prep -top prod2u_p4_normal_v3_watchdog_contract_formal
-
-[files]
-../../src/rtl/prod2u_p4_normal_v3_watchdog.v
-prod2u_p4_normal_v3_watchdog_contract_formal.v

+ 0 - 83
tests/formal/prod2u_p4_normal_v3_watchdog_contract_formal.v

@@ -1,83 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_normal_v3_watchdog_contract_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    reg [3:0] phase = 4'd0;
-    wire arm = (phase == 4'd1) || (phase == 4'd6);
-    wire refresh = (phase == 4'd5);
-    wire disable_cmd = (phase == 4'd7);
-    wire disabled;
-    wire armed;
-    wire watchdog_timeout;
-    wire expiry_due;
-    wire force_safe;
-
-    prod2u_p4_normal_v3_watchdog #(
-        .CLK_HZ(4),
-        .WATCHDOG_SECONDS(1)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .arm(arm),
-        .refresh(refresh),
-        .disable_cmd(disable_cmd),
-        .disabled(disabled),
-        .armed(armed),
-        .watchdog_timeout(watchdog_timeout),
-        .expiry_due(expiry_due),
-        .force_safe(force_safe)
-    );
-
-    always @(posedge clk) begin
-        rst_n <= 1'b1;
-        if (!rst_n) begin
-            phase <= 4'd1;
-        end else if (phase < 4'd8) begin
-            phase <= phase + 4'd1;
-        end
-
-        if (rst_n) begin
-            assert(force_safe == (disable_cmd || expiry_due));
-            if (expiry_due) begin
-                assert(armed);
-                assert(!disabled);
-                assert(!watchdog_timeout);
-                assert(force_safe);
-            end
-            if (watchdog_timeout) begin
-                assert(disabled);
-                assert(!armed);
-            end
-
-            case (phase)
-                4'd1: begin
-                    assert(disabled && !armed && !watchdog_timeout);
-                end
-                4'd2, 4'd3, 4'd4: begin
-                    assert(!disabled && armed && !watchdog_timeout);
-                    assert(!expiry_due && !force_safe);
-                end
-                4'd5: begin
-                    assert(!disabled && armed && !watchdog_timeout);
-                    assert(expiry_due && force_safe);
-                end
-                4'd6: begin
-                    assert(disabled && !armed && watchdog_timeout);
-                    assert(!expiry_due && !force_safe);
-                end
-                4'd7: begin
-                    assert(!disabled && armed && !watchdog_timeout);
-                    assert(!expiry_due && force_safe);
-                end
-                4'd8: begin
-                    assert(disabled && !armed && !watchdog_timeout);
-                    assert(!expiry_due && !force_safe);
-                end
-                default: begin
-                end
-            endcase
-            cover(phase == 4'd8);
-        end
-    end
-endmodule

+ 0 - 23
tests/formal/prod2u_p4_output_state.sby

@@ -1,23 +0,0 @@
-[tasks]
-prove
-values
-
-[options]
-prove: mode prove
-prove: depth 48
-values: mode prove
-values: depth 48
-
-[engines]
-prove: smtbmc yices
-values: abc pdr
-
-[script]
-prove: read_verilog -formal binary921_crc16.v prod2u_p4_normal_v3_output_state.v prod2u_p4_output_state_formal.v
-values: read_verilog -formal -D BOUNDED_VALUE_CHECKS binary921_crc16.v prod2u_p4_normal_v3_output_state.v prod2u_p4_output_state_formal.v
-prep -top prod2u_p4_output_state_formal
-
-[files]
-../../src/rtl/binary921_crc16.v
-../../src/rtl/prod2u_p4_normal_v3_output_state.v
-prod2u_p4_output_state_formal.v

+ 0 - 82
tests/formal/prod2u_p4_output_state_formal.v

@@ -1,82 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_output_state_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    (* anyseq *) reg force_safe;
-    (* anyseq *) reg snapshot_valid;
-    (* anyseq *) reg [271:0] snapshot_payload;
-    (* anyseq *) reg commit_authorize;
-    wire snapshot_ready;
-    wire result_valid;
-    wire result_accepted;
-    wire commit_pulse;
-    wire [191:0] ptc_percent;
-    wire [31:0] fan_percent;
-    wire [7:0] solenoid_percent;
-    wire [15:0] state_hash16;
-    reg past_valid = 1'b0;
-    reg candidate_authorizable = 1'b0;
-    integer i;
-
-    prod2u_p4_normal_v3_output_state dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .force_safe(force_safe),
-        .snapshot_valid(snapshot_valid),
-        .snapshot_ready(snapshot_ready),
-        .snapshot_payload(snapshot_payload),
-        .commit_authorize(commit_authorize),
-        .result_valid(result_valid),
-        .result_accepted(result_accepted),
-        .commit_pulse(commit_pulse),
-        .ptc_percent(ptc_percent),
-        .fan_percent(fan_percent),
-        .solenoid_percent(solenoid_percent),
-        .state_hash16(state_hash16)
-    );
-
-    always @(posedge clk) begin
-        past_valid <= 1'b1;
-        rst_n <= 1'b1;
-        if (snapshot_valid) assume(snapshot_ready);
-        if (commit_authorize) assume(candidate_authorizable);
-        if (!rst_n || force_safe || commit_authorize) begin
-            candidate_authorizable <= 1'b0;
-        end else if (result_valid && result_accepted) begin
-            candidate_authorizable <= 1'b1;
-        end
-        if (past_valid && $past(rst_n)) begin
-            if ($past(force_safe)) begin
-                assert(ptc_percent == 192'd0);
-                assert(fan_percent == {4{8'd30}});
-                assert(solenoid_percent == 8'd0);
-                assert(state_hash16 == 16'he177);
-                assert(!commit_pulse);
-            end
-            if (result_valid) begin
-                assert(!commit_pulse);
-            end
-            if (commit_pulse) begin
-                assert($past(commit_authorize));
-                assert($past(candidate_authorizable));
-                assert(!$past(force_safe));
-            end
-            if (!commit_pulse && !$past(force_safe)) begin
-                assert(ptc_percent == $past(ptc_percent));
-                assert(fan_percent == $past(fan_percent));
-                assert(solenoid_percent == $past(solenoid_percent));
-                assert(state_hash16 == $past(state_hash16));
-            end
-`ifdef BOUNDED_VALUE_CHECKS
-            for (i = 0; i < 24; i = i + 1) begin
-                assert(ptc_percent[i * 8 +: 8] <= 8'd100);
-            end
-            for (i = 0; i < 4; i = i + 1) begin
-                assert(fan_percent[i * 8 +: 8] <= 8'd100);
-            end
-`endif
-            assert(solenoid_percent == 8'd0 || solenoid_percent == 8'd100);
-        end
-    end
-endmodule

+ 0 - 21
tests/formal/prod2u_p4_temperature_i2c_contract.sby

@@ -1,21 +0,0 @@
-[tasks]
-bmc
-cover
-
-[options]
-bmc: mode bmc
-bmc: depth 32
-cover: mode cover
-cover: depth 64
-
-[engines]
-bmc: smtbmc yices
-cover: smtbmc yices
-
-[script]
-read_verilog -formal prod2u_p4_i2c_stop_start_read.v prod2u_p4_temperature_i2c_contract_formal.v
-prep -top prod2u_p4_temperature_i2c_contract_formal
-
-[files]
-../../src/rtl/prod2u_p4_i2c_stop_start_read.v
-prod2u_p4_temperature_i2c_contract_formal.v

+ 0 - 85
tests/formal/prod2u_p4_temperature_i2c_contract_formal.v

@@ -1,85 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_temperature_i2c_contract_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    (* anyseq *) reg abort;
-    (* anyseq *) reg request_valid;
-    (* anyseq *) reg [6:0] request_device_addr;
-    (* anyseq *) reg [7:0] request_register;
-    (* anyseq *) reg response_ready;
-    (* anyseq *) reg scl_i;
-    (* anyseq *) reg sda_i;
-    wire abort_done;
-    wire request_ready;
-    wire response_valid;
-    wire [15:0] response_data;
-    wire [3:0] response_error;
-    wire busy;
-    wire scl_drive_low;
-    wire sda_drive_low;
-    reg past_valid = 1'b0;
-    reg inflight = 1'b0;
-
-    wire request_accepted = request_valid && request_ready && !abort;
-    wire request_retired = (response_valid && response_ready) || abort_done;
-
-    prod2u_p4_i2c_stop_start_read #(
-        .HALF_PERIOD_CLKS(4),
-        .TIMEOUT_CLKS(32)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .abort(abort),
-        .abort_done(abort_done),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_device_addr(request_device_addr),
-        .request_register(request_register),
-        .response_valid(response_valid),
-        .response_ready(response_ready),
-        .response_data(response_data),
-        .response_error(response_error),
-        .busy(busy),
-        .scl_i(scl_i),
-        .sda_i(sda_i),
-        .scl_drive_low(scl_drive_low),
-        .sda_drive_low(sda_drive_low)
-    );
-
-    always @(posedge clk) begin
-        past_valid <= 1'b1;
-        rst_n <= 1'b1;
-
-        if (!rst_n) begin
-            inflight <= 1'b0;
-        end else begin
-            if (request_accepted) begin
-                assert(!inflight || request_retired);
-            end
-            inflight <= request_accepted || (inflight && !request_retired);
-
-            assert(request_ready == !busy);
-            if (!busy || response_valid) begin
-                assert(!scl_drive_low);
-                assert(!sda_drive_low);
-            end
-            if (response_valid) begin
-                assert(inflight);
-                assert(!request_ready);
-            end
-            if (inflight && !request_retired) begin
-                assert(!request_ready);
-            end
-
-            if (past_valid && $past(response_valid && !response_ready && !abort)) begin
-                assert(response_valid);
-                assert($stable(response_data));
-                assert($stable(response_error));
-            end
-
-            cover(inflight && (scl_drive_low || sda_drive_low));
-            cover(response_valid);
-        end
-    end
-endmodule

+ 0 - 21
tests/formal/prod2u_p4_temperature_store_contract.sby

@@ -1,21 +0,0 @@
-[tasks]
-prove
-cover
-
-[options]
-prove: mode prove
-prove: depth 32
-cover: mode cover
-cover: depth 24
-
-[engines]
-prove: abc pdr
-cover: smtbmc yices
-
-[script]
-read_verilog -formal prod2u_p4_temperature_store.v prod2u_p4_temperature_store_contract_formal.v
-prep -top prod2u_p4_temperature_store_contract_formal
-
-[files]
-../../src/rtl/prod2u_p4_temperature_store.v
-prod2u_p4_temperature_store_contract_formal.v

+ 0 - 63
tests/formal/prod2u_p4_temperature_store_contract_formal.v

@@ -1,63 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_temperature_store_contract_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    (* anyseq *) reg wr_en;
-    (* anyseq *) reg [4:0] wr_addr;
-    (* anyseq *) reg [7:0] wr_data;
-    (* anyseq *) reg rd_req;
-    (* anyseq *) reg [4:0] rd_addr;
-    (* anyconst *) reg [4:0] watched_addr;
-    wire rd_valid;
-    wire [7:0] rd_data;
-    reg past_valid = 1'b0;
-    reg watched_valid = 1'b0;
-    reg [7:0] watched_data = 8'd0;
-    reg saw_watched_read = 1'b0;
-
-    prod2u_p4_temperature_store dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .wr_en(wr_en),
-        .wr_addr(wr_addr),
-        .wr_data(wr_data),
-        .rd_req(rd_req),
-        .rd_addr(rd_addr),
-        .rd_valid(rd_valid),
-        .rd_data(rd_data)
-    );
-
-    always @* begin
-        assume(watched_addr <= 5'd26);
-    end
-
-    always @(posedge clk) begin
-        past_valid <= 1'b1;
-        rst_n <= 1'b1;
-
-        if (!rst_n) begin
-            watched_valid <= 1'b0;
-            watched_data <= 8'd0;
-            saw_watched_read <= 1'b0;
-        end else begin
-            if (wr_en && wr_addr == watched_addr) begin
-                watched_valid <= 1'b1;
-                watched_data <= wr_data;
-            end
-
-            if (past_valid && $past(rst_n)) begin
-                assert(rd_valid == $past(rd_req));
-                if ($past(rd_req && rd_addr > 5'd26)) begin
-                    assert(rd_data == 8'hff);
-                end
-                if ($past(rd_req && rd_addr == watched_addr && watched_valid)) begin
-                    assert(rd_data == $past(watched_data));
-                    saw_watched_read <= 1'b1;
-                end
-            end
-
-            cover(watched_valid && saw_watched_read);
-        end
-    end
-endmodule

+ 0 - 24
tests/formal/prod2u_p4_temperature_tx_contract.sby

@@ -1,24 +0,0 @@
-[tasks]
-bmc
-cover
-
-[options]
-bmc: mode bmc
-bmc: depth 40
-cover: mode cover
-cover: depth 96
-
-[engines]
-bmc: smtbmc yices
-cover: smtbmc yices
-
-[script]
-read_verilog -formal binary921_crc16.v binary921_frame_tx.v prod2u_p4_temperature_short_tx.v prod2u_p4_normal_v3_tx.v prod2u_p4_temperature_tx_contract_formal.v
-prep -top prod2u_p4_temperature_tx_contract_formal
-
-[files]
-../../src/rtl/binary921_crc16.v
-../../src/rtl/binary921_frame_tx.v
-../../src/rtl/prod2u_p4_temperature_short_tx.v
-../../src/rtl/prod2u_p4_normal_v3_tx.v
-prod2u_p4_temperature_tx_contract_formal.v

+ 0 - 101
tests/formal/prod2u_p4_temperature_tx_contract_formal.v

@@ -1,101 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_temperature_tx_contract_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    reg frame_valid = 1'b0;
-    reg temperature_start = 1'b0;
-    (* anyseq *) reg tx_ready;
-    wire frame_ready;
-    wire temperature_rd_req;
-    wire [4:0] temperature_rd_addr;
-    reg temperature_rd_valid = 1'b0;
-    reg [7:0] temperature_rd_data = 8'd0;
-    wire temperature_done;
-    wire tx_valid;
-    wire [7:0] tx_data;
-    reg past_valid = 1'b0;
-    reg requests_launched = 1'b0;
-    reg [6:0] accepted_bytes = 7'd0;
-
-    wire [7:0] frame_type = 8'h06;
-    wire [7:0] frame_payload_len = 8'd8;
-    wire [143:0] frame_payload = 144'h0800_1234_0000_2801;
-    wire temperature_force_ff = 1'b1;
-
-    prod2u_p4_normal_v3_tx dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .frame_valid(frame_valid),
-        .frame_ready(frame_ready),
-        .frame_type(frame_type),
-        .frame_payload_len(frame_payload_len),
-        .frame_payload(frame_payload),
-        .temperature_start(temperature_start),
-        .temperature_force_ff(temperature_force_ff),
-        .temperature_rd_req(temperature_rd_req),
-        .temperature_rd_addr(temperature_rd_addr),
-        .temperature_rd_valid(temperature_rd_valid),
-        .temperature_rd_data(temperature_rd_data),
-        .temperature_done(temperature_done),
-        .tx_valid(tx_valid),
-        .tx_ready(tx_ready),
-        .tx_data(tx_data)
-    );
-
-    always @(posedge clk) begin
-        past_valid <= 1'b1;
-        rst_n <= 1'b1;
-        temperature_start <= 1'b0;
-        temperature_rd_valid <= temperature_rd_req;
-        if (temperature_rd_req) begin
-            temperature_rd_data <= {3'd0, temperature_rd_addr};
-        end
-
-        if (!rst_n) begin
-            frame_valid <= 1'b0;
-            temperature_start <= 1'b0;
-            requests_launched <= 1'b0;
-            accepted_bytes <= 7'd0;
-        end else begin
-            if (!requests_launched) begin
-                frame_valid <= 1'b1;
-                temperature_start <= 1'b1;
-                requests_launched <= 1'b1;
-            end
-            if (frame_ready) begin
-                frame_valid <= 1'b0;
-            end
-
-            assert(!(frame_ready && temperature_done));
-            assert(!(frame_ready && temperature_rd_req));
-
-            if (past_valid && $past(tx_valid && !tx_ready)) begin
-                assert(tx_valid);
-                assert($stable(tx_data));
-            end
-
-            if (tx_valid && tx_ready) begin
-                assert(accepted_bytes < 7'd59);
-                case (accepted_bytes)
-                    7'd0, 7'd24: assert(tx_data == 8'ha5);
-                    7'd1, 7'd25: assert(tx_data == 8'h5a);
-                    7'd2, 7'd26: assert(tx_data == 8'h02);
-                    7'd3, 7'd27: assert(tx_data == 8'h04);
-                    7'd4: assert(tx_data == 8'h06);
-                    7'd13: assert(tx_data == 8'h08);
-                    7'd28: assert(tx_data == 8'h10);
-                    7'd29: assert(tx_data == 8'h1b);
-                    default: begin
-                    end
-                endcase
-                accepted_bytes <= accepted_bytes + 7'd1;
-            end
-
-            if (frame_ready) assert(accepted_bytes == 7'd24);
-            if (temperature_done) assert(accepted_bytes == 7'd59);
-            cover(frame_ready);
-            cover(temperature_done);
-        end
-    end
-endmodule

+ 0 - 318
tests/sim/prod2u_p4_axis_force_jog_v1_tb.v

@@ -1,318 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_axis_force_jog_v1_tb;
-    localparam integer DIR_SETUP_CYCLES = 3;
-    localparam integer STEP_HALF_CYCLES = 2;
-
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg command_start = 1'b0;
-    reg command_dir = 1'b0;
-    reg [15:0] command_steps = 16'd1;
-
-    wire step_out;
-    wire dir_out;
-    wire started_pulse;
-
-    reg prod_command_start = 1'b0;
-    reg prod_command_dir = 1'b0;
-    reg [15:0] prod_command_steps = 16'd2;
-    wire prod_step_out;
-    wire prod_dir_out;
-    wire prod_started_pulse;
-
-    integer failures = 0;
-    integer cycle_index = 0;
-    integer rise_count = 0;
-    integer fall_count = 0;
-    integer started_count = 0;
-    integer last_rise_cycle = -1;
-    integer last_fall_cycle = -1;
-    integer command_cycle;
-    integer guard;
-    reg previous_step = 1'b0;
-    reg check_widths = 1'b1;
-    time prod_command_time;
-    time prod_first_rise_time;
-    time prod_first_fall_time;
-    time prod_second_rise_time;
-    time prod_second_fall_time;
-
-    always #5 clk = ~clk;
-
-    prod2u_p4_axis_executor #(
-        .DIR_SETUP_CYCLES(DIR_SETUP_CYCLES),
-        .STEP_HALF_CYCLES(STEP_HALF_CYCLES)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .command_start(command_start),
-        .command_dir(command_dir),
-        .command_steps(command_steps),
-        .step_out(step_out),
-        .dir_out(dir_out),
-        .started_pulse(started_pulse)
-    );
-
-    prod2u_p4_axis_executor prod_dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .command_start(prod_command_start),
-        .command_dir(prod_command_dir),
-        .command_steps(prod_command_steps),
-        .step_out(prod_step_out),
-        .dir_out(prod_dir_out),
-        .started_pulse(prod_started_pulse)
-    );
-
-    task fail;
-        input [8*120-1:0] message;
-        begin
-            failures = failures + 1;
-            $display("AXIS_FIXED_FAIL: %0s", message);
-        end
-    endtask
-
-    always @(posedge clk) begin
-        #1;
-        cycle_index = cycle_index + 1;
-
-        if (!rst_n) begin
-            previous_step = 1'b0;
-        end else begin
-            if (!previous_step && step_out) begin
-                rise_count = rise_count + 1;
-                last_rise_cycle = cycle_index;
-                if (!started_pulse && (started_count == 0)) begin
-                    fail("first STEP rise did not assert started_pulse");
-                end
-                if (check_widths && (last_fall_cycle >= 0) &&
-                    ((cycle_index - last_fall_cycle) != STEP_HALF_CYCLES)) begin
-                    fail("inter-step low phase had the wrong width");
-                end
-            end
-
-            if (previous_step && !step_out) begin
-                fall_count = fall_count + 1;
-                if (check_widths &&
-                    ((cycle_index - last_rise_cycle) != STEP_HALF_CYCLES)) begin
-                    fail("STEP high phase had the wrong width");
-                end
-                last_fall_cycle = cycle_index;
-            end
-
-            if (started_pulse) begin
-                started_count = started_count + 1;
-                if (!step_out) begin
-                    fail("started_pulse asserted without STEP high");
-                end
-                if ((rise_count != 1) && check_widths) begin
-                    fail("started_pulse was not limited to the first STEP rise");
-                end
-            end
-        end
-
-        previous_step = step_out;
-    end
-
-    task reset_axis;
-        begin
-            rst_n = 1'b0;
-            command_start = 1'b0;
-            command_dir = 1'b0;
-            command_steps = 16'd1;
-            rise_count = 0;
-            fall_count = 0;
-            started_count = 0;
-            last_rise_cycle = -1;
-            last_fall_cycle = -1;
-            previous_step = 1'b0;
-            check_widths = 1'b1;
-            repeat (3) @(negedge clk);
-            rst_n = 1'b1;
-            repeat (2) @(negedge clk);
-            if (step_out || started_pulse) begin
-                fail("reset did not leave STEP and started_pulse low");
-            end
-        end
-    endtask
-
-    task issue_command;
-        input direction;
-        input [15:0] steps;
-        begin
-            @(negedge clk);
-            command_dir = direction;
-            command_steps = steps;
-            command_start = 1'b1;
-            @(posedge clk);
-            #1;
-            command_cycle = cycle_index;
-            if (step_out || started_pulse || (dir_out !== direction)) begin
-                fail("command acceptance did not force STEP low and latch DIR");
-            end
-            @(negedge clk);
-            command_start = 1'b0;
-        end
-    endtask
-
-    task wait_for_rises;
-        input integer expected;
-        input integer maximum_cycles;
-        begin
-            guard = 0;
-            while ((rise_count < expected) && (guard < maximum_cycles)) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (rise_count != expected) begin
-                fail("command did not produce the requested STEP rises");
-            end
-        end
-    endtask
-
-    task run_exact_count;
-        input direction;
-        input [15:0] steps;
-        integer first_rise_cycle;
-        begin
-            reset_axis();
-            issue_command(direction, steps);
-            wait_for_rises(steps, (steps * STEP_HALF_CYCLES * 2) +
-                DIR_SETUP_CYCLES + 32);
-            first_rise_cycle = command_cycle + DIR_SETUP_CYCLES;
-            if ((last_rise_cycle < first_rise_cycle) ||
-                (started_count != 1) || (dir_out !== direction)) begin
-                fail("exact-count command violated setup, started, or DIR contract");
-            end
-            guard = 0;
-            while ((fall_count < steps) && (guard < STEP_HALF_CYCLES + 8)) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            repeat (STEP_HALF_CYCLES + 2) @(negedge clk);
-            if ((rise_count != steps) || (fall_count != steps) || step_out ||
-                started_pulse || (started_count != 1)) begin
-                fail("axis did not retire after the exact raw 16-bit step count");
-            end
-        end
-    endtask
-
-    initial begin
-        // Values above the former 800-step cap must execute in full.
-        run_exact_count(1'b0, 16'd1);
-        run_exact_count(1'b1, 16'd799);
-        run_exact_count(1'b0, 16'd800);
-        run_exact_count(1'b1, 16'd801);
-        run_exact_count(1'b0, 16'd8191);
-        run_exact_count(1'b1, 16'hffff);
-
-        // A setup-phase replacement restarts setup and suppresses the old move.
-        reset_axis();
-        issue_command(1'b0, 16'd7);
-        @(negedge clk);
-        issue_command(1'b1, 16'd2);
-        wait_for_rises(2, 64);
-        repeat (STEP_HALF_CYCLES * 2 + 4) @(negedge clk);
-        if ((rise_count != 2) || (fall_count != 2) ||
-            (started_count != 1) || !dir_out) begin
-            fail("DIR_SETUP replacement did not fully supersede the old command");
-        end
-
-        // A high-phase replacement has absolute priority: STEP goes low on the
-        // acceptance edge, then the replacement waits a fresh setup interval.
-        reset_axis();
-        issue_command(1'b0, 16'd7);
-        wait_for_rises(1, 32);
-        check_widths = 1'b0;
-        issue_command(1'b1, 16'd3);
-        if (step_out || started_pulse || !dir_out) begin
-            fail("STEP_HIGH replacement did not immediately force STEP low");
-        end
-        rise_count = 0;
-        fall_count = 0;
-        started_count = 0;
-        previous_step = 1'b0;
-        last_rise_cycle = -1;
-        last_fall_cycle = -1;
-        check_widths = 1'b1;
-        wait_for_rises(3, 64);
-        repeat (STEP_HALF_CYCLES * 2 + 4) @(negedge clk);
-        if ((rise_count != 3) || (fall_count != 3) ||
-            (started_count != 1) || !dir_out) begin
-            fail("STEP_HIGH replacement did not execute only the new command");
-        end
-
-        // A low-phase replacement also starts a fresh setup and discards tail.
-        reset_axis();
-        issue_command(1'b0, 16'd7);
-        wait_for_rises(1, 32);
-        while (step_out) @(negedge clk);
-        issue_command(1'b1, 16'd2);
-        rise_count = 0;
-        fall_count = 0;
-        started_count = 0;
-        previous_step = 1'b0;
-        last_rise_cycle = -1;
-        last_fall_cycle = -1;
-        wait_for_rises(2, 64);
-        repeat (STEP_HALF_CYCLES * 2 + 4) @(negedge clk);
-        if ((rise_count != 2) || (fall_count != 2) ||
-            (started_count != 1) || !dir_out) begin
-            fail("STEP_LOW replacement did not execute only the new command");
-        end
-
-        // Default production parameters at 25 MHz: 25,000 cycles of setup,
-        // followed by 12,500 high and 12,500 low cycles per STEP.
-        reset_axis();
-        @(negedge clk);
-        prod_command_dir = 1'b1;
-        prod_command_steps = 16'd2;
-        prod_command_start = 1'b1;
-        @(posedge clk);
-        prod_command_time = $time;
-        #1;
-        if (prod_step_out || prod_started_pulse || !prod_dir_out) begin
-            fail("production command did not latch with STEP low");
-        end
-        @(negedge clk);
-        prod_command_start = 1'b0;
-
-        @(posedge prod_step_out);
-        prod_first_rise_time = $time;
-        #1;
-        if (!prod_started_pulse) begin
-            fail("production first STEP rise lacked started_pulse");
-        end
-        @(negedge prod_step_out);
-        prod_first_fall_time = $time;
-        @(posedge prod_step_out);
-        prod_second_rise_time = $time;
-        #1;
-        if (prod_started_pulse) begin
-            fail("production second STEP rise repeated started_pulse");
-        end
-        @(negedge prod_step_out);
-        prod_second_fall_time = $time;
-
-        if ((prod_first_rise_time - prod_command_time) != 250000ns) begin
-            fail("production DIR setup was not exactly 25,000 clocks");
-        end
-        if ((prod_first_fall_time - prod_first_rise_time) != 125000ns) begin
-            fail("production STEP high phase was not exactly 12,500 clocks");
-        end
-        if ((prod_second_rise_time - prod_first_fall_time) != 125000ns) begin
-            fail("production STEP low phase was not exactly 12,500 clocks");
-        end
-        if ((prod_second_fall_time - prod_second_rise_time) != 125000ns) begin
-            fail("production second STEP high phase was not exactly 12,500 clocks");
-        end
-
-        if (failures != 0) begin
-            $fatal(1, "prod2u_p4_axis_force_jog_v1_tb failures=%0d", failures);
-        end
-
-        $display("PASS: prod2u_p4_axis_force_jog_v1_tb");
-        $finish;
-    end
-endmodule

+ 0 - 56
tests/sim/prod2u_p4_axis_jog_16bit_tb.v

@@ -1,56 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_axis_jog_16bit_tb;
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg command_start = 1'b0;
-    reg command_dir = 1'b0;
-    reg [15:0] command_steps = 16'hffff;
-    wire step_out;
-    wire dir_out;
-    wire started_pulse;
-
-    integer rises = 0;
-    integer started = 0;
-    integer guard = 0;
-
-    always #5 clk = ~clk;
-    always @(posedge step_out) rises = rises + 1;
-    always @(posedge clk) begin
-        #1;
-        if (started_pulse) started = started + 1;
-    end
-
-    prod2u_p4_axis_executor #(
-        .DIR_SETUP_CYCLES(1),
-        .STEP_HALF_CYCLES(1)
-    ) dut (
-        .clk(clk), .rst_n(rst_n),
-        .command_start(command_start), .command_dir(command_dir),
-        .command_steps(command_steps), .step_out(step_out),
-        .dir_out(dir_out), .started_pulse(started_pulse)
-    );
-
-    initial begin
-        repeat (3) @(negedge clk);
-        rst_n = 1'b1;
-        @(negedge clk);
-        command_dir = 1'b1;
-        command_start = 1'b1;
-        @(negedge clk);
-        command_start = 1'b0;
-
-        while ((rises < 65535) && (guard < 140000)) begin
-            @(negedge clk);
-            guard = guard + 1;
-        end
-        repeat (4) @(negedge clk);
-
-        if ((rises != 65535) || (started != 1) || !dir_out || step_out) begin
-            $fatal(1, "16-bit JOG mismatch rises=%0d started=%0d dir=%0d step=%0d",
-                rises, started, dir_out, step_out);
-        end
-        $display("PASS: prod2u_p4_axis_jog_16bit_tb");
-        $finish;
-    end
-endmodule

+ 0 - 56
tests/sim/prod2u_p4_cdc_sync_depth_tb.v

@@ -1,56 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_cdc_sync_depth_tb;
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg command_start = 1'b0;
-    reg command_dir = 1'b0;
-    reg [15:0] command_steps = 16'd12;
-    reg legacy_limit = 1'b0;
-    reg legacy_force_stop = 1'b0;
-    reg legacy_disabled = 1'b0;
-    reg legacy_watchdog = 1'b0;
-    wire step_out;
-    wire dir_out;
-    wire started_pulse;
-
-    integer rises = 0;
-    integer guard = 0;
-
-    always #5 clk = ~clk;
-    always @(posedge step_out) rises = rises + 1;
-
-    prod2u_p4_axis_executor #(
-        .DIR_SETUP_CYCLES(2),
-        .STEP_HALF_CYCLES(2)
-    ) dut (
-        .clk(clk), .rst_n(rst_n),
-        .command_start(command_start), .command_dir(command_dir),
-        .command_steps(command_steps), .step_out(step_out),
-        .dir_out(dir_out), .started_pulse(started_pulse)
-    );
-
-    initial begin
-        repeat (3) @(negedge clk);
-        rst_n = 1'b1;
-        @(negedge clk);
-        command_start = 1'b1;
-        @(negedge clk);
-        command_start = 1'b0;
-
-        while ((rises < 12) && (guard < 128)) begin
-            @(negedge clk);
-            legacy_limit = ~legacy_limit;
-            legacy_force_stop = ~legacy_force_stop;
-            legacy_disabled = ~legacy_disabled;
-            legacy_watchdog = ~legacy_watchdog;
-            guard = guard + 1;
-        end
-        repeat (8) @(negedge clk);
-        if ((rises != 12) || step_out || (dir_out !== 1'b0)) begin
-            $fatal(1, "legacy unconnected safety signals affected fixed motion");
-        end
-        $display("PASS: prod2u_p4_cdc_sync_depth_tb");
-        $finish;
-    end
-endmodule

+ 0 - 447
tests/sim/prod2u_p4_completion_ack_contract_tb.v

@@ -1,447 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_completion_ack_contract_tb;
-    localparam [7:0] FT_HOST_BATCH_CMD = 8'h07;
-    localparam [7:0] FT_MOTION_CMD = 8'h11;
-    localparam [7:0] FT_HOST_ACK = 8'h06;
-    localparam [7:0] FT_MOTION_STATUS = 8'h12;
-    localparam [7:0] CMD_SET_SNAPSHOT = 8'h2a;
-    localparam [7:0] MOTION_JOG = 8'h35;
-    localparam [7:0] MOTION_GET_STATUS = 8'h37;
-    localparam [7:0] STATUS_OK = 8'h00;
-
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg request_valid = 1'b0;
-    wire request_ready;
-    reg [7:0] request_type = 8'd0;
-    reg [5:0] request_length = 6'd0;
-    reg [271:0] request_payload = 272'd0;
-    reg [15:0] request_crc16 = 16'd0;
-    reg fast_jog_valid = 1'b0;
-    reg [1:0] fast_jog_axis = 2'd0;
-    reg fast_jog_dir = 1'b0;
-    reg [15:0] fast_jog_steps = 16'd1;
-    wire frame_valid;
-    wire [7:0] frame_type;
-    wire [7:0] frame_payload_len;
-    wire [143:0] frame_payload;
-    wire [191:0] ptc_percent;
-    wire [31:0] fan_percent;
-    wire [7:0] solenoid_percent;
-    wire [2:0] step_out;
-    wire [2:0] dir_out;
-    wire en_n;
-    wire disabled;
-    wire watchdog_timeout;
-
-    integer failures = 0;
-    integer guard;
-    integer index;
-    integer x_rises = 0;
-    integer y_rises = 0;
-    integer x_dir0_rises = 0;
-    integer x_dir1_rises = 0;
-    integer y_dir0_rises = 0;
-    reg overlap_seen = 1'b0;
-
-    always #5 clk = ~clk;
-    always @(posedge step_out[0]) begin
-        x_rises = x_rises + 1;
-        if (dir_out[0]) x_dir1_rises = x_dir1_rises + 1;
-        else x_dir0_rises = x_dir0_rises + 1;
-    end
-    always @(posedge step_out[1]) begin
-        y_rises = y_rises + 1;
-        if (!dir_out[1]) y_dir0_rises = y_dir0_rises + 1;
-    end
-    always @(posedge clk) begin
-        #1;
-        if (rst_n && step_out[0] && step_out[1]) overlap_seen = 1'b1;
-    end
-
-    prod2u_p4_normal_v3_core #(
-        .CLK_HZ(64),
-        .WATCHDOG_SECONDS(1),
-        .DIR_SETUP_CYCLES(8),
-        .STEP_HALF_CYCLES(2)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(request_crc16),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(fast_jog_axis),
-        .fast_jog_dir(fast_jog_dir),
-        .fast_jog_steps(fast_jog_steps),
-        .frame_valid(frame_valid),
-        .frame_ready(1'b1),
-        .frame_type(frame_type),
-        .frame_payload_len(frame_payload_len),
-        .frame_payload(frame_payload),
-        .ptc_percent(ptc_percent),
-        .fan_percent(fan_percent),
-        .solenoid_percent(solenoid_percent),
-        .state_hash16(),
-        .step_out(step_out),
-        .dir_out(dir_out),
-        .en_n(en_n),
-        .disabled(disabled),
-        .watchdog_timeout(watchdog_timeout)
-    );
-
-    task fail;
-        input [8*120-1:0] message;
-        begin
-            failures = failures + 1;
-            $display("START_ACK_FAIL: %0s", message);
-        end
-    endtask
-
-    task reset_core;
-        begin
-            rst_n = 1'b0;
-            request_valid = 1'b0;
-            request_type = 8'd0;
-            request_length = 6'd0;
-            request_payload = 272'd0;
-            request_crc16 = 16'd0;
-            fast_jog_valid = 1'b0;
-            fast_jog_axis = 2'd0;
-            fast_jog_dir = 1'b0;
-            fast_jog_steps = 16'd1;
-            overlap_seen = 1'b0;
-            repeat (4) @(negedge clk);
-            rst_n = 1'b1;
-            repeat (4) @(negedge clk);
-        end
-    endtask
-
-    task wait_ready;
-        input [8*80-1:0] label_text;
-        begin
-            guard = 0;
-            while (!request_ready && guard < 1024) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (!request_ready) fail(label_text);
-        end
-    endtask
-
-    task pulse_jog;
-        input [1:0] axis;
-        input direction;
-        input [15:0] steps;
-        input [15:0] crc;
-        begin
-            @(negedge clk);
-            request_crc16 = crc;
-            fast_jog_axis = axis;
-            fast_jog_dir = direction;
-            fast_jog_steps = steps;
-            fast_jog_valid = 1'b1;
-            @(negedge clk);
-            fast_jog_valid = 1'b0;
-        end
-    endtask
-
-    task wait_jog_ack_after_rise;
-        input [1:0] axis;
-        input integer rise_before;
-        input [8*80-1:0] label_text;
-        integer observed_rises;
-        reg early_failed;
-        begin
-            early_failed = 1'b0;
-            guard = 0;
-            while (!(frame_valid && (frame_type == FT_HOST_ACK)) &&
-                   guard < 1024) begin
-                @(posedge clk);
-                #1;
-                observed_rises = (axis == 2'd0) ?
-                    (x_rises - rise_before) : (y_rises - rise_before);
-                if (frame_valid && (frame_type == FT_HOST_ACK) &&
-                    (observed_rises == 0)) begin
-                    fail(label_text);
-                    early_failed = 1'b1;
-                end
-                guard = guard + 1;
-            end
-            if (!(frame_valid && (frame_type == FT_HOST_ACK))) begin
-                fail("JOG start ACK was not observed");
-            end else begin
-                observed_rises = (axis == 2'd0) ?
-                    (x_rises - rise_before) : (y_rises - rise_before);
-                if ((observed_rises == 0) && !early_failed) fail(label_text);
-                if (frame_payload[7:0] !== 8'h01 ||
-                    frame_payload[15:8] !== MOTION_JOG ||
-                    frame_payload[23:16] !== STATUS_OK) begin
-                    fail("JOG start ACK payload mismatch");
-                end
-            end
-            wait_ready("core did not retire JOG start ACK");
-        end
-    endtask
-
-    task pulse_snapshot;
-        begin
-            wait_ready("snapshot request did not become ready");
-            @(negedge clk);
-            request_type = FT_HOST_BATCH_CMD;
-            request_length = 6'd34;
-            request_payload = 272'd0;
-            request_payload[7:0] = CMD_SET_SNAPSHOT;
-            request_payload[15:8] = 8'd0;
-            for (index = 0; index < 24; index = index + 1)
-                request_payload[(index + 2) * 8 +: 8] = 8'd25;
-            request_payload[26 * 8 +: 8] = 8'd40;
-            request_payload[27 * 8 +: 8] = 8'd40;
-            request_payload[28 * 8 +: 8] = 8'd40;
-            request_payload[29 * 8 +: 8] = 8'd40;
-            request_payload[30 * 8 +: 8] = 8'd100;
-            request_payload[31 * 8 +: 8] = 8'd100;
-            request_payload[32 * 8 +: 8] = 8'd0;
-            request_payload[33 * 8 +: 8] = 8'd100;
-            request_crc16 = 16'h7201;
-            request_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            request_valid = 1'b0;
-        end
-    endtask
-
-    task wait_snapshot_ack;
-        begin
-            guard = 0;
-            while (!(frame_valid && (frame_type == FT_HOST_ACK)) &&
-                   guard < 1024) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if (!(frame_valid && (frame_type == FT_HOST_ACK))) begin
-                fail("snapshot ACK was not observed");
-            end else if (frame_payload[7:0] !== 8'h01 ||
-                frame_payload[15:8] !== CMD_SET_SNAPSHOT ||
-                frame_payload[23:16] !== STATUS_OK) begin
-                fail("snapshot ACK payload mismatch");
-            end
-            wait_ready("core did not retire snapshot ACK");
-        end
-    endtask
-
-    task query_unknown_status;
-        reg [7:0] expected_flags;
-        begin
-            expected_flags = 8'h02 |
-                ({7'd0, disabled} << 2) |
-                ({7'd0, watchdog_timeout} << 3);
-            wait_ready("motor status request did not become ready");
-            @(negedge clk);
-            request_type = FT_MOTION_CMD;
-            request_length = 6'd8;
-            request_payload = 272'd0;
-            request_payload[7:0] = MOTION_GET_STATUS;
-            request_crc16 = 16'h7301;
-            request_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            request_valid = 1'b0;
-
-            guard = 0;
-            while (!(frame_valid && (frame_type == FT_HOST_ACK)) &&
-                   guard < 256) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if (!(frame_valid && (frame_type == FT_HOST_ACK)))
-                fail("motor status ACK was not observed");
-
-            guard = 0;
-            while (!(frame_valid && (frame_type == FT_MOTION_STATUS)) &&
-                   guard < 256) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if (!(frame_valid && (frame_type == FT_MOTION_STATUS))) begin
-                fail("constant MOTION_STATUS follow-up was not observed");
-            end else if (frame_payload_len !== 8'd10 ||
-                frame_payload[7:0] !== expected_flags ||
-                frame_payload[23:8] !== 16'd0 ||
-                frame_payload[71:24] !== 48'hffffffffffff ||
-                frame_payload[79:72] !== 8'd0) begin
-                $display("STATUS_MISMATCH payload=%020h", frame_payload[79:0]);
-                fail("MOTION_STATUS did not report unknown position and live flags");
-            end
-            wait_ready("core did not retire motor status response");
-        end
-    endtask
-
-    task run_cross_axis_overlap;
-        integer x_before;
-        integer y_before;
-        begin
-            reset_core();
-            x_before = x_rises;
-            y_before = y_rises;
-
-            pulse_jog(2'd0, 1'b0, 16'd20, 16'h7101);
-            wait_jog_ack_after_rise(2'd0, x_before,
-                "X JOG ACK was emitted before the first X STEP");
-            if (!disabled || watchdog_timeout)
-                fail("JOG unexpectedly armed or expired the watchdog");
-
-            pulse_jog(2'd1, 1'b0, 16'd6, 16'h7102);
-            wait_jog_ack_after_rise(2'd1, y_before,
-                "Y JOG ACK was emitted before the first Y STEP");
-
-            guard = 0;
-            while (((x_rises - x_before) < 20 ||
-                    (y_rises - y_before) < 6) && guard < 4096) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if ((x_rises - x_before) != 20 ||
-                (y_rises - y_before) != 6) begin
-                fail("X/Y JOG counts changed after start ACK");
-            end
-            if (!overlap_seen)
-                fail("X and Y did not overlap after independent start ACKs");
-        end
-    endtask
-
-    task run_same_axis_replace;
-        integer dir0_before;
-        integer dir1_before;
-        integer x_before;
-        begin
-            reset_core();
-            dir0_before = x_dir0_rises;
-            dir1_before = x_dir1_rises;
-
-            x_before = x_rises;
-            pulse_jog(2'd0, 1'b0, 16'd20, 16'h7111);
-            wait_jog_ack_after_rise(2'd0, x_before,
-                "initial X ACK was emitted before its first STEP");
-
-            x_before = x_rises;
-            pulse_jog(2'd0, 1'b1, 16'd3, 16'h7112);
-            wait_jog_ack_after_rise(2'd0, x_before,
-                "replacement X ACK was emitted before its first STEP");
-
-            guard = 0;
-            while (((x_dir1_rises - dir1_before) < 3) && guard < 2048) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if ((x_dir1_rises - dir1_before) != 3)
-                fail("same-axis replacement did not execute three new-direction steps");
-            if ((x_dir0_rises - dir0_before) >= 20)
-                fail("same-axis replacement did not replace the old tail");
-        end
-    endtask
-
-    task run_snapshot_no_motion;
-        integer x_before;
-        integer y_before;
-        reg [2:0] dir_before;
-        begin
-            reset_core();
-            x_before = x_rises;
-            y_before = y_rises;
-            dir_before = dir_out;
-            pulse_snapshot();
-            wait_snapshot_ack();
-            if (ptc_percent[7:0] != 8'd25 ||
-                fan_percent != {4{8'd40}} || solenoid_percent != 8'd100) begin
-                fail("snapshot did not commit non-motor outputs");
-            end
-            repeat (16) @(posedge clk);
-            #1;
-            if (x_rises != x_before || y_rises != y_before ||
-                step_out != 3'b000 || dir_out != dir_before) begin
-                fail("snapshot XYZ fields affected motor outputs");
-            end
-
-            guard = 0;
-            while (!dut.watchdog_expiry_due && guard < 256) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if (!dut.watchdog_expiry_due)
-                fail("snapshot watchdog never reached expiry boundary");
-            if (!request_ready)
-                fail("watchdog expiry boundary blocked an otherwise idle request");
-
-            guard = 0;
-            while (!watchdog_timeout && guard < 8) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if (!watchdog_timeout || ptc_percent != 192'd0 ||
-                fan_percent != {4{8'd30}} || solenoid_percent != 8'd0) begin
-                fail("snapshot watchdog did not retain non-motor safety");
-            end
-        end
-    endtask
-
-    task run_invalid_snapshot_does_not_arm;
-        begin
-            reset_core();
-            wait_ready("invalid snapshot request did not become ready");
-            @(negedge clk);
-            request_type = FT_HOST_BATCH_CMD;
-            request_length = 6'd34;
-            request_payload = 272'd0;
-            request_payload[7:0] = CMD_SET_SNAPSHOT;
-            request_payload[2 * 8 +: 8] = 8'd101;
-            request_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            request_valid = 1'b0;
-
-            guard = 0;
-            while (!(frame_valid && (frame_type == FT_HOST_ACK)) &&
-                   guard < 256) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if (!(frame_valid && (frame_type == FT_HOST_ACK)))
-                fail("invalid snapshot response was not observed");
-            wait_ready("core did not retire invalid snapshot response");
-            repeat (80) @(posedge clk);
-            #1;
-            if (!disabled || watchdog_timeout || dut.watchdog_armed)
-                fail("invalid snapshot armed or expired watchdog");
-        end
-    endtask
-
-    initial begin
-        run_cross_axis_overlap();
-        query_unknown_status();
-        run_same_axis_replace();
-        run_invalid_snapshot_does_not_arm();
-        run_snapshot_no_motion();
-
-        if (failures != 0)
-            $fatal(1, "prod2u_p4_completion_ack_contract_tb RED failures=%0d",
-                failures);
-        $display("PASS: prod2u_p4_completion_ack_contract_tb");
-        $finish;
-    end
-endmodule

+ 0 - 255
tests/sim/prod2u_p4_core_watchdog_refresh_tb.v

@@ -1,255 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_core_watchdog_refresh_tb;
-    localparam [7:0] FT_HOST_CMD = 8'h05;
-    localparam [7:0] FT_HOST_BATCH_CMD = 8'h07;
-    localparam [7:0] FT_MOTION_CMD = 8'h11;
-    localparam [7:0] FT_HOST_ACK = 8'h06;
-    localparam [7:0] CMD_DISABLE = 8'h26;
-    localparam [7:0] CMD_SET_SNAPSHOT = 8'h2a;
-    localparam [7:0] MOTION_JOG = 8'h35;
-    localparam [7:0] MOTION_GET_STATUS = 8'h37;
-    localparam [7:0] STATUS_OK = 8'h00;
-
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg request_valid = 1'b0;
-    wire request_ready;
-    reg [7:0] request_type = 8'd0;
-    reg [5:0] request_length = 6'd0;
-    reg [271:0] request_payload = 272'd0;
-    reg [15:0] request_crc16 = 16'd0;
-    reg fast_jog_valid = 1'b0;
-    reg [1:0] fast_jog_axis = 2'd0;
-    reg fast_jog_dir = 1'b0;
-    reg [15:0] fast_jog_steps = 16'd1;
-    wire frame_valid;
-    wire [7:0] frame_type;
-    wire [143:0] frame_payload;
-    wire [191:0] ptc_percent;
-    wire [31:0] fan_percent;
-    wire [7:0] solenoid_percent;
-    wire [2:0] step_out;
-    wire en_n;
-    wire disabled;
-    wire watchdog_timeout;
-
-    integer guard;
-    integer index;
-    integer x_rises = 0;
-    integer x_before;
-    reg [271:0] payload;
-
-    always #5 clk = ~clk;
-    always @(posedge step_out[0]) x_rises = x_rises + 1;
-
-    prod2u_p4_normal_v3_core #(
-        .CLK_HZ(32),
-        .WATCHDOG_SECONDS(1),
-        .DIR_SETUP_CYCLES(1),
-        .STEP_HALF_CYCLES(1)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(request_crc16),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(fast_jog_axis),
-        .fast_jog_dir(fast_jog_dir),
-        .fast_jog_steps(fast_jog_steps),
-        .frame_valid(frame_valid),
-        .frame_ready(1'b1),
-        .frame_type(frame_type),
-        .frame_payload_len(),
-        .frame_payload(frame_payload),
-        .ptc_percent(ptc_percent),
-        .fan_percent(fan_percent),
-        .solenoid_percent(solenoid_percent),
-        .state_hash16(),
-        .step_out(step_out),
-        .dir_out(),
-        .en_n(en_n),
-        .disabled(disabled),
-        .watchdog_timeout(watchdog_timeout)
-    );
-
-    task fail;
-        input [8*120-1:0] message;
-        begin
-            $display("WATCHDOG_REFRESH_FAIL: %0s", message);
-            $fatal(1);
-        end
-    endtask
-
-    task wait_ready;
-        begin
-            guard = 0;
-            while (!request_ready && guard < 1024) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (!request_ready) fail("request_ready timeout");
-        end
-    endtask
-
-    task send_request;
-        input [7:0] kind;
-        input [5:0] length;
-        input [271:0] bytes;
-        begin
-            wait_ready();
-            @(negedge clk);
-            request_type = kind;
-            request_length = length;
-            request_payload = bytes;
-            request_crc16 = request_crc16 + 16'd1;
-            request_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            request_valid = 1'b0;
-        end
-    endtask
-
-    task expect_ack;
-        input [7:0] command;
-        begin
-            guard = 0;
-            while (!(frame_valid && frame_type == FT_HOST_ACK) && guard < 1024) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if (!(frame_valid && frame_type == FT_HOST_ACK) ||
-                frame_payload[7:0] !== 8'h01 ||
-                frame_payload[15:8] !== command ||
-                frame_payload[23:16] !== STATUS_OK)
-                fail("missing or malformed ACK");
-            wait_ready();
-        end
-    endtask
-
-    task issue_status;
-        begin
-            payload = 272'd0;
-            payload[7:0] = MOTION_GET_STATUS;
-            send_request(FT_MOTION_CMD, 6'd8, payload);
-            expect_ack(MOTION_GET_STATUS);
-        end
-    endtask
-
-    task issue_jog;
-        input [15:0] steps;
-        begin
-            @(negedge clk);
-            fast_jog_axis = 2'd0;
-            fast_jog_dir = 1'b1;
-            fast_jog_steps = steps;
-            fast_jog_valid = 1'b1;
-            @(negedge clk);
-            fast_jog_valid = 1'b0;
-            expect_ack(MOTION_JOG);
-        end
-    endtask
-
-    task issue_snapshot;
-        begin
-            payload = 272'd0;
-            payload[7:0] = CMD_SET_SNAPSHOT;
-            for (index = 2; index <= 29; index = index + 1)
-                payload[index * 8 +: 8] = 8'd20;
-            payload[30 * 8 +: 8] = 8'd100;
-            send_request(FT_HOST_BATCH_CMD, 6'd34, payload);
-            expect_ack(CMD_SET_SNAPSHOT);
-        end
-    endtask
-
-    initial begin
-        repeat (4) @(negedge clk);
-        rst_n = 1'b1;
-        repeat (2) @(negedge clk);
-
-        if (!disabled || dut.watchdog_armed || watchdog_timeout || en_n !== 1'b0)
-            fail("reset state mismatch");
-        issue_status();
-        if (!disabled || dut.watchdog_armed || watchdog_timeout)
-            fail("status query revived reset-disabled watchdog");
-
-        x_before = x_rises;
-        issue_jog(16'd20);
-        guard = 0;
-        while ((x_rises - x_before) < 20 && guard < 256) begin
-            @(posedge clk);
-            #1;
-            guard = guard + 1;
-        end
-        if ((x_rises - x_before) != 20 || !disabled ||
-            dut.watchdog_armed || watchdog_timeout)
-            fail("JOG armed watchdog or did not execute while disabled");
-
-        issue_snapshot();
-        repeat (2) @(posedge clk);
-        #1;
-        if (disabled || !dut.watchdog_armed || watchdog_timeout ||
-            ptc_percent != {24{8'd20}} || fan_percent != {4{8'd20}} ||
-            solenoid_percent != 8'd100)
-            fail("accepted snapshot did not arm watchdog");
-
-        x_before = x_rises;
-        issue_jog(16'd100);
-        issue_status();
-        if (!dut.watchdog_armed || disabled || watchdog_timeout)
-            fail("armed status query did not refresh watchdog");
-
-        guard = 0;
-        while (!dut.watchdog_expiry_due && guard < 128) begin
-            @(negedge clk);
-            guard = guard + 1;
-        end
-        if (!dut.watchdog_expiry_due || !request_ready)
-            fail("expiry boundary blocked request_ready");
-
-        payload = 272'd0;
-        payload[7:0] = MOTION_GET_STATUS;
-        request_type = FT_MOTION_CMD;
-        request_length = 6'd8;
-        request_payload = payload;
-        request_valid = 1'b1;
-        #1;
-        if (!request_ready || !dut.watchdog_command_refresh)
-            fail("simultaneous expiry/status request was not accepted");
-        @(posedge clk);
-        #1;
-        if (!watchdog_timeout || !disabled || dut.watchdog_armed ||
-            en_n !== 1'b0)
-            fail("expiry did not win over simultaneous refresh");
-        @(negedge clk);
-        request_valid = 1'b0;
-        expect_ack(MOTION_GET_STATUS);
-
-        payload = 272'd0;
-        payload[7:0] = CMD_DISABLE;
-        send_request(FT_HOST_CMD, 6'd4, payload);
-        expect_ack(CMD_DISABLE);
-        if (!disabled || watchdog_timeout || dut.watchdog_armed || en_n !== 1'b0)
-            fail("ordinary DISABLE did not clear watchdog state");
-
-        guard = 0;
-        while ((x_rises - x_before) < 100 && guard < 1024) begin
-            @(posedge clk);
-            #1;
-            guard = guard + 1;
-        end
-        if ((x_rises - x_before) != 100 || step_out[2:1] != 2'b00 ||
-            ptc_percent != 192'd0 || fan_percent != {4{8'd30}} ||
-            solenoid_percent != 8'd0 || en_n !== 1'b0)
-            fail("watchdog or DISABLE altered motor execution");
-
-        $display("PASS: prod2u_p4_core_watchdog_refresh_tb");
-        $finish;
-    end
-endmodule

+ 0 - 365
tests/sim/prod2u_p4_fast_jog_core_tb.v

@@ -1,365 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_fast_jog_core_tb;
-    localparam [7:0] FT_HOST_CMD = 8'h05;
-    localparam [7:0] FT_HOST_BATCH_CMD = 8'h07;
-    localparam [7:0] FT_HOST_ACK = 8'h06;
-    localparam [7:0] CMD_GET_STATUS = 8'h24;
-    localparam [7:0] CMD_SET_SNAPSHOT = 8'h2a;
-    localparam [7:0] MOTION_JOG = 8'h35;
-
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg request_valid = 1'b0;
-    wire request_ready;
-    reg [7:0] request_type = 8'd0;
-    reg [5:0] request_length = 6'd0;
-    reg [271:0] request_payload = 272'd0;
-    reg [15:0] request_crc16 = 16'd0;
-    reg fast_jog_valid = 1'b0;
-    reg [1:0] fast_jog_axis = 2'd0;
-    reg fast_jog_dir = 1'b0;
-    reg [15:0] fast_jog_steps = 16'd1;
-    wire frame_valid;
-    reg frame_ready = 1'b0;
-    wire [7:0] frame_type;
-    wire [7:0] frame_payload_len;
-    wire [143:0] frame_payload;
-    wire [191:0] ptc_percent;
-    wire [31:0] fan_percent;
-    wire [7:0] solenoid_percent;
-    wire [2:0] step_out;
-    wire [2:0] dir_out;
-    wire en_n;
-    wire disabled;
-    wire watchdog_timeout;
-
-    integer failures = 0;
-    integer guard;
-    integer index;
-    integer x_rises = 0;
-    integer y_rises = 0;
-    integer ack_count = 0;
-    reg [7:0] ack_commands [0:15];
-    reg overlap_seen = 1'b0;
-
-    always #5 clk = ~clk;
-    always @(posedge step_out[0]) x_rises = x_rises + 1;
-    always @(posedge step_out[1]) y_rises = y_rises + 1;
-
-    always @(negedge clk) begin
-        if (!rst_n) begin
-            ack_count = 0;
-        end else if (frame_valid && frame_ready && (frame_type == FT_HOST_ACK)) begin
-            ack_commands[ack_count] = frame_payload[15:8];
-            ack_count = ack_count + 1;
-        end
-    end
-
-    always @(posedge clk) begin
-        #1;
-        if (!rst_n) overlap_seen = 1'b0;
-        else if (step_out[0] && step_out[1]) overlap_seen = 1'b1;
-    end
-
-    prod2u_p4_normal_v3_core #(
-        .CLK_HZ(128),
-        .WATCHDOG_SECONDS(1),
-        .DIR_SETUP_CYCLES(8),
-        .STEP_HALF_CYCLES(2)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(request_crc16),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(fast_jog_axis),
-        .fast_jog_dir(fast_jog_dir),
-        .fast_jog_steps(fast_jog_steps),
-        .frame_valid(frame_valid),
-        .frame_ready(frame_ready),
-        .frame_type(frame_type),
-        .frame_payload_len(frame_payload_len),
-        .frame_payload(frame_payload),
-        .ptc_percent(ptc_percent),
-        .fan_percent(fan_percent),
-        .solenoid_percent(solenoid_percent),
-        .state_hash16(),
-        .step_out(step_out),
-        .dir_out(dir_out),
-        .en_n(en_n),
-        .disabled(disabled),
-        .watchdog_timeout(watchdog_timeout)
-    );
-
-    task fail;
-        input [8*120-1:0] message;
-        begin
-            failures = failures + 1;
-            $display("FAST_JOG_CORE_FAIL: %0s", message);
-        end
-    endtask
-
-    task reset_core;
-        begin
-            rst_n = 1'b0;
-            request_valid = 1'b0;
-            request_type = 8'd0;
-            request_length = 6'd0;
-            request_payload = 272'd0;
-            request_crc16 = 16'd0;
-            fast_jog_valid = 1'b0;
-            fast_jog_axis = 2'd0;
-            fast_jog_dir = 1'b0;
-            fast_jog_steps = 16'd1;
-            frame_ready = 1'b0;
-            repeat (4) @(negedge clk);
-            rst_n = 1'b1;
-            repeat (4) @(negedge clk);
-        end
-    endtask
-
-    task wait_request_ready;
-        input [8*80-1:0] label_text;
-        begin
-            guard = 0;
-            while (!request_ready && guard < 256) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (!request_ready) fail(label_text);
-        end
-    endtask
-
-    task pulse_get_status;
-        begin
-            wait_request_ready("GET_STATUS request never became ready");
-            @(negedge clk);
-            request_type = FT_HOST_CMD;
-            request_length = 6'd4;
-            request_payload = 272'd0;
-            request_payload[7:0] = CMD_GET_STATUS;
-            request_crc16 = 16'h2401;
-            request_valid = 1'b1;
-            @(negedge clk);
-            request_valid = 1'b0;
-        end
-    endtask
-
-    task pulse_snapshot;
-        begin
-            wait_request_ready("snapshot request never became ready");
-            @(negedge clk);
-            request_type = FT_HOST_BATCH_CMD;
-            request_length = 6'd34;
-            request_payload = 272'd0;
-            request_payload[7:0] = CMD_SET_SNAPSHOT;
-            for (index = 0; index < 24; index = index + 1)
-                request_payload[(index + 2) * 8 +: 8] = 8'd10;
-            for (index = 0; index < 4; index = index + 1)
-                request_payload[(index + 26) * 8 +: 8] = 8'd30;
-            request_payload[30 * 8 +: 8] = 8'd0;
-            request_crc16 = 16'h2a01;
-            request_valid = 1'b1;
-            @(negedge clk);
-            request_valid = 1'b0;
-        end
-    endtask
-
-    task pulse_fast_jog;
-        input [1:0] axis;
-        input direction;
-        input [15:0] steps;
-        begin
-            @(negedge clk);
-            fast_jog_axis = axis;
-            fast_jog_dir = direction;
-            fast_jog_steps = steps;
-            fast_jog_valid = 1'b1;
-            @(negedge clk);
-            fast_jog_valid = 1'b0;
-        end
-    endtask
-
-    task wait_axis_rises;
-        input [1:0] axis;
-        input integer baseline;
-        input integer expected;
-        input [8*100-1:0] label_text;
-        integer observed;
-        begin
-            guard = 0;
-            observed = 0;
-            while ((observed < expected) && (guard < 4096)) begin
-                @(posedge clk);
-                #1;
-                observed = (axis == 2'd0) ?
-                    (x_rises - baseline) : (y_rises - baseline);
-                guard = guard + 1;
-            end
-            if (observed != expected) begin
-                $display("FAST_JOG_COUNT axis=%0d expected=%0d observed=%0d",
-                    axis, expected, observed);
-                fail(label_text);
-            end
-        end
-    endtask
-
-    task wait_ack_total;
-        input integer expected;
-        input [8*100-1:0] label_text;
-        begin
-            guard = 0;
-            while ((ack_count < expected) && (guard < 1024)) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if (ack_count < expected) fail(label_text);
-        end
-    endtask
-
-    task run_stalled_response_case;
-        integer x_before;
-        begin
-            reset_core();
-            pulse_get_status();
-
-            guard = 0;
-            while (!frame_valid && guard < 64) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if (!frame_valid || frame_type != FT_HOST_ACK ||
-                frame_payload[15:8] != CMD_GET_STATUS)
-                fail("old GET_STATUS ACK was not held under TX backpressure");
-            if (request_ready)
-                fail("old response did not establish command_inflight backpressure");
-
-            x_before = x_rises;
-            pulse_fast_jog(2'd0, 1'b1, 16'd4);
-            wait_axis_rises(2'd0, x_before, 4,
-                "fast X JOG did not finish while the old response was stalled");
-            if (!frame_valid || frame_payload[15:8] != CMD_GET_STATUS)
-                fail("fast JOG replaced the stalled old ACK instead of queuing");
-            if (ack_count != 0)
-                fail("an ACK handshook while frame_ready was low");
-
-            frame_ready = 1'b1;
-            wait_ack_total(2, "stalled old ACK and pending JOG ACK did not drain");
-            if (ack_commands[0] != CMD_GET_STATUS ||
-                ack_commands[1] != MOTION_JOG)
-                fail("response order was not old ACK followed by JOG ACK");
-        end
-    endtask
-
-    task run_core_nonidle_case;
-        integer y_before;
-        begin
-            reset_core();
-            pulse_snapshot();
-            if (request_ready)
-                fail("snapshot did not put the core into a non-IDLE interval");
-            y_before = y_rises;
-            pulse_fast_jog(2'd1, 1'b0, 16'd3);
-            wait_axis_rises(2'd1, y_before, 3,
-                "fast Y JOG was blocked by the non-IDLE snapshot state");
-        end
-    endtask
-
-    task run_fast_ack_priority_case;
-        integer x_before;
-        begin
-            reset_core();
-            frame_ready = 1'b1;
-            x_before = x_rises;
-            pulse_fast_jog(2'd0, 1'b0, 16'd2);
-            if (request_ready)
-                fail("ordinary request remained ready while fast JOG ACK was pending");
-            wait_ack_total(1, "fast JOG ACK did not win the next response slot");
-            if (ack_commands[0] != MOTION_JOG)
-                fail("a subsequent ordinary request could precede the fast JOG ACK");
-            wait_axis_rises(2'd0, x_before, 2,
-                "fast ACK priority check changed X motion execution");
-        end
-    endtask
-
-    task run_latest_wins_ack_case;
-        integer x_before;
-        integer replacement_before;
-        begin
-            reset_core();
-            pulse_get_status();
-            guard = 0;
-            while (!frame_valid && guard < 64) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if (!frame_valid || frame_payload[15:8] != CMD_GET_STATUS)
-                fail("latest-wins case did not stall an old response");
-
-            x_before = x_rises;
-            pulse_fast_jog(2'd0, 1'b0, 16'd20);
-            wait_axis_rises(2'd0, x_before, 1,
-                "first dense JOG never reached its first STEP");
-
-            replacement_before = x_rises;
-            pulse_fast_jog(2'd0, 1'b1, 16'd2);
-            wait_axis_rises(2'd0, replacement_before, 2,
-                "latest dense JOG did not replace the old X motion");
-
-            frame_ready = 1'b1;
-            wait_ack_total(2,
-                "old response and latest dense JOG ACK did not drain");
-            repeat (64) @(posedge clk);
-            #1;
-            if (ack_count != 2 || ack_commands[0] != CMD_GET_STATUS ||
-                ack_commands[1] != MOTION_JOG)
-                fail("dense JOGs retained more than the latest pending ACK");
-        end
-    endtask
-
-    task run_cross_axis_case;
-        integer x_before;
-        integer y_before;
-        begin
-            reset_core();
-            frame_ready = 1'b1;
-            x_before = x_rises;
-            y_before = y_rises;
-
-            pulse_fast_jog(2'd0, 1'b0, 16'd20);
-            wait_ack_total(1, "X first STEP did not produce a JOG ACK");
-            if (ack_commands[0] != MOTION_JOG || x_rises == x_before)
-                fail("X ACK was not tied to the first X STEP");
-
-            pulse_fast_jog(2'd1, 1'b1, 16'd6);
-            wait_ack_total(2, "Y first STEP did not produce a JOG ACK");
-            wait_axis_rises(2'd0, x_before, 20,
-                "X motion did not continue after its ACK");
-            wait_axis_rises(2'd1, y_before, 6,
-                "Y motion did not complete after its ACK");
-            if (!overlap_seen)
-                fail("X and Y STEP waveforms never overlapped");
-        end
-    endtask
-
-    initial begin
-        run_stalled_response_case();
-        run_core_nonidle_case();
-        run_fast_ack_priority_case();
-        run_latest_wins_ack_case();
-        run_cross_axis_case();
-
-        if (failures != 0)
-            $fatal(1, "prod2u_p4_fast_jog_core_tb RED failures=%0d", failures);
-        $display("PASS: prod2u_p4_fast_jog_core_tb");
-        $finish;
-    end
-endmodule

+ 0 - 215
tests/sim/prod2u_p4_i2c_stop_start_read_tb.v

@@ -1,215 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_i2c_stop_start_read_tb;
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg request_valid = 1'b0;
-    wire request_ready;
-    reg [6:0] request_device_addr = 7'h49;
-    reg [7:0] request_register = 8'h00;
-    wire response_valid;
-    reg response_ready = 1'b0;
-    wire [15:0] response_data;
-    wire [3:0] response_error;
-    wire busy;
-    wire scl_drive_low;
-    wire sda_drive_low;
-
-    reg slave_scl_drive_low = 1'b0;
-    reg slave_sda_drive_low = 1'b0;
-    wire delayed_scl_drive_low;
-    wire delayed_sda_drive_low;
-    wire scl_bus;
-    wire sda_bus;
-
-    integer start_edges = 0;
-    integer stop_edges = 0;
-    integer guard;
-    reg [7:0] captured;
-    reg master_acknowledged;
-
-    // Deliberately model unequal PCB/IO delay. SDA must not change until SCL
-    // has already reached low, otherwise false START/STOP edges are counted.
-    assign #2 delayed_scl_drive_low = scl_drive_low;
-    assign #1 delayed_sda_drive_low = sda_drive_low;
-    assign scl_bus = ~(delayed_scl_drive_low | slave_scl_drive_low);
-    assign sda_bus = ~(delayed_sda_drive_low | slave_sda_drive_low);
-
-    prod2u_p4_i2c_stop_start_read #(
-        .HALF_PERIOD_CLKS(4),
-        .TIMEOUT_CLKS(2000)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .abort(1'b0),
-        .abort_done(),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_device_addr(request_device_addr),
-        .request_register(request_register),
-        .response_valid(response_valid),
-        .response_ready(response_ready),
-        .response_data(response_data),
-        .response_error(response_error),
-        .busy(busy),
-        .scl_i(scl_bus),
-        .sda_i(sda_bus),
-        .scl_drive_low(scl_drive_low),
-        .sda_drive_low(sda_drive_low)
-    );
-
-    always #5 clk = ~clk;
-
-    always @(negedge sda_bus) begin
-        if (rst_n && scl_bus) start_edges = start_edges + 1;
-    end
-
-    always @(posedge sda_bus) begin
-        if (rst_n && scl_bus) stop_edges = stop_edges + 1;
-    end
-
-    task capture_master_byte;
-        output [7:0] value;
-        integer bit_index;
-        begin
-            for (bit_index = 7; bit_index >= 0; bit_index = bit_index - 1) begin
-                @(posedge scl_bus);
-                value[bit_index] = sda_bus;
-                @(negedge scl_bus);
-            end
-        end
-    endtask
-
-    task drive_slave_ack;
-        begin
-            slave_sda_drive_low = 1'b1;
-            @(posedge scl_bus);
-            @(negedge scl_bus);
-            slave_sda_drive_low = 1'b0;
-        end
-    endtask
-
-    task drive_slave_byte;
-        input [7:0] value;
-        output acknowledged;
-        integer bit_index;
-        begin
-            for (bit_index = 7; bit_index >= 0; bit_index = bit_index - 1) begin
-                slave_sda_drive_low = ~value[bit_index];
-                @(posedge scl_bus);
-                @(negedge scl_bus);
-            end
-            slave_sda_drive_low = 1'b0;
-            @(posedge scl_bus);
-            acknowledged = ~sda_bus;
-            @(negedge scl_bus);
-        end
-    endtask
-
-    task wait_start;
-        begin : wait_for_true_start
-            forever begin
-                @(negedge sda_bus);
-                if (scl_bus) disable wait_for_true_start;
-            end
-        end
-    endtask
-
-    task wait_stop;
-        begin : wait_for_true_stop
-            forever begin
-                @(posedge sda_bus);
-                if (scl_bus) disable wait_for_true_stop;
-            end
-        end
-    endtask
-
-    initial begin
-        repeat (5) @(negedge clk);
-        rst_n = 1'b1;
-        repeat (3) @(negedge clk);
-
-        fork
-            begin : slave_model
-                wait_start();
-                capture_master_byte(captured);
-                if (captured !== 8'h92) begin
-                    $display("WRITE_ADDRESS_MISMATCH got=%02x", captured);
-                    $fatal;
-                end
-                drive_slave_ack();
-
-                capture_master_byte(captured);
-                if (captured !== 8'h00) begin
-                    $display("REGISTER_MISMATCH got=%02x", captured);
-                    $fatal;
-                end
-                drive_slave_ack();
-                wait_stop();
-
-                wait_start();
-                capture_master_byte(captured);
-                if (captured !== 8'h93) begin
-                    $display("READ_ADDRESS_MISMATCH got=%02x", captured);
-                    $fatal;
-                end
-                drive_slave_ack();
-
-                drive_slave_byte(8'h0c, master_acknowledged);
-                if (!master_acknowledged) begin
-                    $display("HIGH_BYTE_NOT_ACKED");
-                    $fatal;
-                end
-                drive_slave_byte(8'h80, master_acknowledged);
-                if (master_acknowledged) begin
-                    $display("LOW_BYTE_NOT_NACKED");
-                    $fatal;
-                end
-                wait_stop();
-            end
-
-            begin : master_request
-                while (!request_ready) @(negedge clk);
-                request_valid = 1'b1;
-                @(posedge clk);
-                #1 request_valid = 1'b0;
-
-                guard = 0;
-                while (!response_valid && guard < 2500) begin
-                    @(negedge clk);
-                    guard = guard + 1;
-                end
-                if (!response_valid || response_error !== 4'd0 ||
-                    response_data !== 16'h0c80) begin
-                    $display(
-                        "RESPONSE_MISMATCH valid=%0d error=%0d data=%04x",
-                        response_valid,
-                        response_error,
-                        response_data
-                    );
-                    $fatal;
-                end
-                response_ready = 1'b1;
-                @(posedge clk);
-                #1 response_ready = 1'b0;
-            end
-        join
-
-        repeat (3) @(negedge clk);
-        if (start_edges !== 2 || stop_edges !== 2) begin
-            $display(
-                "FALSE_START_STOP_EDGES starts=%0d stops=%0d expected=2/2",
-                start_edges,
-                stop_edges
-            );
-            $fatal;
-        end
-        if (busy || response_valid || scl_drive_low || sda_drive_low) begin
-            $display("BUS_NOT_RELEASED_AT_END");
-            $fatal;
-        end
-
-        $display("PASS: prod2u_p4_i2c_stop_start_read_tb");
-        $finish;
-    end
-endmodule

+ 0 - 82
tests/sim/prod2u_p4_jog_no_gates_contract_tb.v

@@ -1,82 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_jog_no_gates_contract_tb;
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg jog_start = 1'b0;
-    reg [1:0] jog_axis = 2'd0;
-    reg jog_dir = 1'b0;
-    reg [15:0] jog_steps = 16'd1;
-    reg legacy_limit = 1'b0;
-    reg legacy_disabled = 1'b0;
-    reg legacy_watchdog = 1'b0;
-    wire [1:0] axis_started_pulse;
-    wire [2:0] step_out;
-    wire [2:0] dir_out;
-
-    integer x_rises = 0;
-    integer y_rises = 0;
-    integer x_started = 0;
-    integer y_started = 0;
-    integer guard = 0;
-
-    always #5 clk = ~clk;
-    always @(posedge step_out[0]) x_rises = x_rises + 1;
-    always @(posedge step_out[1]) y_rises = y_rises + 1;
-    always @(posedge clk) begin
-        #1;
-        if (axis_started_pulse[0]) x_started = x_started + 1;
-        if (axis_started_pulse[1]) y_started = y_started + 1;
-    end
-
-    prod2u_p4_motor_hub #(
-        .DIR_SETUP_CYCLES(2),
-        .STEP_HALF_CYCLES(1)
-    ) dut (
-        .clk(clk), .rst_n(rst_n),
-        .jog_start(jog_start), .jog_axis(jog_axis),
-        .jog_dir(jog_dir), .jog_steps(jog_steps),
-        .axis_started_pulse(axis_started_pulse),
-        .step_out(step_out), .dir_out(dir_out)
-    );
-
-    task issue_jog;
-        input [1:0] axis;
-        input direction;
-        input [15:0] steps;
-        begin
-            @(negedge clk);
-            jog_axis = axis;
-            jog_dir = direction;
-            jog_steps = steps;
-            jog_start = 1'b1;
-            @(negedge clk);
-            jog_start = 1'b0;
-        end
-    endtask
-
-    initial begin
-        repeat (3) @(negedge clk);
-        rst_n = 1'b1;
-
-        issue_jog(2'd0, 1'b1, 16'd801);
-        issue_jog(2'd1, 1'b0, 16'd17);
-        while (((x_rises < 801) || (y_rises < 17)) && (guard < 1800)) begin
-            @(negedge clk);
-            legacy_limit = ~legacy_limit;
-            legacy_disabled = ~legacy_disabled;
-            legacy_watchdog = ~legacy_watchdog;
-            guard = guard + 1;
-        end
-        repeat (6) @(negedge clk);
-
-        if ((x_rises != 801) || (y_rises != 17) ||
-            (x_started != 1) || (y_started != 1) ||
-            !dir_out[0] || dir_out[1] || step_out[2] || dir_out[2]) begin
-            $fatal(1, "no-gates contract mismatch x=%0d y=%0d sx=%0d sy=%0d",
-                x_rises, y_rises, x_started, y_started);
-        end
-        $display("PASS: prod2u_p4_jog_no_gates_contract_tb");
-        $finish;
-    end
-endmodule

+ 0 - 236
tests/sim/prod2u_p4_minimal_snapshot_contract_tb.v

@@ -1,236 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_minimal_snapshot_contract_tb;
-    localparam [7:0] FT_HOST_BATCH_CMD = 8'h07;
-    localparam [7:0] FT_MOTION_CMD = 8'h11;
-    localparam [7:0] FT_HOST_ACK = 8'h06;
-    localparam [7:0] CMD_SET_SNAPSHOT = 8'h2a;
-    localparam [7:0] MOTION_JOG = 8'h35;
-    localparam [7:0] STATUS_OK = 8'h00;
-    localparam [7:0] STATUS_BAD_VALUE = 8'h05;
-
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg request_valid = 1'b0;
-    wire request_ready;
-    reg [7:0] request_type = 8'd0;
-    reg [5:0] request_length = 6'd0;
-    reg [271:0] request_payload = 272'd0;
-    reg [15:0] request_crc16 = 16'd0;
-    reg fast_jog_valid = 1'b0;
-    reg [1:0] fast_jog_axis = 2'd0;
-    reg fast_jog_dir = 1'b0;
-    reg [15:0] fast_jog_steps = 16'd1;
-    wire frame_valid;
-    wire [7:0] frame_type;
-    wire [143:0] frame_payload;
-    wire [191:0] ptc_percent;
-    wire [31:0] fan_percent;
-    wire [7:0] solenoid_percent;
-    wire [2:0] step_out;
-    wire [2:0] dir_out;
-    wire en_n;
-    wire disabled;
-    wire watchdog_timeout;
-
-    integer x_rises = 0;
-    integer y_rises = 0;
-    integer z_rises = 0;
-    integer guard;
-    integer index;
-    integer x_before;
-    reg [271:0] payload;
-
-    always #5 clk = ~clk;
-    always @(posedge step_out[0]) x_rises = x_rises + 1;
-    always @(posedge step_out[1]) y_rises = y_rises + 1;
-    always @(posedge step_out[2]) z_rises = z_rises + 1;
-
-    prod2u_p4_normal_v3_core #(
-        .CLK_HZ(64),
-        .WATCHDOG_SECONDS(1),
-        .DIR_SETUP_CYCLES(2),
-        .STEP_HALF_CYCLES(1)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(request_crc16),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(fast_jog_axis),
-        .fast_jog_dir(fast_jog_dir),
-        .fast_jog_steps(fast_jog_steps),
-        .frame_valid(frame_valid),
-        .frame_ready(1'b1),
-        .frame_type(frame_type),
-        .frame_payload_len(),
-        .frame_payload(frame_payload),
-        .ptc_percent(ptc_percent),
-        .fan_percent(fan_percent),
-        .solenoid_percent(solenoid_percent),
-        .state_hash16(),
-        .step_out(step_out),
-        .dir_out(dir_out),
-        .en_n(en_n),
-        .disabled(disabled),
-        .watchdog_timeout(watchdog_timeout)
-    );
-
-    task fail;
-        input [8*120-1:0] message;
-        begin
-            $display("SNAPSHOT_CONTRACT_FAIL: %0s", message);
-            $fatal(1);
-        end
-    endtask
-
-    task wait_ready;
-        begin
-            guard = 0;
-            while (!request_ready && guard < 1024) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (!request_ready) fail("request_ready timeout");
-        end
-    endtask
-
-    task issue_request;
-        input [7:0] kind;
-        input [5:0] length;
-        input [271:0] bytes;
-        begin
-            wait_ready();
-            @(negedge clk);
-            request_type = kind;
-            request_length = length;
-            request_payload = bytes;
-            request_crc16 = request_crc16 + 16'd1;
-            request_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            request_valid = 1'b0;
-        end
-    endtask
-
-    task expect_ack;
-        input [7:0] command;
-        input [7:0] status;
-        begin
-            guard = 0;
-            while (!(frame_valid && frame_type == FT_HOST_ACK) && guard < 1024) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if (!(frame_valid && frame_type == FT_HOST_ACK))
-                fail("ACK timeout");
-            if (frame_payload[15:8] !== command ||
-                frame_payload[23:16] !== status)
-                fail("ACK payload mismatch");
-            wait_ready();
-        end
-    endtask
-
-    task issue_fast_jog;
-        input [1:0] axis;
-        input direction;
-        input [15:0] steps;
-        begin
-            @(negedge clk);
-            fast_jog_axis = axis;
-            fast_jog_dir = direction;
-            fast_jog_steps = steps;
-            fast_jog_valid = 1'b1;
-            @(negedge clk);
-            fast_jog_valid = 1'b0;
-        end
-    endtask
-
-    function [271:0] snapshot_bytes;
-        input [7:0] output_value;
-        input [7:0] solenoid_value;
-        input [23:0] xyz;
-        integer value_index;
-        reg [271:0] bytes;
-        begin
-            bytes = 272'd0;
-            bytes[7:0] = CMD_SET_SNAPSHOT;
-            for (value_index = 2; value_index <= 29;
-                 value_index = value_index + 1)
-                bytes[value_index * 8 +: 8] = output_value;
-            bytes[30 * 8 +: 8] = solenoid_value;
-            bytes[31 * 8 +: 24] = xyz;
-            snapshot_bytes = bytes;
-        end
-    endfunction
-
-    initial begin
-        repeat (4) @(negedge clk);
-        rst_n = 1'b1;
-        repeat (2) @(negedge clk);
-
-        payload = snapshot_bytes(8'd25, 8'd100, 24'h006400);
-        payload[2 * 8 +: 8] = 8'd101;
-        issue_request(FT_HOST_BATCH_CMD, 6'd34, payload);
-        expect_ack(CMD_SET_SNAPSHOT, STATUS_BAD_VALUE);
-        repeat (80) @(posedge clk);
-        #1;
-        if (!disabled || watchdog_timeout || dut.watchdog_armed ||
-            ptc_percent != 192'd0 || fan_percent != {4{8'd30}} ||
-            solenoid_percent != 8'd0)
-            fail("invalid snapshot changed outputs or armed watchdog");
-
-        payload = snapshot_bytes(8'd25, 8'd100, 24'h006400);
-        issue_request(FT_HOST_BATCH_CMD, 6'd34, payload);
-        expect_ack(CMD_SET_SNAPSHOT, STATUS_OK);
-        repeat (2) @(posedge clk);
-        #1;
-        if (disabled || !dut.watchdog_armed || watchdog_timeout ||
-            ptc_percent != {24{8'd25}} || fan_percent != {4{8'd25}} ||
-            solenoid_percent != 8'd100 || step_out != 3'b000)
-            fail("valid snapshot did not commit only non-motor outputs");
-
-        x_before = x_rises;
-        issue_fast_jog(2'd0, 1'b1, 16'd100);
-        expect_ack(MOTION_JOG, STATUS_OK);
-        if ((x_rises - x_before) < 1 || dir_out[0] !== 1'b1)
-            fail("JOG ACK preceded physical STEP");
-
-        payload = snapshot_bytes(8'd40, 8'd0, 24'h640064);
-        issue_request(FT_HOST_BATCH_CMD, 6'd34, payload);
-        expect_ack(CMD_SET_SNAPSHOT, STATUS_OK);
-        if (ptc_percent != {24{8'd40}} || fan_percent != {4{8'd40}} ||
-            solenoid_percent != 8'd0 || dir_out[0] !== 1'b1 ||
-            y_rises != 0 || z_rises != 0)
-            fail("snapshot XYZ affected an active motor command");
-
-        guard = 0;
-        while (!watchdog_timeout && guard < 256) begin
-            @(posedge clk);
-            #1;
-            guard = guard + 1;
-        end
-        if (!watchdog_timeout || !disabled || en_n !== 1'b0)
-            fail("watchdog did not safe non-motor state");
-
-        guard = 0;
-        while ((x_rises - x_before) < 100 && guard < 1024) begin
-            @(posedge clk);
-            #1;
-            guard = guard + 1;
-        end
-        if ((x_rises - x_before) != 100 || y_rises != 0 || z_rises != 0 ||
-            ptc_percent != 192'd0 || fan_percent != {4{8'd30}} ||
-            solenoid_percent != 8'd0 || en_n !== 1'b0)
-            fail("watchdog or snapshot altered JOG execution");
-
-        $display("PASS: prod2u_p4_minimal_snapshot_contract_tb");
-        $finish;
-    end
-endmodule

+ 0 - 165
tests/sim/prod2u_p4_motor_hub_axis_isolation_tb.v

@@ -1,165 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_motor_hub_axis_isolation_tb;
-    localparam integer DIR_SETUP_CYCLES = 3;
-    localparam integer STEP_HALF_CYCLES = 2;
-
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg jog_start = 1'b0;
-    reg [1:0] jog_axis = 2'd0;
-    reg jog_dir = 1'b0;
-    reg [15:0] jog_steps = 16'd1;
-
-    wire [1:0] axis_started_pulse;
-    wire [2:0] step_out;
-    wire [2:0] dir_out;
-
-    integer failures = 0;
-    integer x_rises = 0;
-    integer y_rises = 0;
-    integer x_started = 0;
-    integer y_started = 0;
-    integer guard;
-
-    always #5 clk = ~clk;
-    always @(posedge step_out[0]) x_rises = x_rises + 1;
-    always @(posedge step_out[1]) y_rises = y_rises + 1;
-    always @(posedge clk) begin
-        #1;
-        if (axis_started_pulse[0]) x_started = x_started + 1;
-        if (axis_started_pulse[1]) y_started = y_started + 1;
-        if (step_out[2] || dir_out[2]) begin
-            failures = failures + 1;
-            $display("HUB_FAIL: reserved Z outputs were not fixed low");
-        end
-        if (axis_started_pulse[0] && !step_out[0]) begin
-            failures = failures + 1;
-            $display("HUB_FAIL: X started pulse did not coincide with X STEP high");
-        end
-        if (axis_started_pulse[1] && !step_out[1]) begin
-            failures = failures + 1;
-            $display("HUB_FAIL: Y started pulse did not coincide with Y STEP high");
-        end
-    end
-
-    prod2u_p4_motor_hub #(
-        .DIR_SETUP_CYCLES(DIR_SETUP_CYCLES),
-        .STEP_HALF_CYCLES(STEP_HALF_CYCLES)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .jog_start(jog_start),
-        .jog_axis(jog_axis),
-        .jog_dir(jog_dir),
-        .jog_steps(jog_steps),
-        .axis_started_pulse(axis_started_pulse),
-        .step_out(step_out),
-        .dir_out(dir_out)
-    );
-
-    task issue_jog;
-        input [1:0] axis;
-        input direction;
-        input [15:0] steps;
-        begin
-            @(negedge clk);
-            jog_axis = axis;
-            jog_dir = direction;
-            jog_steps = steps;
-            jog_start = 1'b1;
-            @(posedge clk);
-            #1;
-            if ((axis == 2'd0) && (step_out[0] || (dir_out[0] !== direction))) begin
-                failures = failures + 1;
-                $display("HUB_FAIL: X command did not latch with STEP low");
-            end
-            if ((axis == 2'd1) && (step_out[1] || (dir_out[1] !== direction))) begin
-                failures = failures + 1;
-                $display("HUB_FAIL: Y command did not latch with STEP low");
-            end
-            @(negedge clk);
-            jog_start = 1'b0;
-        end
-    endtask
-
-    task wait_counts;
-        input integer expected_x;
-        input integer expected_y;
-        begin
-            guard = 0;
-            while (((x_rises < expected_x) || (y_rises < expected_y)) &&
-                   (guard < 512)) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if ((x_rises != expected_x) || (y_rises != expected_y)) begin
-                failures = failures + 1;
-                $display("HUB_FAIL: count mismatch x=%0d/%0d y=%0d/%0d",
-                    x_rises, expected_x, y_rises, expected_y);
-            end
-        end
-    endtask
-
-    initial begin
-        repeat (3) @(negedge clk);
-        rst_n = 1'b1;
-        repeat (2) @(negedge clk);
-
-        // X and Y are separate executors and must overlap without interference.
-        issue_jog(2'd0, 1'b0, 16'd8);
-        wait_counts(1, 0);
-        issue_jog(2'd1, 1'b1, 16'd3);
-        wait_counts(8, 3);
-        repeat (8) @(negedge clk);
-        if ((x_started != 1) || (y_started != 1) ||
-            (x_rises != 8) || (y_rises != 3)) begin
-            failures = failures + 1;
-            $display("HUB_FAIL: independent overlap count/started mismatch");
-        end
-
-        // Replacing X while it is high must immediately lower only X; Y keeps
-        // its own schedule and state.
-        x_rises = 0;
-        y_rises = 0;
-        x_started = 0;
-        y_started = 0;
-        issue_jog(2'd0, 1'b0, 16'd9);
-        issue_jog(2'd1, 1'b0, 16'd9);
-        wait_counts(1, 1);
-        issue_jog(2'd0, 1'b1, 16'd2);
-        if (step_out[0] || !dir_out[0]) begin
-            failures = failures + 1;
-            $display("HUB_FAIL: same-axis overwrite did not force X STEP low");
-        end
-        guard = 0;
-        while ((y_rises < 9) && (guard < 128)) begin
-            @(negedge clk);
-            guard = guard + 1;
-        end
-        repeat (16) @(negedge clk);
-        if ((x_rises != 3) || (y_rises != 9) ||
-            (x_started != 2) || (y_started != 1)) begin
-            failures = failures + 1;
-            $display("HUB_FAIL: overwrite/peer isolation x=%0d y=%0d sx=%0d sy=%0d",
-                x_rises, y_rises, x_started, y_started);
-        end
-
-        // Reserved axis values are ignored and cannot disturb X/Y.
-        issue_jog(2'd2, 1'b1, 16'd5);
-        issue_jog(2'd3, 1'b1, 16'd5);
-        repeat (16) @(negedge clk);
-        if ((x_rises != 3) || (y_rises != 9) ||
-            (x_started != 2) || (y_started != 1)) begin
-            failures = failures + 1;
-            $display("HUB_FAIL: reserved axis command changed X/Y motion");
-        end
-
-        if (failures != 0) begin
-            $fatal(1, "prod2u_p4_motor_hub_axis_isolation_tb failures=%0d",
-                failures);
-        end
-        $display("PASS: prod2u_p4_motor_hub_axis_isolation_tb");
-        $finish;
-    end
-endmodule

+ 0 - 62
tests/sim/prod2u_p4_motor_status_payload_tb.v

@@ -1,62 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_motor_status_payload_tb;
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg jog_start = 1'b0;
-    reg [1:0] jog_axis = 2'd0;
-    reg jog_dir = 1'b0;
-    reg [15:0] jog_steps = 16'd2;
-    wire [1:0] axis_started_pulse;
-    wire [2:0] step_out;
-    wire [2:0] dir_out;
-
-    integer started_events = 0;
-
-    always #5 clk = ~clk;
-    always @(posedge clk) begin
-        #1;
-        if (|axis_started_pulse) started_events = started_events + 1;
-        if (step_out[2] || dir_out[2]) begin
-            $fatal(1, "reserved Z output changed");
-        end
-    end
-
-    prod2u_p4_motor_hub #(
-        .DIR_SETUP_CYCLES(1),
-        .STEP_HALF_CYCLES(1)
-    ) dut (
-        .clk(clk), .rst_n(rst_n),
-        .jog_start(jog_start), .jog_axis(jog_axis),
-        .jog_dir(jog_dir), .jog_steps(jog_steps),
-        .axis_started_pulse(axis_started_pulse),
-        .step_out(step_out), .dir_out(dir_out)
-    );
-
-    initial begin
-        repeat (3) @(negedge clk);
-        rst_n = 1'b1;
-        @(negedge clk);
-        jog_axis = 2'd0;
-        jog_dir = 1'b1;
-        jog_start = 1'b1;
-        @(negedge clk);
-        jog_start = 1'b0;
-        repeat (12) @(negedge clk);
-        if ((started_events != 1) || !dir_out[0]) begin
-            $fatal(1, "minimal Hub did not expose exactly one X start event");
-        end
-
-        @(negedge clk);
-        jog_axis = 2'd2;
-        jog_start = 1'b1;
-        @(negedge clk);
-        jog_start = 1'b0;
-        repeat (8) @(negedge clk);
-        if (started_events != 1) begin
-            $fatal(1, "reserved Z command produced an axis start event");
-        end
-        $display("PASS: prod2u_p4_motor_status_payload_tb");
-        $finish;
-    end
-endmodule

+ 0 - 327
tests/sim/prod2u_p4_normal_v3_rx_fast_jog_tb.v

@@ -1,327 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_normal_v3_rx_fast_jog_tb;
-    localparam [7:0] HOST_CMD = 8'h05;
-    localparam [7:0] MOTION_CMD = 8'h11;
-    localparam [7:0] MOTION_JOG = 8'h35;
-
-    reg clk;
-    reg rst_n;
-    reg rx_valid;
-    wire rx_ready;
-    reg [7:0] rx_data;
-    wire request_valid;
-    reg request_ready;
-    wire [7:0] request_type;
-    wire [5:0] request_length;
-    wire [271:0] request_payload;
-    wire [15:0] request_crc16;
-    wire [15:0] crc_error_count;
-    wire [15:0] timeout_count;
-    wire [15:0] format_error_count;
-    wire fast_jog_valid;
-    wire [1:0] fast_jog_axis;
-    wire fast_jog_dir;
-    wire [15:0] fast_jog_steps;
-
-    reg [7:0] frame [0:49];
-    integer frame_length;
-    integer i;
-    integer ready_guard;
-    integer fast_event_count;
-    reg fast_valid_previous;
-    reg [1:0] last_fast_axis;
-    reg last_fast_dir;
-    reg [15:0] last_fast_steps;
-    reg check_held_request;
-    reg [7:0] held_request_type;
-    reg [5:0] held_request_length;
-    reg [271:0] held_request_payload;
-    reg [15:0] held_request_crc16;
-
-    prod2u_p4_normal_v3_rx #(
-        .CLK_HZ(10000),
-        .INTER_BYTE_TIMEOUT_MS(2)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_valid(rx_valid),
-        .rx_ready(rx_ready),
-        .rx_data(rx_data),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(request_crc16),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(fast_jog_axis),
-        .fast_jog_dir(fast_jog_dir),
-        .fast_jog_steps(fast_jog_steps),
-        .crc_error_count(crc_error_count),
-        .timeout_count(timeout_count),
-        .format_error_count(format_error_count)
-    );
-
-    initial begin
-        clk = 1'b0;
-        forever #5 clk = ~clk;
-    end
-
-    always @(negedge clk) begin
-        if (!rst_n) begin
-            fast_event_count = 0;
-            fast_valid_previous = 1'b0;
-            last_fast_axis = 2'd0;
-            last_fast_dir = 1'b0;
-            last_fast_steps = 16'd0;
-        end else begin
-            if (fast_jog_valid) begin
-                if (fast_valid_previous) begin
-                    $fatal(1, "FAST_JOG_VALID_NOT_SINGLE_CYCLE");
-                end
-                fast_event_count = fast_event_count + 1;
-                last_fast_axis = fast_jog_axis;
-                last_fast_dir = fast_jog_dir;
-                last_fast_steps = fast_jog_steps;
-            end
-            fast_valid_previous = fast_jog_valid;
-
-            if (check_held_request &&
-                (!request_valid || request_type !== held_request_type ||
-                 request_length !== held_request_length ||
-                 request_payload !== held_request_payload ||
-                 request_crc16 !== held_request_crc16)) begin
-                $fatal(1, "FAST_JOG_OVERWROTE_HELD_NORMAL_REQUEST");
-            end
-        end
-    end
-
-    function [15:0] crc16_byte;
-        input [15:0] crc_in;
-        input [7:0] data;
-        reg [15:0] value;
-        integer bit_index;
-        begin
-            value = crc_in ^ {data, 8'h00};
-            for (bit_index = 0; bit_index < 8; bit_index = bit_index + 1) begin
-                if (value[15]) begin
-                    value = (value << 1) ^ 16'h1021;
-                end else begin
-                    value = value << 1;
-                end
-            end
-            crc16_byte = value;
-        end
-    endfunction
-
-    task begin_frame;
-        input [7:0] frame_type;
-        input [7:0] payload_length;
-        begin
-            for (i = 0; i < 50; i = i + 1) begin
-                frame[i] = 8'h00;
-            end
-            frame[0] = 8'ha5;
-            frame[1] = 8'h5a;
-            frame[2] = 8'h02;
-            frame[3] = 8'h04;
-            frame[4] = frame_type;
-            frame[13] = payload_length;
-            frame_length = 16 + payload_length;
-        end
-    endtask
-
-    task finish_frame;
-        reg [15:0] crc;
-        integer last_body_byte;
-        begin
-            crc = 16'hffff;
-            last_body_byte = frame_length - 3;
-            for (i = 2; i <= last_body_byte; i = i + 1) begin
-                crc = crc16_byte(crc, frame[i]);
-            end
-            frame[frame_length - 2] = crc[7:0];
-            frame[frame_length - 1] = crc[15:8];
-        end
-    endtask
-
-    task build_host_command;
-        input [7:0] command;
-        begin
-            begin_frame(HOST_CMD, 8'd4);
-            frame[14] = command;
-            finish_frame();
-        end
-    endtask
-
-    task build_jog;
-        input [7:0] opcode;
-        input [7:0] axis;
-        input [7:0] dir;
-        input [7:0] speed;
-        input [15:0] steps;
-        input [7:0] reserved0;
-        input [7:0] reserved1;
-        begin
-            begin_frame(MOTION_CMD, 8'd8);
-            frame[14] = opcode;
-            frame[15] = axis;
-            frame[16] = dir;
-            frame[17] = speed;
-            frame[18] = steps[7:0];
-            frame[19] = steps[15:8];
-            frame[20] = reserved0;
-            frame[21] = reserved1;
-            finish_frame();
-        end
-    endtask
-
-    task send_byte;
-        input [7:0] value;
-        begin
-            ready_guard = 0;
-            while (!rx_ready && ready_guard < 16) begin
-                @(negedge clk);
-                ready_guard = ready_guard + 1;
-            end
-            if (!rx_ready) begin
-                $fatal(1, "FAST_JOG_RX_BLOCKED_BY_HELD_REQUEST");
-            end
-            @(negedge clk);
-            rx_data = value;
-            rx_valid = 1'b1;
-            @(negedge clk);
-            rx_valid = 1'b0;
-        end
-    endtask
-
-    task send_built_frame;
-        begin
-            for (i = 0; i < frame_length; i = i + 1) begin
-                send_byte(frame[i]);
-            end
-        end
-    endtask
-
-    task expect_fast_event;
-        input [1:0] expected_axis;
-        input expected_dir;
-        input [15:0] expected_steps;
-        integer count_before;
-        integer wait_cycles;
-        begin
-            count_before = fast_event_count;
-            send_built_frame();
-            wait_cycles = 0;
-            while (fast_event_count == count_before && wait_cycles < 8) begin
-                @(negedge clk);
-                wait_cycles = wait_cycles + 1;
-            end
-            if (fast_event_count !== count_before + 1) begin
-                $fatal(1, "FAST_JOG_VALID_EVENT_COUNT_MISMATCH");
-            end
-            if (last_fast_axis !== expected_axis ||
-                last_fast_dir !== expected_dir ||
-                last_fast_steps !== expected_steps) begin
-                $fatal(1, "FAST_JOG_PAYLOAD_MISMATCH");
-            end
-            repeat (2) @(negedge clk);
-            if (fast_event_count !== count_before + 1) begin
-                $fatal(1, "FAST_JOG_VALID_EVENT_REPEATED");
-            end
-        end
-    endtask
-
-    task expect_no_fast_event;
-        integer count_before;
-        begin
-            count_before = fast_event_count;
-            send_built_frame();
-            repeat (4) @(negedge clk);
-            if (fast_event_count !== count_before) begin
-                $fatal(1, "INVALID_JOG_PRODUCED_FAST_EVENT");
-            end
-        end
-    endtask
-
-    initial begin
-        rst_n = 1'b0;
-        rx_valid = 1'b0;
-        rx_data = 8'h00;
-        request_ready = 1'b0;
-        fast_event_count = 0;
-        fast_valid_previous = 1'b0;
-        check_held_request = 1'b0;
-        repeat (4) @(negedge clk);
-        rst_n = 1'b1;
-        repeat (2) @(negedge clk);
-
-        // Fill the ordinary request slot and deliberately leave it pending.
-        build_host_command(8'h20);
-        send_built_frame();
-        repeat (2) @(negedge clk);
-        if (!request_valid) begin
-            $fatal(1, "NORMAL_REQUEST_DID_NOT_ENTER_HELD_SLOT");
-        end
-        held_request_type = request_type;
-        held_request_length = request_length;
-        held_request_payload = request_payload;
-        held_request_crc16 = request_crc16;
-        check_held_request = 1'b1;
-
-        // A held ordinary request must not backpressure the continuous parser.
-        build_jog(MOTION_JOG, 8'd1, 8'd1, 8'd3, 16'h1234, 8'd0, 8'd0);
-        expect_fast_event(2'd1, 1'b1, 16'h1234);
-
-        // The RTL trusts the host's raw u16 field. Zero is deliberately not gated.
-        build_jog(MOTION_JOG, 8'd0, 8'd0, 8'd0, 16'h0000, 8'd0, 8'd0);
-        expect_fast_event(2'd0, 1'b0, 16'h0000);
-
-        build_jog(MOTION_JOG, 8'd2, 8'd0, 8'd0, 16'd1, 8'd0, 8'd0);
-        expect_no_fast_event();
-        build_jog(MOTION_JOG, 8'd0, 8'd2, 8'd0, 16'd1, 8'd0, 8'd0);
-        expect_no_fast_event();
-        build_jog(MOTION_JOG, 8'd0, 8'd0, 8'd4, 16'd1, 8'd0, 8'd0);
-        expect_no_fast_event();
-        build_jog(MOTION_JOG, 8'd0, 8'd0, 8'd3, 16'd1, 8'd1, 8'd0);
-        expect_no_fast_event();
-        build_jog(MOTION_JOG, 8'd0, 8'd0, 8'd3, 16'd1, 8'd0, 8'd1);
-        expect_no_fast_event();
-        build_jog(8'h37, 8'd0, 8'd0, 8'd3, 16'd1, 8'd0, 8'd0);
-        expect_no_fast_event();
-        build_host_command(MOTION_JOG);
-        expect_no_fast_event();
-        begin_frame(MOTION_CMD, 8'd4);
-        frame[14] = MOTION_JOG;
-        frame[15] = 8'd0;
-        frame[16] = 8'd0;
-        frame[17] = 8'd0;
-        finish_frame();
-        expect_no_fast_event();
-
-        build_jog(MOTION_JOG, 8'd0, 8'd1, 8'd3, 16'h55aa, 8'd0, 8'd0);
-        frame[frame_length - 1] = frame[frame_length - 1] ^ 8'h01;
-        expect_no_fast_event();
-
-        // Consume the held normal request, then prove JOG uses only the fast path.
-        check_held_request = 1'b0;
-        request_ready = 1'b1;
-        @(posedge clk);
-        #1;
-        @(negedge clk);
-        if (request_valid) begin
-            $fatal(1, "HELD_NORMAL_REQUEST_DID_NOT_HANDSHAKE");
-        end
-        request_ready = 1'b0;
-
-        build_jog(MOTION_JOG, 8'd0, 8'd1, 8'd2, 16'hffff, 8'd0, 8'd0);
-        expect_fast_event(2'd0, 1'b1, 16'hffff);
-        if (request_valid) begin
-            $fatal(1, "VALID_JOG_LEAKED_INTO_NORMAL_REQUEST_SLOT");
-        end
-
-        $display("PASS: prod2u_p4_normal_v3_rx_fast_jog_tb");
-        $finish;
-    end
-endmodule

+ 0 - 530
tests/sim/prod2u_p4_normal_v3_rx_tb.v

@@ -1,530 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_normal_v3_rx_tb;
-    localparam [7:0] HOST_CMD = 8'h05;
-    localparam [7:0] HOST_BATCH_CMD = 8'h07;
-    localparam [7:0] MOTION_CMD = 8'h11;
-
-    reg clk;
-    reg rst_n;
-    reg rx_valid;
-    wire rx_ready;
-    reg [7:0] rx_data;
-    wire request_valid;
-    reg request_ready;
-    wire [7:0] request_type;
-    wire [5:0] request_length;
-    wire [271:0] request_payload;
-    wire [15:0] request_crc16;
-    wire fast_jog_valid;
-    wire [1:0] fast_jog_axis;
-    wire fast_jog_dir;
-    wire [15:0] fast_jog_steps;
-    wire [15:0] crc_error_count;
-    wire [15:0] timeout_count;
-    wire [15:0] format_error_count;
-
-    reg [7:0] frame [0:49];
-    reg [271:0] expected_payload;
-    reg [15:0] count_before;
-    reg [7:0] held_request_type;
-    reg [5:0] held_request_length;
-    reg [271:0] held_request_payload;
-    reg [15:0] held_request_crc16;
-    reg [15:0] held_crc_error_count;
-    reg [15:0] held_timeout_count;
-    reg [15:0] held_format_error_count;
-    reg check_held_request;
-    integer frame_length;
-    integer i;
-    integer wait_cycles;
-    reg timeout_probe_valid;
-    reg [7:0] timeout_probe_data;
-    wire timeout1_probe_ready;
-    wire timeout3_probe_ready;
-    wire [15:0] timeout1_probe_count;
-    wire [15:0] timeout3_probe_count;
-
-    prod2u_p4_normal_v3_rx #(
-        .CLK_HZ(10000),
-        .INTER_BYTE_TIMEOUT_MS(2)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_valid(rx_valid),
-        .rx_ready(rx_ready),
-        .rx_data(rx_data),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(request_crc16),
-        .fast_jog_valid(fast_jog_valid),
-        .fast_jog_axis(fast_jog_axis),
-        .fast_jog_dir(fast_jog_dir),
-        .fast_jog_steps(fast_jog_steps),
-        .crc_error_count(crc_error_count),
-        .timeout_count(timeout_count),
-        .format_error_count(format_error_count)
-    );
-
-    prod2u_p4_normal_v3_rx #(
-        .CLK_HZ(1000),
-        .INTER_BYTE_TIMEOUT_MS(1)
-    ) timeout1_dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_valid(timeout_probe_valid),
-        .rx_ready(timeout1_probe_ready),
-        .rx_data(timeout_probe_data),
-        .request_valid(),
-        .request_ready(1'b1),
-        .request_type(),
-        .request_length(),
-        .request_payload(),
-        .request_crc16(),
-        .fast_jog_valid(),
-        .fast_jog_axis(),
-        .fast_jog_dir(),
-        .fast_jog_steps(),
-        .crc_error_count(),
-        .timeout_count(timeout1_probe_count),
-        .format_error_count()
-    );
-
-    prod2u_p4_normal_v3_rx #(
-        .CLK_HZ(1000),
-        .INTER_BYTE_TIMEOUT_MS(3)
-    ) timeout3_dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_valid(timeout_probe_valid),
-        .rx_ready(timeout3_probe_ready),
-        .rx_data(timeout_probe_data),
-        .request_valid(),
-        .request_ready(1'b1),
-        .request_type(),
-        .request_length(),
-        .request_payload(),
-        .request_crc16(),
-        .fast_jog_valid(),
-        .fast_jog_axis(),
-        .fast_jog_dir(),
-        .fast_jog_steps(),
-        .crc_error_count(),
-        .timeout_count(timeout3_probe_count),
-        .format_error_count()
-    );
-
-    initial begin
-        clk = 1'b0;
-        forever #5 clk = ~clk;
-    end
-
-    always @(posedge clk) begin
-        if (check_held_request &&
-            (!request_valid || request_type !== held_request_type ||
-             request_length !== held_request_length ||
-             request_payload !== held_request_payload ||
-             request_crc16 !== held_request_crc16)) begin
-            $display(
-                "held request changed valid=%0d type=%02x/%02x len=%0d/%0d crc=%04x/%04x payload_match=%0d",
-                request_valid,
-                request_type,
-                held_request_type,
-                request_length,
-                held_request_length,
-                request_crc16,
-                held_request_crc16,
-                request_payload === held_request_payload
-            );
-            $fatal;
-        end
-    end
-
-    function [15:0] crc16_byte;
-        input [15:0] crc_in;
-        input [7:0] data;
-        reg [15:0] value;
-        integer bit_index;
-        begin
-            value = crc_in ^ {data, 8'h00};
-            for (bit_index = 0; bit_index < 8; bit_index = bit_index + 1) begin
-                if (value[15]) begin
-                    value = (value << 1) ^ 16'h1021;
-                end else begin
-                    value = value << 1;
-                end
-            end
-            crc16_byte = value;
-        end
-    endfunction
-
-    task begin_frame;
-        input [7:0] frame_type;
-        input [7:0] payload_length;
-        begin
-            for (i = 0; i < 50; i = i + 1) begin
-                frame[i] = 8'h00;
-            end
-            frame[0] = 8'ha5;
-            frame[1] = 8'h5a;
-            frame[2] = 8'h02;
-            frame[3] = 8'h04;
-            frame[4] = frame_type;
-            frame[13] = payload_length;
-            frame_length = 16 + payload_length;
-        end
-    endtask
-
-    task finish_frame;
-        reg [15:0] crc;
-        integer last_body_byte;
-        begin
-            crc = 16'hffff;
-            last_body_byte = frame_length - 3;
-            for (i = 2; i <= last_body_byte; i = i + 1) begin
-                crc = crc16_byte(crc, frame[i]);
-            end
-            frame[frame_length - 2] = crc[7:0];
-            frame[frame_length - 1] = crc[15:8];
-        end
-    endtask
-
-    task build_snapshot;
-        begin
-            begin_frame(HOST_BATCH_CMD, 8'd34);
-            frame[14] = 8'h2a;
-            frame[15] = 8'h00;
-            for (i = 0; i < 24; i = i + 1) begin
-                frame[16 + i] = i[7:0];
-            end
-            frame[40] = 8'd30;
-            frame[41] = 8'd40;
-            frame[42] = 8'd50;
-            frame[43] = 8'd60;
-            frame[44] = 8'd100;
-            frame[45] = 8'd0;
-            frame[46] = 8'd100;
-            frame[47] = 8'd0;
-            finish_frame();
-        end
-    endtask
-
-    task build_host_command;
-        input [7:0] command;
-        begin
-            begin_frame(HOST_CMD, 8'd4);
-            frame[14] = command;
-            finish_frame();
-        end
-    endtask
-
-    task build_motion_command;
-        input [7:0] opcode;
-        begin
-            begin_frame(MOTION_CMD, 8'd8);
-            frame[14] = opcode;
-            frame[15] = 8'd1;
-            frame[16] = 8'd0;
-            frame[17] = 8'd3;
-            frame[18] = 8'ha0;
-            frame[19] = 8'h00;
-            finish_frame();
-        end
-    endtask
-
-    task send_byte;
-        input [7:0] value;
-        begin
-            while (!rx_ready) begin
-                @(negedge clk);
-            end
-            rx_data = value;
-            rx_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            rx_valid = 1'b0;
-        end
-    endtask
-
-    task send_built_frame;
-        begin
-            for (i = 0; i < frame_length; i = i + 1) begin
-                send_byte(frame[i]);
-            end
-        end
-    endtask
-
-    task expect_request;
-        input [7:0] expected_type;
-        input [5:0] expected_length;
-        input [271:0] expected_bytes;
-        begin
-            wait_cycles = 0;
-            while (!request_valid && wait_cycles < 20) begin
-                @(negedge clk);
-                wait_cycles = wait_cycles + 1;
-            end
-            if (!request_valid) begin
-                $display("request timeout type=%02x", expected_type);
-                $fatal;
-            end
-            if (request_type !== expected_type ||
-                request_length !== expected_length ||
-                request_payload !== expected_bytes ||
-                request_crc16 !== {frame[frame_length - 1], frame[frame_length - 2]}) begin
-                $display(
-                    "request mismatch type=%02x/%02x length=%0d/%0d",
-                    request_type,
-                    expected_type,
-                    request_length,
-                    expected_length
-                );
-                $fatal;
-            end
-            @(posedge clk);
-            #1;
-            if (request_valid) begin
-                $display("request_valid did not clear after ready handshake");
-                $fatal;
-            end
-        end
-    endtask
-
-    task expect_format_rejection;
-        begin
-            count_before = format_error_count;
-            send_built_frame();
-            repeat (3) @(negedge clk);
-            if (request_valid || format_error_count !== count_before + 16'd1) begin
-                $display(
-                    "format rejection mismatch count=%0d/%0d valid=%0d",
-                    format_error_count,
-                    count_before + 16'd1,
-                    request_valid
-                );
-                $fatal;
-            end
-        end
-    endtask
-
-    initial begin
-        rst_n = 1'b0;
-        rx_valid = 1'b0;
-        rx_data = 8'h00;
-        request_ready = 1'b1;
-        check_held_request = 1'b0;
-        timeout_probe_valid = 1'b0;
-        timeout_probe_data = 8'h00;
-        repeat (4) @(negedge clk);
-        rst_n = 1'b1;
-
-        if ($bits(timeout1_dut.timeout_counter) != 1 ||
-            $bits(timeout3_dut.timeout_counter) != 2) begin
-            $display(
-                "timeout counter widths mismatch one=%0d three=%0d",
-                $bits(timeout1_dut.timeout_counter),
-                $bits(timeout3_dut.timeout_counter)
-            );
-            $fatal;
-        end
-
-        // A parser with timeout N expires on the Nth idle cycle after a byte.
-        timeout_probe_data = 8'ha5;
-        timeout_probe_valid = 1'b1;
-        @(posedge clk);
-        #1;
-        @(negedge clk);
-        timeout_probe_valid = 1'b0;
-        @(posedge clk);
-        #1;
-        if (timeout1_probe_count !== 16'd1 || timeout3_probe_count !== 16'd0 ||
-            timeout3_dut.timeout_counter !== 2'd1) begin
-            $display(
-                "timeout first-idle mismatch t1=%0d t3=%0d counter3=%0d",
-                timeout1_probe_count,
-                timeout3_probe_count,
-                timeout3_dut.timeout_counter
-            );
-            $fatal;
-        end
-        @(posedge clk);
-        #1;
-        if (timeout3_probe_count !== 16'd0 || timeout3_dut.timeout_counter !== 2'd2) begin
-            $display(
-                "timeout second-idle mismatch t3=%0d counter3=%0d",
-                timeout3_probe_count,
-                timeout3_dut.timeout_counter
-            );
-            $fatal;
-        end
-        @(posedge clk);
-        #1;
-        if (timeout3_probe_count !== 16'd1 || timeout3_dut.timeout_counter !== 2'd0) begin
-            $display(
-                "timeout third-idle mismatch t3=%0d counter3=%0d",
-                timeout3_probe_count,
-                timeout3_dut.timeout_counter
-            );
-            $fatal;
-        end
-
-        // The first complete command is accepted immediately after reset.
-        build_snapshot();
-        expected_payload = 272'd0;
-        for (i = 0; i < 34; i = i + 1) begin
-            expected_payload[i * 8 +: 8] = frame[14 + i];
-        end
-        send_built_frame();
-        expect_request(HOST_BATCH_CMD, 6'd34, expected_payload);
-
-        build_host_command(8'h29);
-        expected_payload = 272'd0;
-        expected_payload[7:0] = 8'h29;
-        send_built_frame();
-        expect_request(HOST_CMD, 6'd4, expected_payload);
-
-        build_host_command(8'h26);
-        expected_payload = 272'd0;
-        expected_payload[7:0] = 8'h26;
-        send_built_frame();
-        expect_request(HOST_CMD, 6'd4, expected_payload);
-
-        build_motion_command(8'h35);
-        send_built_frame();
-        if (!fast_jog_valid || fast_jog_axis !== 2'd1 ||
-            fast_jog_dir !== 1'b0 || fast_jog_steps !== 16'd160 ||
-            request_valid) begin
-            $display("legal JOG did not use the fast exit");
-            $fatal;
-        end
-        @(posedge clk);
-        #1;
-        if (fast_jog_valid) begin
-            $display("fast JOG event was not one cycle");
-            $fatal;
-        end
-
-        build_host_command(8'h24);
-        frame[2] = 8'h03;
-        expect_format_rejection();
-
-        build_host_command(8'h24);
-        frame[3] = 8'h03;
-        expect_format_rejection();
-
-        build_host_command(8'h24);
-        frame[4] = 8'h06;
-        expect_format_rejection();
-
-        build_host_command(8'h24);
-        frame[5] = 8'h01;
-        expect_format_rejection();
-
-        build_host_command(8'h24);
-        frame[9] = 8'h01;
-        expect_format_rejection();
-
-        build_snapshot();
-        frame[13] = 8'd33;
-        expect_format_rejection();
-
-        build_host_command(8'h24);
-        frame[13] = 8'd8;
-        expect_format_rejection();
-
-        build_motion_command(8'h37);
-        frame[13] = 8'd4;
-        expect_format_rejection();
-
-        build_host_command(8'h26);
-        frame[frame_length - 1] = frame[frame_length - 1] ^ 8'h01;
-        count_before = crc_error_count;
-        send_built_frame();
-        repeat (3) @(negedge clk);
-        if (request_valid || crc_error_count !== count_before + 16'd1) begin
-            $display("CRC rejection mismatch count=%0d valid=%0d", crc_error_count, request_valid);
-            $fatal;
-        end
-
-        // A truncated frame expires without producing a request.
-        build_snapshot();
-        for (i = 0; i < 6; i = i + 1) begin
-            send_byte(frame[i]);
-        end
-        repeat (19) @(negedge clk);
-        if (timeout_count !== 16'd0) begin
-            $display("timeout asserted before boundary count=%0d", timeout_count);
-            $fatal;
-        end
-        @(negedge clk);
-        if (timeout_count !== 16'd1 || request_valid) begin
-            $display("timeout mismatch count=%0d valid=%0d", timeout_count, request_valid);
-            $fatal;
-        end
-
-        // The one-entry ordinary slot stays stable while RX continues parsing.
-        request_ready = 1'b0;
-        build_motion_command(8'h37);
-        send_built_frame();
-        wait_cycles = 0;
-        while (!request_valid && wait_cycles < 20) begin
-            @(negedge clk);
-            wait_cycles = wait_cycles + 1;
-        end
-        if (!request_valid) begin
-            $display("ordinary request was not held under backpressure");
-            $fatal;
-        end
-        held_request_type = request_type;
-        held_request_length = request_length;
-        held_request_payload = request_payload;
-        held_request_crc16 = request_crc16;
-        held_crc_error_count = crc_error_count;
-        held_timeout_count = timeout_count;
-        held_format_error_count = format_error_count;
-        check_held_request = 1'b1;
-        repeat (8) begin
-            @(posedge clk);
-            #1;
-            if (!rx_ready || crc_error_count !== held_crc_error_count ||
-                timeout_count !== held_timeout_count ||
-                format_error_count !== held_format_error_count) begin
-                $display("held request blocked RX or changed parser counters");
-                $fatal;
-            end
-        end
-
-        build_host_command(8'h29);
-        send_built_frame();
-        repeat (2) @(posedge clk);
-        #1;
-        if (!request_valid || request_type !== held_request_type ||
-            request_length !== held_request_length ||
-            request_payload !== held_request_payload ||
-            request_crc16 !== held_request_crc16) begin
-            $display("ordinary overflow replaced the held request");
-            $fatal;
-        end
-        check_held_request = 1'b0;
-        request_ready = 1'b1;
-        @(posedge clk);
-        #1;
-        if (request_valid || !rx_ready) begin
-            $display("request handshake did not retire the held slot");
-            $fatal;
-        end
-
-        build_host_command(8'h26);
-        expected_payload = 272'd0;
-        expected_payload[7:0] = 8'h26;
-        send_built_frame();
-        expect_request(HOST_CMD, 6'd4, expected_payload);
-
-        $display("PASS: prod2u_p4_normal_v3_rx_tb");
-        $finish;
-    end
-endmodule

+ 0 - 114
tests/sim/prod2u_p4_normal_v3_tx_tb.v

@@ -1,114 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_normal_v3_tx_tb;
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg frame_valid = 1'b0;
-    wire frame_ready;
-    reg [7:0] frame_type = 8'h06;
-    reg [7:0] frame_payload_len = 8'd8;
-    reg [143:0] frame_payload = 144'h0800_1234_1602_2a01;
-    wire tx_valid;
-    reg tx_ready = 1'b1;
-    wire [7:0] tx_data;
-    reg [7:0] captured [0:40];
-    reg [15:0] expected_crc;
-    integer count;
-    integer index;
-
-    prod2u_p4_normal_v3_tx dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .frame_valid(frame_valid),
-        .frame_ready(frame_ready),
-        .frame_type(frame_type),
-        .frame_payload_len(frame_payload_len),
-        .frame_payload(frame_payload),
-        .tx_valid(tx_valid),
-        .tx_ready(tx_ready),
-        .tx_data(tx_data)
-    );
-
-    always #5 clk = ~clk;
-
-    always @(posedge clk) begin
-        if (frame_ready) frame_valid <= 1'b0;
-    end
-
-    function [15:0] crc16_byte;
-        input [15:0] crc_in;
-        input [7:0] data;
-        reg [15:0] value;
-        integer bit_index;
-        begin
-            value = crc_in ^ {data, 8'h00};
-            for (bit_index = 0; bit_index < 8; bit_index = bit_index + 1) begin
-                if (value[15]) value = (value << 1) ^ 16'h1021;
-                else value = value << 1;
-            end
-            crc16_byte = value;
-        end
-    endfunction
-
-    task capture_and_check;
-        input [7:0] expected_type;
-        input [7:0] expected_length;
-        input [143:0] expected_payload;
-        begin
-            count = 0;
-            while (count < 16 + expected_length) begin
-                @(posedge clk);
-                if (tx_valid && tx_ready) begin
-                    captured[count] = tx_data;
-                    count = count + 1;
-                end
-            end
-            if (captured[0] !== 8'ha5 || captured[1] !== 8'h5a ||
-                captured[2] !== 8'h02 || captured[3] !== 8'h04 ||
-                captured[4] !== expected_type || captured[13] !== expected_length) $fatal;
-            for (index = 5; index <= 12; index = index + 1) begin
-                if (captured[index] !== 8'd0) $fatal;
-            end
-            for (index = 0; index < expected_length; index = index + 1) begin
-                if (captured[14 + index] !== expected_payload[index * 8 +: 8]) $fatal;
-            end
-            expected_crc = 16'hffff;
-            for (index = 2; index < 14 + expected_length; index = index + 1) begin
-                expected_crc = crc16_byte(expected_crc, captured[index]);
-            end
-            if (captured[14 + expected_length] !== expected_crc[7:0] ||
-                captured[15 + expected_length] !== expected_crc[15:8]) $fatal;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-        end
-    endtask
-
-    task send_frame;
-        input [7:0] next_type;
-        input [7:0] next_length;
-        input [143:0] next_payload;
-        begin
-            frame_type = next_type;
-            frame_payload_len = next_length;
-            frame_payload = next_payload;
-            frame_valid = 1'b1;
-            capture_and_check(next_type, next_length, next_payload);
-            if (frame_valid) $fatal;
-        end
-    endtask
-
-    initial begin
-        repeat (4) @(negedge clk);
-        rst_n = 1'b1;
-        repeat (8) @(posedge clk);
-        #1;
-        if (tx_valid || frame_ready) $fatal(1, "TX emitted an unsolicited frame");
-
-        send_frame(8'h06, 8'd8, 144'h0800_1234_1602_2a01);
-        send_frame(8'h12, 8'd10, 144'h03_6400_64ff_0703_0003);
-
-        $display("PASS: prod2u_p4_normal_v3_tx_tb");
-        $finish;
-    end
-endmodule

+ 0 - 110
tests/sim/prod2u_p4_normal_v3_watchdog_contract_tb.v

@@ -1,110 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_normal_v3_watchdog_contract_tb;
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg arm = 1'b0;
-    reg refresh = 1'b0;
-    reg disable_cmd = 1'b0;
-    wire disabled;
-    wire armed;
-    wire watchdog_timeout;
-    wire expiry_due;
-    wire force_safe;
-
-    always #5 clk = ~clk;
-
-    prod2u_p4_normal_v3_watchdog #(
-        .CLK_HZ(10),
-        .WATCHDOG_SECONDS(1)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .arm(arm),
-        .refresh(refresh),
-        .disable_cmd(disable_cmd),
-        .disabled(disabled),
-        .armed(armed),
-        .watchdog_timeout(watchdog_timeout),
-        .expiry_due(expiry_due),
-        .force_safe(force_safe)
-    );
-
-    task pulse_arm;
-        begin
-            @(negedge clk); arm = 1'b1;
-            @(negedge clk); arm = 1'b0;
-        end
-    endtask
-
-    integer i;
-    initial begin
-        repeat (2) @(negedge clk);
-        rst_n = 1'b1;
-        @(negedge clk);
-        if (!disabled || armed || watchdog_timeout) $fatal(1, "reset contract");
-
-        // Refresh is side-effect free while disabled and cannot arm a lease.
-        refresh = 1'b1;
-        @(negedge clk);
-        refresh = 1'b0;
-        if (!disabled || armed || watchdog_timeout) $fatal(1, "refresh armed disabled watchdog");
-
-        pulse_arm();
-        if (disabled || !armed || watchdog_timeout) $fatal(1, "arm contract");
-
-        // Arm clears the elapsed counter. The first eight complete clocks are
-        // ordinary lease time. At clock nine expiry_due must hard-stop pins in
-        // the same combinational cycle, before timeout/disabled are registered.
-        for (i = 1; i < 9; i = i + 1) begin
-            @(posedge clk);
-            #1;
-            if (expiry_due || watchdog_timeout || force_safe || disabled || !armed)
-                $fatal(1, "watchdog expired early at elapsed clock %0d", i);
-        end
-        @(posedge clk);
-        #1;
-        if (!expiry_due || watchdog_timeout || !force_safe || disabled || !armed)
-            $fatal(1, "expiry arbitration boundary mismatch");
-        @(negedge clk);
-        refresh = 1'b1;
-        @(posedge clk);
-        #1;
-        if (!watchdog_timeout || force_safe || !disabled || armed)
-            $fatal(1, "expiry boundary not exposed after full lease");
-        @(negedge clk);
-        refresh = 1'b0;
-        if (!disabled || armed || !watchdog_timeout || force_safe)
-            $fatal(1, "expiry did not win over refresh");
-
-        // A legal actuation arm is the recovery action after timeout.
-        pulse_arm();
-        if (disabled || !armed || watchdog_timeout || force_safe)
-            $fatal(1, "arm did not recover timed-out watchdog");
-
-        // DISABLE remains the highest-priority input when arm is asserted in
-        // the same cycle. It must leave the watchdog disabled and unarmed.
-        @(negedge clk);
-        arm = 1'b1;
-        disable_cmd = 1'b1;
-        @(posedge clk);
-        #1;
-        if (!disabled || armed || watchdog_timeout || !force_safe)
-            $fatal(1, "disable did not win over simultaneous arm");
-        @(negedge clk);
-        arm = 1'b0;
-        disable_cmd = 1'b0;
-        #1;
-        if (!disabled || armed || watchdog_timeout || force_safe) begin
-            $display("DISABLE_PERSIST disabled=%0d armed=%0d timeout=%0d due=%0d safe=%0d",
-                disabled, armed, watchdog_timeout, expiry_due, force_safe);
-            $fatal(1, "disable priority state did not persist");
-        end
-
-        pulse_arm();
-        if (disabled || !armed || watchdog_timeout) $fatal(1, "post-disable arm failed");
-
-        $display("PASS: prod2u_p4_normal_v3_watchdog_contract_tb");
-        $finish;
-    end
-endmodule

+ 0 - 86
tests/sim/prod2u_p4_production_defaults_tb.v

@@ -1,86 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_production_defaults_tb;
-    reg sys_clk = 1'b0;
-    reg host_uart_rx = 1'b1;
-    reg x_limit_raw = 1'b0;
-    reg y_limit_raw = 1'b0;
-    wire host_uart_tx;
-    wire [23:0] ptc_pwm_out;
-    wire [3:0] fan_pwm_out;
-    wire solenoid_out;
-    wire motor_en_n;
-    wire x_step;
-    wire x_dir;
-    wire y_step;
-    wire y_dir;
-    wire z_step;
-    wire z_dir;
-
-    always #20 sys_clk = ~sys_clk;
-
-    prod2u_p4_normal_v3_top #(
-        .POR_CYCLES(4),
-        .SOLENOID_ACTIVE_HIGH(1)
-    ) dut (
-        .sys_clk(sys_clk),
-        .host_uart_rx(host_uart_rx),
-        .host_uart_tx(host_uart_tx),
-        .ptc_pwm_out(ptc_pwm_out),
-        .fan_pwm_out(fan_pwm_out),
-        .solenoid_out(solenoid_out),
-        .motor_en_n(motor_en_n),
-        .x_step(x_step),
-        .x_dir(x_dir),
-        .y_step(y_step),
-        .y_dir(y_dir),
-        .z_step(z_step),
-        .z_dir(z_dir),
-        .x_limit_raw(x_limit_raw),
-        .y_limit_raw(y_limit_raw)
-    );
-
-    task check_integer;
-        input [8*48-1:0] label_text;
-        input integer actual;
-        input integer expected;
-        begin
-            if (actual != expected) begin
-                $display("DEFAULT_FAIL %0s actual=%0d expected=%0d",
-                    label_text, actual, expected);
-                $fatal(1);
-            end
-        end
-    endtask
-
-    initial begin
-        #1;
-        check_integer("watchdog seconds", dut.WATCHDOG_SECONDS, 5);
-        check_integer("dir setup cycles", dut.MOTOR_DIR_SETUP_CYCLES, 25000);
-        check_integer("step half cycles", dut.MOTOR_STEP_HALF_CYCLES, 12500);
-        check_integer("core dir setup", dut.u_core.DIR_SETUP_CYCLES, 25000);
-        check_integer("core step half", dut.u_core.STEP_HALF_CYCLES, 12500);
-        check_integer("hub dir setup", dut.u_core.u_motors.DIR_SETUP_CYCLES, 25000);
-        check_integer("hub step half", dut.u_core.u_motors.STEP_HALF_CYCLES, 12500);
-        check_integer("X dir setup", dut.u_core.u_motors.u_x_axis.DIR_SETUP_CYCLES, 25000);
-        check_integer("Y dir setup", dut.u_core.u_motors.u_y_axis.DIR_SETUP_CYCLES, 25000);
-        check_integer("X step half", dut.u_core.u_motors.u_x_axis.STEP_HALF_CYCLES, 12500);
-        check_integer("Y step half", dut.u_core.u_motors.u_y_axis.STEP_HALF_CYCLES, 12500);
-        check_integer("X JOG counter bits", $bits(dut.u_core.u_motors.u_x_axis.remaining_steps), 16);
-        check_integer("Y JOG counter bits", $bits(dut.u_core.u_motors.u_y_axis.remaining_steps), 16);
-
-        wait (dut.sys_rst_n === 1'b1);
-        repeat (4) @(posedge sys_clk);
-        #1;
-        if (motor_en_n || x_step || y_step || z_step ||
-            dut.disabled !== 1'b1 || dut.watchdog_timeout !== 1'b0) begin
-            $display("DEFAULT_SAFE_FAIL en_n=%0d step=%0d%0d%0d disabled=%0d timeout=%0d",
-                motor_en_n, z_step, y_step, x_step,
-                dut.disabled, dut.watchdog_timeout);
-            $fatal(1);
-        end
-
-        $display("PASS: prod2u_p4_production_defaults_tb");
-        $finish;
-    end
-endmodule

+ 0 - 216
tests/sim/prod2u_p4_temperature_core_integration_tb.v

@@ -1,216 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_temperature_core_integration_tb;
-    localparam [7:0] FT_HOST_CMD = 8'h05;
-    localparam [7:0] FT_HOST_ACK = 8'h06;
-    localparam [7:0] CMD_GET_STATUS = 8'h24;
-    localparam [7:0] CMD_GET_TEMPERATURES = 8'h28;
-    localparam [7:0] STATUS_OK = 8'h00;
-    localparam [7:0] STATUS_BAD_VALUE = 8'h05;
-    localparam [7:0] STATUS_TEMP_BUS = 8'h0a;
-
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg request_valid = 1'b0;
-    wire request_ready;
-    reg [7:0] request_type = FT_HOST_CMD;
-    reg [5:0] request_length = 6'd4;
-    reg [271:0] request_payload = 272'd0;
-    reg [15:0] request_crc16 = 16'd0;
-    reg powerup_ready = 1'b0;
-    wire temperature_read_start;
-    reg temperature_read_done = 1'b0;
-    reg temperature_bus_error = 1'b0;
-    wire temperature_tx_start;
-    wire temperature_tx_force_ff;
-    reg temperature_tx_done = 1'b0;
-    wire frame_valid;
-    wire [7:0] frame_type;
-    wire [7:0] frame_payload_len;
-    wire [143:0] frame_payload;
-    integer guard;
-
-    always #5 clk = ~clk;
-
-    prod2u_p4_normal_v3_core #(
-        .CLK_HZ(32),
-        .WATCHDOG_SECONDS(1),
-        .DIR_SETUP_CYCLES(1),
-        .STEP_HALF_CYCLES(1)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_type(request_type),
-        .request_length(request_length),
-        .request_payload(request_payload),
-        .request_crc16(request_crc16),
-        .fast_jog_valid(1'b0),
-        .fast_jog_axis(2'd0),
-        .fast_jog_dir(1'b0),
-        .fast_jog_steps(16'd1),
-        .powerup_ready(powerup_ready),
-        .temperature_read_start(temperature_read_start),
-        .temperature_read_done(temperature_read_done),
-        .temperature_bus_error(temperature_bus_error),
-        .temperature_tx_start(temperature_tx_start),
-        .temperature_tx_force_ff(temperature_tx_force_ff),
-        .temperature_tx_done(temperature_tx_done),
-        .frame_valid(frame_valid),
-        .frame_ready(1'b1),
-        .frame_type(frame_type),
-        .frame_payload_len(frame_payload_len),
-        .frame_payload(frame_payload),
-        .ptc_percent(),
-        .fan_percent(),
-        .solenoid_percent(),
-        .state_hash16(),
-        .step_out(),
-        .dir_out(),
-        .en_n(),
-        .disabled(),
-        .watchdog_timeout()
-    );
-
-    task wait_ready;
-        begin
-            guard = 0;
-            while (!request_ready && guard < 256) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (!request_ready) begin
-                $display("CORE_REQUEST_READY_TIMEOUT");
-                $fatal;
-            end
-        end
-    endtask
-
-    task send_host;
-        input [7:0] command;
-        input [7:0] channel;
-        input [7:0] value;
-        input [7:0] flags;
-        begin
-            wait_ready();
-            @(negedge clk);
-            request_type = FT_HOST_CMD;
-            request_length = 6'd4;
-            request_payload = 272'd0;
-            request_payload[7:0] = command;
-            request_payload[15:8] = channel;
-            request_payload[23:16] = value;
-            request_payload[31:24] = flags;
-            request_crc16 = request_crc16 + 16'd1;
-            request_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            request_valid = 1'b0;
-        end
-    endtask
-
-    task pulse_temperature_done;
-        input bus_error_value;
-        begin
-            @(negedge clk);
-            temperature_bus_error = bus_error_value;
-            temperature_read_done = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            temperature_read_done = 1'b0;
-            temperature_bus_error = 1'b0;
-        end
-    endtask
-
-    task finish_temperature_tx;
-        begin
-            @(negedge clk);
-            temperature_tx_done = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            temperature_tx_done = 1'b0;
-            wait_ready();
-        end
-    endtask
-
-    task expect_ack;
-        input [7:0] command;
-        input [7:0] status;
-        input expected_ok;
-        begin
-            guard = 0;
-            while (!frame_valid && guard < 256) begin
-                @(posedge clk);
-                #1;
-                guard = guard + 1;
-            end
-            if (!frame_valid || frame_type !== FT_HOST_ACK ||
-                frame_payload_len !== 8'd8 ||
-                frame_payload[7:0] !== {7'd0, expected_ok} ||
-                frame_payload[15:8] !== command ||
-                frame_payload[23:16] !== status) begin
-                $display(
-                    "CORE_ACK_MISMATCH valid=%0d type=%02x len=%0d ok=%02x cmd=%02x status=%02x",
-                    frame_valid,
-                    frame_type,
-                    frame_payload_len,
-                    frame_payload[7:0],
-                    frame_payload[15:8],
-                    frame_payload[23:16]
-                );
-                $fatal;
-            end
-            wait_ready();
-        end
-    endtask
-
-    initial begin
-        repeat (4) @(negedge clk);
-        rst_n = 1'b1;
-        repeat (2) @(negedge clk);
-
-        powerup_ready = 1'b0;
-        send_host(CMD_GET_TEMPERATURES, 8'd0, 8'd0, 8'd0);
-        if (!temperature_tx_start || !temperature_tx_force_ff ||
-            temperature_read_start || frame_valid) begin
-            $display("CORE_EARLY_FF_PATH_MISMATCH");
-            $fatal;
-        end
-        finish_temperature_tx();
-
-        powerup_ready = 1'b1;
-        send_host(CMD_GET_TEMPERATURES, 8'd0, 8'd0, 8'd0);
-        if (!temperature_read_start || temperature_tx_start || frame_valid) begin
-            $display("CORE_READ_START_PATH_MISMATCH");
-            $fatal;
-        end
-        pulse_temperature_done(1'b0);
-        if (!temperature_tx_start || temperature_tx_force_ff || frame_valid) begin
-            $display("CORE_SUCCESS_TX_PATH_MISMATCH");
-            $fatal;
-        end
-        finish_temperature_tx();
-
-        send_host(CMD_GET_TEMPERATURES, 8'd0, 8'd0, 8'd0);
-        if (!temperature_read_start) $fatal;
-        pulse_temperature_done(1'b1);
-        expect_ack(CMD_GET_TEMPERATURES, STATUS_TEMP_BUS, 1'b0);
-
-        send_host(CMD_GET_TEMPERATURES, 8'd1, 8'd0, 8'd0);
-        if (temperature_read_start || temperature_tx_start) begin
-            $display("CORE_NONEXACT_REQUEST_TOUCHED_TEMPERATURE_PATH");
-            $fatal;
-        end
-        expect_ack(CMD_GET_TEMPERATURES, STATUS_BAD_VALUE, 1'b0);
-
-        send_host(CMD_GET_STATUS, 8'd0, 8'd0, 8'd0);
-        expect_ack(CMD_GET_STATUS, STATUS_OK, 1'b1);
-
-        $display("PASS: prod2u_p4_temperature_core_integration_tb");
-        $finish;
-    end
-endmodule

+ 0 - 230
tests/sim/prod2u_p4_temperature_short_tx_tb.v

@@ -1,230 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_temperature_short_tx_tb;
-    reg clk = 1'b0;
-    reg rst_n = 1'b0;
-    reg start = 1'b0;
-    reg force_ff = 1'b0;
-    wire rd_req;
-    wire [4:0] rd_addr;
-    reg rd_valid = 1'b0;
-    reg [7:0] rd_data = 8'd0;
-    wire tx_valid;
-    reg tx_ready = 1'b1;
-    wire [7:0] tx_data;
-    wire busy;
-    wire done;
-
-    reg [7:0] memory [0:26];
-    reg [7:0] captured [0:34];
-    reg [15:0] expected_crc;
-    reg [7:0] stalled_data;
-    integer capture_count;
-    integer read_count;
-    integer index;
-    integer wait_cycles;
-
-    prod2u_p4_temperature_short_tx dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .start(start),
-        .force_ff(force_ff),
-        .rd_req(rd_req),
-        .rd_addr(rd_addr),
-        .rd_valid(rd_valid),
-        .rd_data(rd_data),
-        .tx_valid(tx_valid),
-        .tx_ready(tx_ready),
-        .tx_data(tx_data),
-        .busy(busy),
-        .done(done)
-    );
-
-    always #5 clk = ~clk;
-
-    always @(posedge clk) begin
-        if (!rst_n) begin
-            rd_valid <= 1'b0;
-            rd_data <= 8'd0;
-            read_count <= 0;
-        end else begin
-            rd_valid <= rd_req;
-            if (rd_req) begin
-                if (rd_addr > 5'd26 || rd_addr !== read_count[4:0]) begin
-                    $display(
-                        "STORE_READ_ORDER_MISMATCH count=%0d addr=%0d",
-                        read_count,
-                        rd_addr
-                    );
-                    $fatal;
-                end
-                rd_data <= memory[rd_addr];
-                read_count <= read_count + 1;
-            end
-        end
-    end
-
-    function [15:0] crc16_byte;
-        input [15:0] crc_in;
-        input [7:0] value_in;
-        reg [15:0] value;
-        integer bit_index;
-        begin
-            value = crc_in ^ {value_in, 8'h00};
-            for (bit_index = 0; bit_index < 8; bit_index = bit_index + 1) begin
-                if (value[15]) value = (value << 1) ^ 16'h1021;
-                else value = value << 1;
-            end
-            crc16_byte = value;
-        end
-    endfunction
-
-    task pulse_start;
-        input next_force_ff;
-        begin
-            @(negedge clk);
-            force_ff = next_force_ff;
-            start = 1'b1;
-            @(posedge clk);
-            #1;
-            start = 1'b0;
-        end
-    endtask
-
-    task capture_frame;
-        input expected_force_ff;
-        begin
-            capture_count = 0;
-            wait_cycles = 0;
-            while (tx_valid !== 1'b1 && wait_cycles < 100) begin
-                @(posedge clk);
-                #1;
-                wait_cycles = wait_cycles + 1;
-            end
-            if (!tx_valid) begin
-                $display("TX_VALID_TIMEOUT force_ff=%0d", expected_force_ff);
-                $fatal;
-            end
-
-            @(negedge clk);
-            tx_ready = 1'b0;
-            stalled_data = tx_data;
-            repeat (4) begin
-                @(posedge clk);
-                #1;
-                if (!tx_valid || tx_data !== stalled_data) begin
-                    $display(
-                        "TX_CHANGED_UNDER_BACKPRESSURE valid=%0d data=%02x expected=%02x",
-                        tx_valid,
-                        tx_data,
-                        stalled_data
-                    );
-                    $fatal;
-                end
-            end
-            @(negedge clk);
-            tx_ready = 1'b1;
-
-            wait_cycles = 0;
-            while (capture_count < 35 && wait_cycles < 500) begin
-                @(posedge clk);
-                if (tx_valid && tx_ready) begin
-                    captured[capture_count] = tx_data;
-                    capture_count = capture_count + 1;
-                end
-                #1;
-                wait_cycles = wait_cycles + 1;
-            end
-            if (capture_count !== 35) begin
-                $display("TX_FRAME_TIMEOUT captured=%0d", capture_count);
-                $fatal;
-            end
-            if (captured[0] !== 8'ha5 || captured[1] !== 8'h5a ||
-                captured[2] !== 8'h02 || captured[3] !== 8'h04 ||
-                captured[4] !== 8'h10 || captured[5] !== 8'h1b) begin
-                $display("SHORT_HEADER_MISMATCH");
-                $fatal;
-            end
-            for (index = 0; index < 27; index = index + 1) begin
-                if (captured[6 + index] !==
-                    (expected_force_ff ? 8'hff : index[7:0])) begin
-                    $display(
-                        "SHORT_PAYLOAD_MISMATCH index=%0d data=%02x expected=%02x",
-                        index,
-                        captured[6 + index],
-                        (expected_force_ff ? 8'hff : index[7:0])
-                    );
-                    $fatal;
-                end
-            end
-
-            expected_crc = 16'hffff;
-            for (index = 2; index < 33; index = index + 1) begin
-                expected_crc = crc16_byte(expected_crc, captured[index]);
-            end
-            if (captured[33] !== expected_crc[7:0] ||
-                captured[34] !== expected_crc[15:8]) begin
-                $display(
-                    "SHORT_CRC_MISMATCH got=%02x%02x expected_lo_hi=%02x%02x",
-                    captured[33],
-                    captured[34],
-                    expected_crc[7:0],
-                    expected_crc[15:8]
-                );
-                $fatal;
-            end
-
-            wait_cycles = 0;
-            while (done !== 1'b1 && wait_cycles < 5) begin
-                @(posedge clk);
-                #1;
-                wait_cycles = wait_cycles + 1;
-            end
-            if (!done || busy) begin
-                $display("TX_DONE_MISMATCH done=%0d busy=%0d", done, busy);
-                $fatal;
-            end
-        end
-    endtask
-
-    initial begin
-        for (index = 0; index < 27; index = index + 1) begin
-            memory[index] = index[7:0];
-        end
-
-        repeat (4) @(negedge clk);
-        rst_n = 1'b1;
-        pulse_start(1'b0);
-        if (!busy) begin
-            $display("TX_BUSY_NOT_ASSERTED_AFTER_START");
-            $fatal;
-        end
-        capture_frame(1'b0);
-        if (read_count !== 27) begin
-            $display("STORE_READ_COUNT_MISMATCH count=%0d", read_count);
-            $fatal;
-        end
-        if ({captured[34], captured[33]} !== 16'hc91f) begin
-            $display("GOLDEN_CRC_MISMATCH crc=%02x%02x", captured[33], captured[34]);
-            $fatal;
-        end
-
-        @(negedge clk);
-        rst_n = 1'b0;
-        repeat (2) @(negedge clk);
-        rst_n = 1'b1;
-        pulse_start(1'b1);
-        capture_frame(1'b1);
-        if (read_count !== 0) begin
-            $display("FORCE_FF_READ_STORE count=%0d", read_count);
-            $fatal;
-        end
-        if ({captured[34], captured[33]} !== 16'hc41b) begin
-            $display("ALL_FF_CRC_MISMATCH crc=%02x%02x", captured[33], captured[34]);
-            $fatal;
-        end
-
-        $display("PASS: prod2u_p4_temperature_short_tx_tb");
-        $finish;
-    end
-endmodule

+ 0 - 260
tests/sim/prod2u_p4_temperature_top_integration_tb.v

@@ -1,260 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_temperature_top_integration_tb;
-    reg clk = 1'b0;
-    reg host_rst_n = 1'b0;
-    reg host_to_dut = 1'b1;
-    wire dut_to_host;
-    wire host_rx_valid;
-    wire [7:0] host_rx_data;
-    reg force_sda_low = 1'b0;
-    tri1 temp_scl;
-    tri1 temp_sda;
-    reg [7:0] request_frame [0:23];
-    reg [7:0] captured [0:127];
-    integer request_length;
-    integer captured_count = 0;
-    integer read_index = 0;
-    integer index;
-    integer guard;
-    integer accepted_requests = 0;
-    integer host_bytes_launched = 0;
-    integer dut_bytes_received = 0;
-    reg [7:0] last_accepted_command = 8'd0;
-    reg [15:0] crc;
-    reg early_i2c_seen = 1'b0;
-
-    assign temp_sda = force_sda_low ? 1'b0 : 1'bz;
-
-    uart_rx_8n1 #(.CLKS_PER_BIT(4)) u_host_rx (
-        .clk(clk),
-        .rst_n(host_rst_n),
-        .rx_i(dut_to_host),
-        .rx_valid(host_rx_valid),
-        .rx_data(host_rx_data),
-        .rx_ready(1'b1),
-        .framing_error(),
-        .break_detected(),
-        .overflow()
-    );
-
-    prod2u_p4_normal_v3_top #(
-        .CLK_HZ(10000),
-        .HOST_UART_CLKS_PER_BIT(4),
-        .POR_CYCLES(4),
-        .INTER_BYTE_TIMEOUT_MS(8),
-        .PTC_STEP_CLKS(1),
-        .FAN_STEP_CLKS(1),
-        .SOLENOID_ACTIVE_HIGH(1)
-    ) dut (
-        .sys_clk(clk),
-        .host_uart_rx(host_to_dut),
-        .host_uart_tx(dut_to_host),
-        .ptc_pwm_out(),
-        .fan_pwm_out(),
-        .solenoid_out(),
-        .motor_en_n(),
-        .x_step(),
-        .x_dir(),
-        .y_step(),
-        .y_dir(),
-        .z_step(),
-        .z_dir(),
-        .x_limit_raw(1'b0),
-        .y_limit_raw(1'b0),
-        .temp_scl(temp_scl),
-        .temp_sda(temp_sda)
-    );
-
-    always #5 clk = ~clk;
-
-    always @(posedge clk) begin
-        if (host_rx_valid) begin
-            captured[captured_count] <= host_rx_data;
-            captured_count <= captured_count + 1;
-        end
-        if (!dut.temperature_powerup_ready && dut.temperature_i2c_request_valid)
-            early_i2c_seen <= 1'b1;
-        if (dut.request_valid && dut.request_ready) begin
-            accepted_requests <= accepted_requests + 1;
-            last_accepted_command <= dut.request_payload[7:0];
-        end
-        if (dut.uart_rx_valid && dut.uart_rx_ready)
-            dut_bytes_received <= dut_bytes_received + 1;
-    end
-
-    function [15:0] crc16_byte;
-        input [15:0] crc_in;
-        input [7:0] data;
-        reg [15:0] value;
-        integer bit_index;
-        begin
-            value = crc_in ^ {data, 8'h00};
-            for (bit_index = 0; bit_index < 8; bit_index = bit_index + 1) begin
-                if (value[15]) value = (value << 1) ^ 16'h1021;
-                else value = value << 1;
-            end
-            crc16_byte = value;
-        end
-    endfunction
-
-    task build_host_command;
-        input [7:0] command;
-        begin
-            for (index = 0; index < 24; index = index + 1)
-                request_frame[index] = 8'd0;
-            request_frame[0] = 8'ha5;
-            request_frame[1] = 8'h5a;
-            request_frame[2] = 8'h02;
-            request_frame[3] = 8'h04;
-            request_frame[4] = 8'h05;
-            request_frame[13] = 8'd4;
-            request_frame[14] = command;
-            request_length = 20;
-            crc = 16'hffff;
-            for (index = 2; index < 18; index = index + 1)
-                crc = crc16_byte(crc, request_frame[index]);
-            request_frame[18] = crc[7:0];
-            request_frame[19] = crc[15:8];
-        end
-    endtask
-
-    task send_request;
-        integer byte_index;
-        integer bit_index;
-        begin
-            for (byte_index = 0; byte_index < request_length; byte_index = byte_index + 1) begin
-                @(negedge clk);
-                host_to_dut = 1'b0;
-                repeat (4) @(posedge clk);
-                for (bit_index = 0; bit_index < 8; bit_index = bit_index + 1) begin
-                    @(negedge clk);
-                    host_to_dut = request_frame[byte_index][bit_index];
-                    repeat (4) @(posedge clk);
-                end
-                @(negedge clk);
-                host_to_dut = 1'b1;
-                repeat (4) @(posedge clk);
-                host_bytes_launched = host_bytes_launched + 1;
-            end
-        end
-    endtask
-
-    task wait_bytes;
-        input integer count;
-        begin
-            guard = 0;
-            while (captured_count < read_index + count && guard < 200000) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (captured_count < read_index + count) begin
-                $display(
-                    "TOP_TEMPERATURE_UART_TIMEOUT have=%0d need=%0d host_bytes=%0d dut_bytes=%0d accepted=%0d last_cmd=%02x crc_err=%0d timeout_err=%0d format_err=%0d req_valid=%0d req_ready=%0d core_state=%0d inflight=%0d read_state=%0d read_done=%0d bus_error=%0d i2c_state=%0d i2c_valid=%0d i2c_error=%0d frame_valid=%0d tx_owner=%0d",
-                    captured_count,
-                    read_index + count,
-                    host_bytes_launched,
-                    dut_bytes_received,
-                    accepted_requests,
-                    last_accepted_command,
-                    dut.parser_crc_error_count,
-                    dut.parser_timeout_count,
-                    dut.parser_format_error_count,
-                    dut.request_valid,
-                    dut.request_ready,
-                    dut.u_core.state,
-                    dut.u_core.command_inflight,
-                    dut.u_temperature_read.state,
-                    dut.temperature_read_done,
-                    dut.temperature_bus_error,
-                    dut.u_temperature_i2c.state,
-                    dut.temperature_i2c_response_valid,
-                    dut.temperature_i2c_error,
-                    dut.frame_valid,
-                    dut.u_tx_frames.owner
-                );
-                $fatal;
-            end
-        end
-    endtask
-
-    task check_crc;
-        input integer frame_length;
-        begin
-            crc = 16'hffff;
-            for (index = read_index + 2; index < read_index + frame_length - 2; index = index + 1)
-                crc = crc16_byte(crc, captured[index]);
-            if (captured[read_index + frame_length - 2] !== crc[7:0] ||
-                captured[read_index + frame_length - 1] !== crc[15:8]) begin
-                $display("TOP_TEMPERATURE_CRC_MISMATCH");
-                $fatal;
-            end
-        end
-    endtask
-
-    task expect_all_ff_temperature;
-        begin
-            wait_bytes(35);
-            if (captured[read_index] !== 8'ha5 || captured[read_index + 1] !== 8'h5a ||
-                captured[read_index + 2] !== 8'h02 || captured[read_index + 3] !== 8'h04 ||
-                captured[read_index + 4] !== 8'h10 || captured[read_index + 5] !== 8'h1b)
-                $fatal;
-            for (index = 0; index < 27; index = index + 1)
-                if (captured[read_index + 6 + index] !== 8'hff) $fatal;
-            check_crc(35);
-            read_index = read_index + 35;
-        end
-    endtask
-
-    task expect_ack;
-        input [7:0] command;
-        input [7:0] status;
-        input expected_ok;
-        begin
-            wait_bytes(24);
-            if (captured[read_index + 4] !== 8'h06 ||
-                captured[read_index + 13] !== 8'd8 ||
-                captured[read_index + 14] !== {7'd0, expected_ok} ||
-                captured[read_index + 15] !== command ||
-                captured[read_index + 16] !== status) begin
-                $display("TOP_TEMPERATURE_ACK_MISMATCH");
-                $fatal;
-            end
-            check_crc(24);
-            read_index = read_index + 24;
-        end
-    endtask
-
-    initial begin
-        repeat (4) @(negedge clk);
-        host_rst_n = 1'b1;
-        wait (dut.sys_rst_n === 1'b1);
-
-        build_host_command(8'h28);
-        send_request();
-        expect_all_ff_temperature();
-        if (early_i2c_seen) begin
-            $display("EARLY_GET_ACCESSED_I2C");
-            $fatal;
-        end
-
-        wait (dut.temperature_powerup_ready === 1'b1);
-        force_sda_low = 1'b1;
-        build_host_command(8'h28);
-        send_request();
-        expect_ack(8'h28, 8'h0a, 1'b0);
-        force_sda_low = 1'b0;
-        repeat (8) @(negedge clk);
-        if (dut.temperature_scl_drive_low || dut.temperature_sda_drive_low) begin
-            $display("TOP_TEMPERATURE_BUS_NOT_RELEASED_AFTER_ERROR");
-            $fatal;
-        end
-
-        build_host_command(8'h24);
-        send_request();
-        expect_ack(8'h24, 8'h00, 1'b1);
-
-        $display("PASS: prod2u_p4_temperature_top_integration_tb");
-        $finish;
-    end
-endmodule

+ 0 - 201
tests/sim/uart_8n1_phy_tb.v

@@ -1,201 +0,0 @@
-`timescale 1ns/1ps
-
-module uart_8n1_phy_tb;
-    reg clk;
-    reg rst_n;
-    reg tx_valid;
-    reg [7:0] tx_data;
-    wire tx_ready;
-    wire tx_line;
-    wire rx_valid;
-    wire [7:0] rx_data;
-    wire rx_framing_error;
-    wire rx_break_detected;
-    wire rx_overflow;
-    reg rx_ready;
-    reg tx_min_valid;
-    reg [7:0] tx_min_data;
-    wire tx_min_ready;
-    wire tx_min_line;
-    wire tx_min_busy;
-    reg tx_np_valid;
-    reg [7:0] tx_np_data;
-    wire tx_np_ready;
-    wire tx_np_line;
-    wire tx_np_busy;
-    wire rx_np_valid;
-    wire [7:0] rx_np_data;
-    wire rx_np_framing_error;
-    wire rx_np_break_detected;
-    wire rx_np_overflow;
-    reg rx_np_ready;
-    integer min_busy_cycles;
-
-    uart_tx_8n1 #(
-        .CLKS_PER_BIT(4)
-    ) u_tx (
-        .clk(clk),
-        .rst_n(rst_n),
-        .tx_valid(tx_valid),
-        .tx_data(tx_data),
-        .tx_ready(tx_ready),
-        .tx_o(tx_line),
-        .busy()
-    );
-
-    uart_rx_8n1 #(
-        .CLKS_PER_BIT(4)
-    ) u_rx (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_i(tx_line),
-        .rx_valid(rx_valid),
-        .rx_data(rx_data),
-        .rx_ready(rx_ready),
-        .framing_error(rx_framing_error),
-        .break_detected(rx_break_detected),
-        .overflow(rx_overflow)
-    );
-
-    uart_tx_8n1 #(
-        .CLKS_PER_BIT(1)
-    ) u_tx_min (
-        .clk(clk),
-        .rst_n(rst_n),
-        .tx_valid(tx_min_valid),
-        .tx_data(tx_min_data),
-        .tx_ready(tx_min_ready),
-        .tx_o(tx_min_line),
-        .busy(tx_min_busy)
-    );
-
-    uart_tx_8n1 #(
-        .CLKS_PER_BIT(3)
-    ) u_tx_np (
-        .clk(clk),
-        .rst_n(rst_n),
-        .tx_valid(tx_np_valid),
-        .tx_data(tx_np_data),
-        .tx_ready(tx_np_ready),
-        .tx_o(tx_np_line),
-        .busy(tx_np_busy)
-    );
-
-    uart_rx_8n1 #(
-        .CLKS_PER_BIT(3)
-    ) u_rx_np (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_i(tx_np_line),
-        .rx_valid(rx_np_valid),
-        .rx_data(rx_np_data),
-        .rx_ready(rx_np_ready),
-        .framing_error(rx_np_framing_error),
-        .break_detected(rx_np_break_detected),
-        .overflow(rx_np_overflow)
-    );
-
-    initial begin
-        clk = 1'b0;
-        forever #5 clk = ~clk;
-    end
-
-    task send_byte;
-        input [7:0] value;
-        begin
-            while (!tx_ready) @(negedge clk);
-            tx_data = value;
-            tx_valid = 1'b1;
-            @(negedge clk);
-            tx_valid = 1'b0;
-        end
-    endtask
-
-    task send_np_byte;
-        input [7:0] value;
-        begin
-            while (!tx_np_ready) @(negedge clk);
-            tx_np_data = value;
-            tx_np_valid = 1'b1;
-            @(negedge clk);
-            tx_np_valid = 1'b0;
-        end
-    endtask
-
-    initial begin
-        rst_n = 1'b0;
-        tx_valid = 1'b0;
-        tx_data = 8'd0;
-        rx_ready = 1'b1;
-        tx_min_valid = 1'b0;
-        tx_min_data = 8'd0;
-        tx_np_valid = 1'b0;
-        tx_np_data = 8'd0;
-        rx_np_ready = 1'b1;
-        repeat (4) @(negedge clk);
-        rst_n = 1'b1;
-
-        if ($bits(u_tx_min.clk_count) != 1 ||
-            $bits(u_tx_np.clk_count) != 2 ||
-            $bits(u_rx_np.clk_count) != 2) begin
-            $display(
-                "UART clock counter widths mismatch tx1=%0d tx3=%0d rx3=%0d",
-                $bits(u_tx_min.clk_count),
-                $bits(u_tx_np.clk_count),
-                $bits(u_rx_np.clk_count)
-            );
-            $fatal;
-        end
-
-        send_byte(8'ha5);
-        wait (rx_valid === 1'b1);
-        if (rx_data !== 8'ha5 || rx_framing_error || rx_break_detected || rx_overflow) begin
-            $display("UART 8N1 loopback mismatch data=%02x framing=%0b break=%0b overflow=%0b",
-                rx_data, rx_framing_error, rx_break_detected, rx_overflow);
-            $fatal;
-        end
-        @(negedge clk);
-
-        send_np_byte(8'h5a);
-        wait (rx_np_valid === 1'b1);
-        if (rx_np_data !== 8'h5a || rx_np_framing_error ||
-            rx_np_break_detected || rx_np_overflow) begin
-            $display(
-                "UART non-power-of-two loopback mismatch data=%02x framing=%0b break=%0b overflow=%0b",
-                rx_np_data,
-                rx_np_framing_error,
-                rx_np_break_detected,
-                rx_np_overflow
-            );
-            $fatal;
-        end
-        @(negedge clk);
-
-        while (!tx_min_ready) @(negedge clk);
-        tx_min_data = 8'h96;
-        tx_min_valid = 1'b1;
-        @(posedge clk);
-        #1;
-        @(negedge clk);
-        tx_min_valid = 1'b0;
-        min_busy_cycles = 0;
-        while (tx_min_busy && min_busy_cycles < 12) begin
-            @(posedge clk);
-            #1;
-            min_busy_cycles = min_busy_cycles + 1;
-        end
-        if (min_busy_cycles !== 10 || tx_min_busy || !tx_min_ready || tx_min_line !== 1'b1) begin
-            $display(
-                "UART one-clock TX mismatch cycles=%0d busy=%0b ready=%0b line=%0b",
-                min_busy_cycles,
-                tx_min_busy,
-                tx_min_ready,
-                tx_min_line
-            );
-            $fatal;
-        end
-
-        $display("PASS: uart_8n1_phy_tb");
-        $finish;
-    end
-endmodule

+ 0 - 94
tests/sim/uart_rx_back_to_back_tb.v

@@ -1,94 +0,0 @@
-`timescale 1ns/1ps
-
-module uart_rx_back_to_back_tb;
-    localparam integer CLKS_PER_BIT = 8;
-
-    reg clk;
-    reg rst_n;
-    reg rx_i;
-    reg rx_ready;
-    wire rx_valid;
-    wire [7:0] rx_data;
-    wire framing_error;
-    wire break_detected;
-    wire overflow;
-    reg [7:0] captured [0:3];
-    integer capture_count;
-
-    uart_rx_8n1 #(
-        .CLKS_PER_BIT(CLKS_PER_BIT),
-        .BREAK_BITS(11)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .rx_i(rx_i),
-        .rx_valid(rx_valid),
-        .rx_data(rx_data),
-        .rx_ready(rx_ready),
-        .framing_error(framing_error),
-        .break_detected(break_detected),
-        .overflow(overflow)
-    );
-
-    initial begin
-        clk = 1'b0;
-        forever #5 clk = ~clk;
-    end
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            capture_count <= 0;
-        end else if (rx_valid) begin
-            captured[capture_count] <= rx_data;
-            capture_count <= capture_count + 1;
-        end
-    end
-
-    task drive_uart_byte;
-        input [7:0] value;
-        integer bit_index;
-        begin
-            rx_i = 1'b0;
-            repeat (CLKS_PER_BIT) @(negedge clk);
-            for (bit_index = 0; bit_index < 8; bit_index = bit_index + 1) begin
-                rx_i = value[bit_index];
-                repeat (CLKS_PER_BIT) @(negedge clk);
-            end
-            rx_i = 1'b1;
-            repeat (CLKS_PER_BIT) @(negedge clk);
-        end
-    endtask
-
-    initial begin
-        rst_n = 1'b0;
-        rx_i = 1'b1;
-        rx_ready = 1'b1;
-        repeat (4) @(negedge clk);
-        rst_n = 1'b1;
-
-        drive_uart_byte(8'h33);
-        drive_uart_byte(8'h34);
-        drive_uart_byte(8'h20);
-        drive_uart_byte(8'h0a);
-        repeat (16) @(negedge clk);
-
-        if (capture_count !== 4 || captured[0] !== 8'h33 || captured[1] !== 8'h34 ||
-            captured[2] !== 8'h20 || captured[3] !== 8'h0a || framing_error || break_detected || overflow) begin
-            $display(
-                "UART RX back-to-back mismatch count=%0d bytes=%02x %02x %02x %02x framing=%0b break=%0b overflow=%0b",
-                capture_count,
-                captured[0],
-                captured[1],
-                captured[2],
-                captured[3],
-                framing_error,
-                break_detected,
-                overflow
-            );
-            $fatal;
-        end
-
-        $display("PASS: uart_rx_back_to_back_tb");
-        $finish;
-    end
-endmodule

+ 0 - 206
tests/unit/test_prod2u_p4_ack_only_host_contract.py

@@ -1,206 +0,0 @@
-#!/usr/bin/env python3
-"""RED contract tests for the minimal ACK-only Normal-v3 wire path."""
-
-from __future__ import annotations
-
-import importlib.util
-import sys
-import unittest
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[2]
-TOOLS = ROOT / "tools"
-sys.path.insert(0, str(TOOLS))
-
-import prod2u_p4_normal_v3_model as model_v3  # noqa: E402
-import prod2u_p4_protocol as protocol  # noqa: E402
-
-
-GOLDEN_REQUEST_HEX = {
-    "enable": (
-        "a55a0204070000000000000000222a00"
-        "000000000000000000000000000000000000000000000000"
-        "1e1e1e1e00000000d6df"
-    ),
-    "jog_x": "a55a020411000000000000000008350001000100000086c3",
-    "jog_y": "a55a0204110000000000000000083501000001000000473e",
-    "mark_x": "a55a0204110000000000000000083600010000000000477d",
-    "mark_y": "a55a02041100000000000000000836010000000000008680",
-    "open": (
-        "a55a0204070000000000000000222a00"
-        "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a"
-        "46464646646464642c75"
-    ),
-    "close": (
-        "a55a0204070000000000000000222a00"
-        "0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a0a"
-        "4646464600000000684a"
-    ),
-    "disable": "a55a02040500000000000000000426000000c4ae",
-}
-
-
-def load_cli():
-    path = TOOLS / "prod2u_p4_cli.py"
-    spec = importlib.util.spec_from_file_location(
-        "test_prod2u_p4_minimal_ack_only_cli",
-        path,
-    )
-    if spec is None or spec.loader is None:
-        raise AssertionError(f"unable to import {path}")
-    module = importlib.util.module_from_spec(spec)
-    sys.modules[spec.name] = module
-    spec.loader.exec_module(module)
-    return module
-
-
-class ScriptedEndpoint:
-    """Expose scripted response bytes only after the request is written."""
-
-    def __init__(self, response: bytes) -> None:
-        self._response = bytearray(response)
-        self.writes: list[bytes] = []
-
-    def write(self, data: bytes) -> int:
-        self.writes.append(bytes(data))
-        return len(data)
-
-    def read(self, size: int = 1) -> bytes:
-        if not self.writes or not self._response:
-            return b""
-        take = min(size, len(self._response))
-        result = bytes(self._response[:take])
-        del self._response[:take]
-        return result
-
-
-def legacy_temperature_request() -> bytes:
-    return protocol.encode_frame(
-        frame_type=protocol.FrameType.HOST_CMD,
-        seq=0,
-        timestamp_tick=0,
-        payload=b"\x29\x00\x00\x00",
-    )
-
-
-class Prod2UP4MinimalAckOnlyContractTests(unittest.TestCase):
-    def test_existing_input_request_hex_vectors_remain_byte_exact(self) -> None:
-        self.assertEqual(
-            {name: value.hex() for name, value in model_v3.GOLDEN_VECTORS.items()},
-            GOLDEN_REQUEST_HEX,
-        )
-
-    def test_ordinary_command_accepts_ack_as_first_and_only_response(self) -> None:
-        cli = load_cli()
-        request = protocol.build_host_command(command=protocol.CommandId.GET_STATUS)
-        ack = protocol.build_host_ack(
-            ok=True,
-            command=protocol.CommandId.GET_STATUS,
-            status=protocol.StatusCode.OK,
-            state_hash16=0xBEEF,
-        )
-        endpoint = ScriptedEndpoint(ack)
-        session = cli.NormalSession(endpoint, timeout_seconds=0.05)
-
-        result = session.command(request, expected_command=protocol.CommandId.GET_STATUS)
-
-        self.assertEqual(result.raw_response, ack)
-        self.assertEqual(
-            [frame.frame_type for frame in result.frames],
-            [protocol.FrameType.HOST_ACK],
-        )
-        self.assertEqual(result.ack.state_hash16, 0xBEEF)
-        self.assertEqual(endpoint.writes, [request])
-        self.assertFalse(hasattr(session, "_trace_policy"))
-        self.assertFalse(hasattr(result, "command_result_trace"))
-
-    def test_motor_status_response_is_ack_then_one_ten_byte_status(self) -> None:
-        cli = load_cli()
-        request = protocol.build_get_motor_status()
-        ack = protocol.build_host_ack(
-            ok=True,
-            command=protocol.MotionOpcode.GET_MOTOR_STATUS,
-            status=protocol.StatusCode.OK,
-            response_type=protocol.FrameType.MOTION_STATUS,
-            result_flags=0x08,
-        )
-        status_wire = protocol.build_motion_status(
-            flags=0x02,
-            position_valid_mask=0,
-            busy_mask=0,
-            current_xyz=(0xFF, 0xFF, 0xFF),
-            target_xyz=(0xFF, 0xFF, 0xFF),
-            fault_mask=0,
-        )
-        endpoint = ScriptedEndpoint(ack + status_wire)
-        session = cli.NormalSession(endpoint, timeout_seconds=0.05)
-
-        result = session.motor_status()
-        frames, remainder = protocol.decode_stream(result.raw_response)
-
-        self.assertEqual(remainder, b"")
-        self.assertEqual(
-            [frame.frame_type for frame in frames],
-            [protocol.FrameType.HOST_ACK, protocol.FrameType.MOTION_STATUS],
-        )
-        self.assertEqual(len(frames[1].payload), protocol.MOTION_STATUS_PAYLOAD_LEN)
-        self.assertEqual(result.status.current_xyz, (0xFF, 0xFF, 0xFF))
-        self.assertEqual(endpoint.writes, [request])
-
-    def test_mark_closed_is_unsupported_and_has_no_model_side_effect(self) -> None:
-        subject = model_v3.NormalV3Model()
-        before = subject.state_fingerprint()
-
-        result = subject.apply_frame(bytes.fromhex(GOLDEN_REQUEST_HEX["mark_x"]))
-
-        self.assertFalse(result.accepted)
-        self.assertEqual(result.command, 0x36)
-        self.assertEqual(result.status, protocol.StatusCode.UNSUPPORTED_IN_PROFILE)
-        self.assertEqual(subject.state_fingerprint(), before)
-
-    def test_legacy_temperature_request_is_unsupported_and_has_no_side_effect(self) -> None:
-        subject = model_v3.NormalV3Model()
-        before = subject.state_fingerprint()
-
-        result = subject.apply_frame(legacy_temperature_request())
-
-        self.assertFalse(result.accepted)
-        self.assertEqual(result.command, 0x29)
-        self.assertEqual(result.status, protocol.StatusCode.UNSUPPORTED_IN_PROFILE)
-        self.assertEqual(subject.state_fingerprint(), before)
-
-    def test_jog_step_field_keeps_zero_invalid_and_65535_valid(self) -> None:
-        with self.assertRaisesRegex(ValueError, "steps must be from 1 to 65535"):
-            protocol.build_motor_jog(axis=0, raw_dir=1, speed_code=3, steps=0)
-
-        maximum = protocol.build_motor_jog(
-            axis=1,
-            raw_dir=1,
-            speed_code=3,
-            steps=65535,
-        )
-        decoded = protocol.decode_motion_command(protocol.decode_frame(maximum))
-
-        self.assertEqual(decoded.steps, 65535)
-        self.assertEqual(protocol.decode_frame(maximum).payload[4:6], b"\xFF\xFF")
-
-    def test_snapshot_ack_has_no_axis_acceptance_or_skip_bits(self) -> None:
-        wire = protocol.build_host_ack(
-            ok=True,
-            command=protocol.CommandId.SET_OUTPUT_SNAPSHOT,
-            status=protocol.StatusCode.OK,
-            detail=0,
-            state_hash16=0xE177,
-            result_flags=0x01,
-        )
-
-        ack = protocol.decode_host_ack(protocol.decode_frame(wire))
-
-        self.assertEqual(ack.detail, 0)
-        self.assertEqual(ack.state_hash16, 0xE177)
-        self.assertEqual(ack.result_flags, 0x01)
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 304
tests/unit/test_prod2u_p4_activate_verification_toolchain.py

@@ -1,304 +0,0 @@
-"""Windows activation-script guards for the local verification toolchain."""
-
-from __future__ import annotations
-
-import json
-import base64
-import re
-import shutil
-import os
-import subprocess
-import tempfile
-import unittest
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[2]
-ACTIVATION_SCRIPT = ROOT / "tools" / "activate_verification_toolchain.ps1"
-AGENT_INSTRUCTIONS = ROOT / "AGENTS.md"
-POWERSHELL = shutil.which("powershell.exe")
-CMD = shutil.which("cmd.exe")
-CMD_SHIM = ROOT / "tools" / "toolchain_shims" / "verilator.cmd"
-
-
-def ps_literal(path: Path) -> str:
-    return "'" + str(path).replace("'", "''") + "'"
-
-
-def run_powershell(command: str) -> subprocess.CompletedProcess[str]:
-    if POWERSHELL is None:
-        raise unittest.SkipTest("Windows PowerShell is unavailable")
-    return subprocess.run(
-        [POWERSHELL, "-NoProfile", "-NonInteractive", "-Command", command],
-        cwd=ROOT,
-        text=True,
-        capture_output=True,
-        check=False,
-        timeout=60,
-    )
-
-
-def last_json_line(stdout: str) -> dict[str, object]:
-    for line in reversed(stdout.splitlines()):
-        if line.strip().startswith("{"):
-            return json.loads(line)
-    raise AssertionError(f"PowerShell output did not contain JSON:\n{stdout}")
-
-
-class ActivateVerificationToolchainTests(unittest.TestCase):
-    def test_repository_instructions_require_a_native_verilator_entrypoint(self) -> None:
-        instructions = AGENT_INSTRUCTIONS.read_text(encoding="utf-8")
-
-        self.assertIn("tools/activate_verification_toolchain.ps1", instructions)
-        self.assertIn("resolver", instructions)
-        self.assertIn("Verilator", instructions)
-        self.assertIn("PATH", instructions)
-
-    def test_verilator_command_is_bound_to_native_windows_binary(self) -> None:
-        source = ACTIVATION_SCRIPT.read_text(encoding="utf-8")
-
-        self.assertIn('"verilator_bin.exe"', source)
-        self.assertIn('"verilator.exe"', source)
-        self.assertIn("$env:VERILATOR = $VerilatorNative", source)
-        self.assertRegex(
-            source,
-            re.compile(
-                r"Set-Alias\s+-Name\s+verilator\s+-Value\s+\$VerilatorNative"
-                r"\s+-Scope\s+Global\s+-Force",
-                re.IGNORECASE,
-            ),
-        )
-
-    def test_repeated_activation_runs_native_verilator_without_file_association(self) -> None:
-        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
-            toolchain = Path(temporary) / "suite"
-            native = toolchain / "bin" / "verilator_bin.exe"
-            native.parent.mkdir(parents=True)
-            command = f"""
-$source = @'
-using System;
-public static class FakeVerilator {{
-    public static int Main(string[] args) {{
-        Console.WriteLine("Fake Verilator 1.0");
-        return 0;
-    }}
-}}
-'@
-Add-Type -TypeDefinition $source -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication
-& {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)}
-& {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)}
-$resolved = Get-Command verilator -ErrorAction Stop
-verilator --version
-$versionExit = $LASTEXITCODE
-[pscustomobject]@{{
-    command_type = [string]$resolved.CommandType
-    definition = [string]$resolved.Definition
-    env_verilator = [string]$env:VERILATOR
-    version_exit = $versionExit
-}} | ConvertTo-Json -Compress
-"""
-            completed = run_powershell(command)
-
-        self.assertEqual(completed.returncode, 0, completed.stderr)
-        payload = last_json_line(completed.stdout)
-        self.assertEqual(payload["command_type"], "Alias")
-        self.assertEqual(Path(str(payload["definition"])).resolve(), native.resolve())
-        self.assertEqual(Path(str(payload["env_verilator"])).resolve(), native.resolve())
-        self.assertEqual(payload["version_exit"], 0)
-        self.assertIn("Fake Verilator 1.0", completed.stdout)
-
-    def test_child_powershell_never_resolves_extensionless_verilator_wrapper(self) -> None:
-        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
-            toolchain = Path(temporary) / "suite"
-            native = toolchain / "bin" / "verilator_bin.exe"
-            wrapper = toolchain / "bin" / "verilator"
-            child_script = Path(temporary) / "child-verilator-check.ps1"
-            native.parent.mkdir(parents=True)
-            wrapper.write_text("#!/usr/bin/env perl\n", encoding="ascii")
-            child_script.write_text(
-                """$ErrorActionPreference = "Stop"
-$resolved = Get-Command verilator -ErrorAction Stop
-if ([System.IO.Path]::GetFullPath($resolved.Definition) -eq
-        [System.IO.Path]::GetFullPath($env:EXPECTED_UNSAFE_VERILATOR)) {
-    Write-Error "child PowerShell resolved the extensionless Verilator wrapper"
-    exit 91
-}
-verilator --version
-exit $LASTEXITCODE
-""",
-                encoding="utf-8-sig",
-            )
-            command = f"""
-$ErrorActionPreference = "Stop"
-$source = @'
-using System;
-public static class FakeVerilator {{
-    public static int Main(string[] args) {{
-        Console.WriteLine("Fake Verilator 1.0");
-        return 0;
-    }}
-}}
-'@
-Add-Type -TypeDefinition $source -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication
-& {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)}
-$env:EXPECTED_UNSAFE_VERILATOR = {ps_literal(wrapper)}
-& (Join-Path $PSHOME "powershell.exe") -NoProfile -NonInteractive -File {ps_literal(child_script)}
-exit $LASTEXITCODE
-"""
-            completed = run_powershell(command)
-
-        self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
-        self.assertIn("Fake Verilator 1.0", completed.stdout)
-
-    def test_child_powershell_preserves_verilator_metacharacters_and_exit_code(self) -> None:
-        arguments = [
-            "--lint-only",
-            r"C:\space dir\file.v",
-            "D=100%",
-            "bang!name",
-            "caret^name",
-            "paren(name)",
-            "amp&name",
-        ]
-        expected = [
-            base64.b64encode(argument.encode("utf-8")).decode("ascii")
-            for argument in arguments
-        ]
-        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
-            toolchain = Path(temporary) / "suite"
-            native = toolchain / "bin" / "verilator_bin.exe"
-            native.parent.mkdir(parents=True)
-            child_script = Path(temporary) / "child-verilator-argv.ps1"
-            child_script.write_text(
-                r"""verilator '--lint-only' 'C:\space dir\file.v' 'D=100%' 'bang!name' 'caret^name' 'paren(name)' 'amp&name'
-exit $LASTEXITCODE
-""",
-                encoding="utf-8-sig",
-            )
-            command = f"""
-$ErrorActionPreference = "Stop"
-$source = @'
-using System;
-using System.Text;
-public static class FakeVerilator {{
-    public static int Main(string[] args) {{
-        foreach (string argument in args) {{
-            Console.WriteLine(Convert.ToBase64String(Encoding.UTF8.GetBytes(argument)));
-        }}
-        return 37;
-    }}
-}}
-'@
-Add-Type -TypeDefinition $source -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication
-& {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)}
-& (Join-Path $PSHOME "powershell.exe") -NoProfile -NonInteractive -File {ps_literal(child_script)}
-exit $LASTEXITCODE
-"""
-            completed = run_powershell(command)
-
-        self.assertEqual(completed.returncode, 37, completed.stdout + completed.stderr)
-        observed = [line.strip() for line in completed.stdout.splitlines() if line.strip() in expected]
-        self.assertEqual(observed, expected)
-
-    def test_child_powershell_rejects_verilator_target_outside_toolchain_root(self) -> None:
-        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
-            root = Path(temporary)
-            toolchain = root / "suite"
-            native = toolchain / "bin" / "verilator_bin.exe"
-            attacker = root / "attacker" / "verilator_bin.exe"
-            native.parent.mkdir(parents=True)
-            attacker.parent.mkdir(parents=True)
-            child_script = root / "child-verilator-target.ps1"
-            child_script.write_text(
-                """$env:VERILATOR = $env:UNTRUSTED_VERILATOR
-verilator --version
-exit $LASTEXITCODE
-""",
-                encoding="utf-8-sig",
-            )
-            command = f"""
-$ErrorActionPreference = "Stop"
-$safeSource = @'
-using System;
-public static class SafeVerilator {{
-    public static int Main(string[] args) {{ return 0; }}
-}}
-'@
-$attackerSource = @'
-using System;
-public static class AttackerVerilator {{
-    public static int Main(string[] args) {{
-        Console.WriteLine("UNTRUSTED_VERILATOR_EXECUTED");
-        return 0;
-    }}
-}}
-'@
-Add-Type -TypeDefinition $safeSource -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication
-Add-Type -TypeDefinition $attackerSource -OutputAssembly {ps_literal(attacker)} -OutputType ConsoleApplication
-& {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)}
-$env:UNTRUSTED_VERILATOR = {ps_literal(attacker)}
-& (Join-Path $PSHOME "powershell.exe") -NoProfile -NonInteractive -File {ps_literal(child_script)}
-exit $LASTEXITCODE
-"""
-            completed = run_powershell(command)
-
-        self.assertNotEqual(completed.returncode, 0, completed.stdout + completed.stderr)
-        self.assertNotIn("UNTRUSTED_VERILATOR_EXECUTED", completed.stdout)
-
-    def test_extensionless_only_toolchain_fails_before_path_or_command_exposure(self) -> None:
-        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
-            toolchain = Path(temporary) / "suite"
-            wrapper = toolchain / "bin" / "verilator"
-            wrapper.parent.mkdir(parents=True)
-            wrapper.write_text("extensionless Perl wrapper", encoding="ascii")
-            command = f"""
-$system32 = Join-Path $env:SystemRoot "System32"
-$env:PATH = "$system32;$env:SystemRoot"
-Remove-Item Env:VERILATOR -ErrorAction SilentlyContinue
-$beforePath = $env:PATH
-$caught = $null
-try {{
-    & {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)}
-}} catch {{
-    $caught = $_.Exception.Message
-}}
-$resolved = Get-Command verilator -ErrorAction SilentlyContinue
-[pscustomobject]@{{
-    caught = [string]$caught
-    path_unchanged = ($env:PATH -ceq $beforePath)
-    command_found = ($null -ne $resolved)
-    env_verilator = [string]$env:VERILATOR
-}} | ConvertTo-Json -Compress
-"""
-            completed = run_powershell(command)
-
-        self.assertEqual(completed.returncode, 0, completed.stderr)
-        payload = last_json_line(completed.stdout)
-        self.assertIn("native Verilator", str(payload["caught"]))
-        self.assertTrue(payload["path_unchanged"])
-        self.assertFalse(payload["command_found"])
-        self.assertEqual(payload["env_verilator"], "")
-
-    def test_cmd_verilator_shim_is_fail_closed_and_never_forwards_arguments(self) -> None:
-        source = CMD_SHIM.read_text(encoding="ascii")
-        self.assertNotIn("%*", source)
-        if CMD is None:
-            raise unittest.SkipTest("cmd.exe is unavailable")
-        env = os.environ.copy()
-        env["PATH"] = os.pathsep.join((str(CMD_SHIM.parent), env.get("PATH", "")))
-        completed = subprocess.run(
-            [CMD, "/d", "/s", "/c", "verilator --version"],
-            cwd=ROOT,
-            env=env,
-            text=True,
-            capture_output=True,
-            check=False,
-            timeout=30,
-        )
-
-        self.assertEqual(completed.returncode, 126, completed.stdout + completed.stderr)
-        self.assertIn("supported only from PowerShell", completed.stderr)
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 294
tests/unit/test_prod2u_p4_cli_v3.py

@@ -1,294 +0,0 @@
-#!/usr/bin/env python3
-"""Host CLI tests for the minimal ACK-only Normal-v3 image."""
-
-from __future__ import annotations
-
-import subprocess
-import sys
-import unittest
-from argparse import Namespace
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(ROOT / "tools"))
-
-import prod2u_p4_cli as cli  # noqa: E402
-import prod2u_p4_protocol as protocol  # noqa: E402
-
-
-class FakeSerial:
-    def __init__(self, response: bytes = b"") -> None:
-        self.response = bytearray(response)
-        self.writes: list[bytes] = []
-        self.is_open = False
-        self.open_count = 0
-        self.close_count = 0
-        self.dtr = None
-        self.rts = None
-
-    def open(self) -> None:
-        self.is_open = True
-        self.open_count += 1
-
-    def close(self) -> None:
-        self.is_open = False
-        self.close_count += 1
-
-    def write(self, data: bytes) -> int:
-        self.writes.append(bytes(data))
-        return len(data)
-
-    def read(self, size: int = 1) -> bytes:
-        if not self.writes or not self.response:
-            return b""
-        take = min(size, len(self.response))
-        result = bytes(self.response[:take])
-        del self.response[:take]
-        return result
-
-
-class FakeClock:
-    def __init__(self) -> None:
-        self.value = 0.0
-
-    def monotonic(self) -> float:
-        return self.value
-
-    def sleep(self, duration: float) -> None:
-        self.value += max(duration, 0.001)
-
-
-class Prod2UP4CliV3Tests(unittest.TestCase):
-    def test_open_com5_configures_exact_921600_8n1_without_dtr_or_rts(self) -> None:
-        endpoint = FakeSerial()
-
-        observed = cli.open_com5(lambda: endpoint)
-
-        self.assertIs(observed, endpoint)
-        self.assertEqual(endpoint.port, "COM5")
-        self.assertEqual(endpoint.baudrate, 921600)
-        self.assertEqual(endpoint.bytesize, 8)
-        self.assertEqual(endpoint.parity, "N")
-        self.assertEqual(endpoint.stopbits, 1)
-        self.assertFalse(endpoint.dtr)
-        self.assertFalse(endpoint.rts)
-        self.assertEqual(endpoint.open_count, 1)
-
-    def test_parser_exposes_only_current_wire_operations(self) -> None:
-        parser = cli.build_parser()
-        subcommands = set(parser._subparsers._group_actions[0].choices)
-
-        self.assertEqual(
-            subcommands,
-            {
-                "selftest",
-                "preflight",
-                "set-all-outputs",
-                "jog",
-                "get-status",
-                "motor-status",
-                "disable",
-            },
-        )
-        for retired in (
-            "mark-closed",
-            "read-temperatures",
-            "normal-actuator-trace-gate",
-            "normal-actuator-temp-gate",
-        ):
-            self.assertNotIn(retired, subcommands)
-
-    def test_cli_restricts_jog_to_physical_xy_while_wire_keeps_reserved_z(self) -> None:
-        parser = cli.build_parser()
-        with self.assertRaises(SystemExit):
-            parser.parse_args(
-                ["jog", "--axis", "2", "--raw-dir", "0", "--speed-code", "3", "--steps", "1"]
-            )
-
-        reserved_z = protocol.build_motor_jog(
-            axis=2,
-            raw_dir=0,
-            speed_code=3,
-            steps=1,
-        )
-        self.assertEqual(
-            protocol.decode_motion_command(protocol.decode_frame(reserved_z)).axis,
-            2,
-        )
-
-    def test_selftest_is_offline_and_names_commit_versioned_profile(self) -> None:
-        payload = cli._selftest()
-
-        self.assertEqual(payload["status"], "pass")
-        self.assertEqual(payload["profile"], "prod2u-p4-normal-actuator-binary921-v3")
-        self.assertEqual(payload["jog_request_steps_max"], 65535)
-        self.assertEqual(payload["jog_executed_steps"], "requested_u16_without_cap")
-        self.assertEqual(payload["jog_effective_step_rate_hz"], 1000)
-        self.assertEqual(payload["jog_ack_semantics"], "FIRST_STEP_EMITTED")
-        self.assertFalse(payload["hardware_opened"])
-        self.assertFalse(payload["program_sram_attempted"])
-
-    def test_preflight_only_consumes_enumeration_and_never_opens_hardware(self) -> None:
-        payload = cli.run_preflight(
-            enumerator=lambda: {
-                "status": "pass",
-                "opened_com": False,
-                "opened_jtag": False,
-                "dtr_rts_toggled": False,
-                "serial_ports": [{"name": "USB Serial (COM5)", "device_id": "COM5"}],
-                "pnp_devices": [{"name": "AL-Link", "device_id": "USB\\VID_1234"}],
-            }
-        )
-
-        self.assertEqual(payload["status"], "pass")
-        self.assertFalse(payload["hardware_opened"])
-        self.assertFalse(payload["serial"]["opened"])
-        self.assertFalse(payload["jtag"]["opened"])
-        self.assertFalse(payload["program_sram_attempted"])
-
-    def test_ordinary_command_accepts_one_ack_and_has_no_trace_policy(self) -> None:
-        request = protocol.build_host_command(command=protocol.CommandId.GET_STATUS)
-        ack = protocol.build_host_ack(
-            ok=True,
-            command=protocol.CommandId.GET_STATUS,
-            status=protocol.StatusCode.OK,
-            state_hash16=0x1234,
-        )
-        endpoint = FakeSerial(ack)
-        session = cli.NormalSession(endpoint, timeout_seconds=0.05)
-
-        result = session.command(request, expected_command=protocol.CommandId.GET_STATUS)
-
-        self.assertEqual(result.raw_response, ack)
-        self.assertEqual([frame.frame_type for frame in result.frames], [protocol.FrameType.HOST_ACK])
-        self.assertEqual(endpoint.writes, [request])
-        self.assertFalse(hasattr(session, "_trace_policy"))
-        self.assertFalse(hasattr(result, "command_result_trace"))
-
-    def test_motor_status_requires_ack_then_motion_status(self) -> None:
-        ack = protocol.build_host_ack(
-            ok=True,
-            command=protocol.MotionOpcode.GET_MOTOR_STATUS,
-            status=protocol.StatusCode.OK,
-            response_type=protocol.FrameType.MOTION_STATUS,
-            result_flags=0x08,
-        )
-        status = protocol.build_motion_status(
-            flags=0x02,
-            position_valid_mask=0,
-            busy_mask=0,
-            current_xyz=(0xFF, 0xFF, 0xFF),
-            target_xyz=(0xFF, 0xFF, 0xFF),
-            fault_mask=0,
-        )
-        endpoint = FakeSerial(ack + status)
-
-        result = cli.NormalSession(endpoint, timeout_seconds=0.05).motor_status()
-
-        self.assertEqual(result.raw_response, ack + status)
-        self.assertEqual(result.status.current_xyz, (0xFF, 0xFF, 0xFF))
-        self.assertEqual(endpoint.writes, [protocol.build_get_motor_status()])
-
-    def test_unexpected_first_frame_sends_one_disable_and_terminates(self) -> None:
-        request = protocol.build_host_command(command=protocol.CommandId.GET_STATUS)
-        unexpected = protocol.build_motion_status(
-            flags=0x02,
-            position_valid_mask=0,
-            busy_mask=0,
-            current_xyz=(0xFF, 0xFF, 0xFF),
-            target_xyz=(0xFF, 0xFF, 0xFF),
-            fault_mask=0,
-        )
-        endpoint = FakeSerial(unexpected)
-        session = cli.NormalSession(endpoint, timeout_seconds=0.05)
-
-        with self.assertRaisesRegex(RuntimeError, "first response must be HOST_ACK"):
-            session.command(request, expected_command=protocol.CommandId.GET_STATUS)
-
-        self.assertEqual(
-            endpoint.writes,
-            [request, protocol.build_host_command(command=protocol.CommandId.DISABLE)],
-        )
-        self.assertTrue(session.disable_attempted)
-        with self.assertRaisesRegex(RuntimeError, "terminated"):
-            session.command(request, expected_command=protocol.CommandId.GET_STATUS)
-
-    def test_timeout_sends_exactly_one_disable_without_retrying_request(self) -> None:
-        clock = FakeClock()
-        endpoint = FakeSerial()
-        session = cli.NormalSession(
-            endpoint,
-            timeout_seconds=0.005,
-            monotonic=clock.monotonic,
-            sleep=clock.sleep,
-        )
-        request = protocol.build_host_command(command=protocol.CommandId.GET_STATUS)
-
-        with self.assertRaisesRegex(TimeoutError, "ACK timeout"):
-            session.command(request, expected_command=protocol.CommandId.GET_STATUS)
-
-        self.assertEqual(endpoint.writes.count(request), 1)
-        self.assertEqual(
-            endpoint.writes.count(protocol.build_host_command(command=protocol.CommandId.DISABLE)),
-            1,
-        )
-
-    def test_live_jog_requires_ok_for_force_motion_contract(self) -> None:
-        request = protocol.build_motor_jog(axis=0, raw_dir=1, speed_code=3, steps=10)
-        ack = protocol.build_host_ack(
-            ok=False,
-            command=protocol.MotionOpcode.JOG,
-            status=protocol.StatusCode.BUSY,
-        )
-        endpoint = FakeSerial(ack)
-
-        with self.assertRaisesRegex(RuntimeError, "unexpected ACK status"):
-            cli._live_request(
-                Namespace(
-                    command="jog",
-                    axis=0,
-                    raw_dir=1,
-                    speed_code=3,
-                    steps=10,
-                ),
-                endpoint,
-            )
-
-        self.assertEqual(
-            endpoint.writes,
-            [request, protocol.build_host_command(command=protocol.CommandId.DISABLE)],
-        )
-
-    def test_trailing_frame_after_ack_sends_one_disable_and_terminates(self) -> None:
-        request = protocol.build_host_command(command=protocol.CommandId.GET_STATUS)
-        ack = protocol.build_host_ack(
-            ok=True,
-            command=protocol.CommandId.GET_STATUS,
-            status=protocol.StatusCode.OK,
-        )
-        endpoint = FakeSerial(ack + ack)
-        session = cli.NormalSession(endpoint, timeout_seconds=0.05)
-
-        with self.assertRaisesRegex(RuntimeError, "unexpected bytes after completed response"):
-            session.command(request, expected_command=protocol.CommandId.GET_STATUS)
-
-        self.assertEqual(
-            endpoint.writes,
-            [request, protocol.build_host_command(command=protocol.CommandId.DISABLE)],
-        )
-        self.assertTrue(session.disable_attempted)
-
-    def test_enumerator_failure_is_bounded_and_read_only(self) -> None:
-        def runner(*_args, **_kwargs):
-            return subprocess.CompletedProcess([], 1, stdout="", stderr="failed")
-
-        payload = cli.enumerate_hardware_candidates(runner=runner)
-
-        self.assertEqual(payload["status"], "blocked_hardware_enumeration_failed")
-        self.assertFalse(payload["opened_com"])
-        self.assertFalse(payload["opened_jtag"])
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 393
tests/unit/test_prod2u_p4_fast_jog_contract.py

@@ -1,393 +0,0 @@
-#!/usr/bin/env python3
-"""RED contracts for the trusted-host JOG fast path."""
-
-from __future__ import annotations
-
-import inspect
-import json
-import re
-import sys
-from pathlib import Path
-
-import pytest
-
-
-ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(ROOT / "tools"))
-
-import prod2u_p4_normal_v3_model as model  # noqa: E402
-import prod2u_p4_protocol as protocol  # noqa: E402
-
-
-RAW_STEP_POLICY = "RAW_U16_TRUSTED_HOST_NO_CPLD_CAP"
-FAST_PATH_POLICY = "RX_FAST_JOG_BYPASSES_NORMAL_REQUEST_SLOT"
-SAME_AXIS_HOST_RULE = "HOST_MUST_NOT_REPEAT_SAME_AXIS_BEFORE_COMPLETION"
-SAME_AXIS_VIOLATION_POLICY = "LATEST_COMMAND_WINS_OLD_ACK_NOT_GUARANTEED"
-COMPLETION_POLICY = "NONE_HOST_TRACKS_TIME"
-PARALLEL_POLICY = "TWO_INDEPENDENT_PARALLEL_EXECUTORS"
-
-HOST_CONTRACT_PATH = ROOT / "config" / "prod2u_p4_normal_host_contract_v4.json"
-HOST_SCHEMA_PATH = ROOT / "schemas" / "prod2u_p4_normal_host_contract_v4.schema.json"
-HW_BINDING_PATH = ROOT / "config" / "prod2u_p4_normal_v3_hw_binding.json"
-RESOURCE_BASELINE_PATH = ROOT / "config" / "prod2u_p4_normal_v3_resource_baseline.json"
-RX_PATH = ROOT / "src" / "rtl" / "prod2u_p4_normal_v3_rx.v"
-CORE_PATH = ROOT / "src" / "rtl" / "prod2u_p4_normal_v3_core.v"
-TOP_PATH = ROOT / "src" / "top" / "prod2u_p4_normal_v3_top.v"
-AXIS_PATH = ROOT / "src" / "rtl" / "prod2u_p4_axis_executor.v"
-HUB_PATH = ROOT / "src" / "rtl" / "prod2u_p4_motor_hub.v"
-AXIS_FORMAL_PATH = ROOT / "tests" / "formal" / "prod2u_p4_axis_safety_formal.v"
-FAST_FORMAL_PATH = ROOT / "tests" / "formal" / "prod2u_p4_fast_jog_path_formal.v"
-FAST_SBY_PATH = ROOT / "tests" / "formal" / "prod2u_p4_fast_jog_path.sby"
-RX_PAYLOAD_FORMAL_PATH = (
-    ROOT / "tests" / "formal" / "prod2u_p4_normal_v3_rx_payload_formal.v"
-)
-TARGET_MANIFEST_PATH = ROOT / "config" / "prod2u_p4_verification_targets_v1.json"
-RUNBOOK_PATH = ROOT / "docs" / "prod2u-p4-normal-v3-runbook.zh-CN.md"
-SEND_HEX_PATH = ROOT / "tools" / "package_templates" / "SEND_HEX.ps1"
-INITIALIZE_PATH = ROOT / "tools" / "package_templates" / "INITIALIZE_DISABLE.ps1"
-
-
-def _json(path: Path) -> dict[str, object]:
-    return json.loads(path.read_text(encoding="utf-8-sig"))
-
-
-def _text(path: Path) -> str:
-    return path.read_text(encoding="utf-8-sig")
-
-
-def _compact_verilog(value: str) -> str:
-    without_line_comments = re.sub(r"//.*", "", value)
-    return re.sub(r"\s+", "", without_line_comments)
-
-
-@pytest.mark.parametrize("steps", (0, 65536))
-def test_host_builder_rejects_values_outside_nonzero_u16(steps: int) -> None:
-    with pytest.raises(ValueError, match="steps must be from 1 to 65535"):
-        protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=0, steps=steps)
-
-
-@pytest.mark.parametrize("steps", (1, 799, 800, 801, 8191, 65535))
-def test_host_builder_preserves_every_valid_u16_step_value(steps: int) -> None:
-    wire = protocol.build_motor_jog(
-        axis=1,
-        raw_dir=1,
-        speed_code=3,
-        steps=steps,
-    )
-    frame = protocol.decode_frame(wire)
-    command = protocol.decode_motion_command(frame)
-
-    assert frame.payload[4:6] == steps.to_bytes(2, "little")
-    assert command.steps == steps
-
-
-def test_host_contract_declares_trusted_fast_jog_and_host_owned_completion() -> None:
-    contract = _json(HOST_CONTRACT_PATH)
-    jog = contract["commands"]["jog"]
-    motion = contract["motion"]
-
-    assert jog.get("step_field_policy") == RAW_STEP_POLICY
-    assert jog.get("fast_path_policy") == FAST_PATH_POLICY
-    assert jog.get("same_axis_host_rule") == SAME_AXIS_HOST_RULE
-    assert jog.get("same_axis_violation_policy") == SAME_AXIS_VIOLATION_POLICY
-    assert jog.get("completion_event") == COMPLETION_POLICY
-    assert jog["step_range"] == [1, 65535]
-    assert jog["executed_step_cap"] is None
-    assert jog["ack_semantics"] == "FIRST_STEP_EMITTED"
-    assert jog["rejects_busy"] is False
-    assert jog["limit_policy"] == "IGNORE_ALL_INPUTS"
-    assert motion["execution"] == PARALLEL_POLICY
-    assert motion["peer_axis_may_start"] is True
-
-
-def test_host_schema_enforces_the_new_fast_jog_policy_markers() -> None:
-    schema = _json(HOST_SCHEMA_PATH)
-    jog = schema["$defs"]["jogCommand"]
-    required = set(jog["required"])
-    properties = jog["properties"]
-    expected = {
-        "step_field_policy": RAW_STEP_POLICY,
-        "fast_path_policy": FAST_PATH_POLICY,
-        "same_axis_host_rule": SAME_AXIS_HOST_RULE,
-        "same_axis_violation_policy": SAME_AXIS_VIOLATION_POLICY,
-        "completion_event": COMPLETION_POLICY,
-    }
-
-    assert expected.keys() <= required
-    for name, value in expected.items():
-        assert properties[name]["const"] == value
-
-
-def test_hardware_binding_mirrors_the_trusted_host_fast_jog_contract() -> None:
-    motor = _json(HW_BINDING_PATH)["motor"]
-
-    assert motor.get("jog_step_field_policy") == RAW_STEP_POLICY
-    assert motor.get("jog_fast_path_policy") == FAST_PATH_POLICY
-    assert motor.get("same_axis_host_rule") == SAME_AXIS_HOST_RULE
-    assert motor.get("same_axis_violation_policy") == SAME_AXIS_VIOLATION_POLICY
-    assert motor.get("completion_event") == COMPLETION_POLICY
-    assert motor["jog_executed_step_cap"] is None
-    assert motor["ack_semantics"] == "FIRST_STEP_EMITTED"
-    assert motor["valid_xy_jog_busy_rejection_sources"] == []
-    assert motor["limit_logic_consumer"] == "none"
-
-
-def test_resource_remeasurement_metadata_names_the_selected_temperature_variant() -> None:
-    baseline = _json(RESOURCE_BASELINE_PATH)
-    measurement = baseline["measurement"]
-
-    assert measurement["candidate_contract"] == RAW_STEP_POLICY
-    assert measurement["reason"] == "remeasure_after_on_demand_temperature_b1"
-    assert measurement["temperature_resource_variant"] == "B1_COMPACT_BYTE_CRC"
-    assert measurement["advisory_estimate_provenance"] == (
-        "single_clean_resource_candidate_pending_required_second_build"
-    )
-    assert measurement["advisory_estimate"] == {
-        "lut": [2234, 2234],
-        "ff": [1810, 1810],
-        "packed_slices": [1237, 1237],
-    }
-    assert baseline["architecture"]["bram9k"] == 1
-    assert "800" not in (
-        str(measurement["candidate_contract"]) + str(measurement["reason"])
-    )
-
-
-def test_model_publishes_policy_markers_and_keeps_xy_execution_independent() -> None:
-    source = inspect.getsource(model)
-    for marker in (
-        RAW_STEP_POLICY,
-        FAST_PATH_POLICY,
-        SAME_AXIS_HOST_RULE,
-        SAME_AXIS_VIOLATION_POLICY,
-        COMPLETION_POLICY,
-        PARALLEL_POLICY,
-    ):
-        assert marker in source
-
-    subject = model.NormalV3Model()
-    x_result = subject.apply_frame(
-        protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=0, steps=801)
-    )
-    y_result = subject.apply_frame(
-        protocol.build_motor_jog(axis=1, raw_dir=1, speed_code=3, steps=65535)
-    )
-
-    assert x_result.accepted and y_result.accepted
-    assert subject.active_mask == 0x03
-    assert subject.busy_mask == 0
-    assert subject.axes[0].remaining_steps == 801
-    assert subject.axes[1].remaining_steps == 65535
-
-
-def test_rx_exports_the_dedicated_fast_jog_event() -> None:
-    source = _text(RX_PATH)
-    for signal in (
-        "fast_jog_valid",
-        "fast_jog_axis",
-        "fast_jog_dir",
-        "fast_jog_steps",
-    ):
-        assert re.search(
-            rf"output\s+(?:wire|reg)\s+(?:\[[^\]]+\]\s+)?{signal}\b",
-            source,
-        ), signal
-
-
-def test_rx_keeps_parsing_while_the_normal_request_slot_is_pending() -> None:
-    source = _text(RX_PATH)
-    ready_assignment = re.search(r"assign\s+rx_ready\s*=\s*([^;]+);", source)
-
-    assert ready_assignment is not None
-    ready_rhs = ready_assignment.group(1)
-    assert "request_valid" not in ready_rhs
-    assert "request_ready" not in ready_rhs
-
-
-def test_rx_fast_classifier_checks_fields_but_never_checks_the_step_value() -> None:
-    source = _text(RX_PATH)
-    compact = _compact_verilog(source)
-    required_checks = (
-        "candidate_type==MOTION_CMD",
-        "candidate_length==6'd8",
-        "candidate_payload[7:0]==MOTION_JOG",
-        "candidate_payload[15:8]<=8'd1",
-        "candidate_payload[23:16]<=8'd1",
-        "candidate_payload[31:24]<=8'd3",
-        "candidate_payload[63:48]==16'd0",
-        "fast_jog_steps<=candidate_payload[47:32]",
-    )
-
-    for expected in required_checks:
-        assert expected in compact
-    assert not re.search(
-        r"candidate_payload\s*\[\s*47\s*:\s*32\s*\]\s*(?:==|!=|<=|>=|<|>)",
-        source,
-    )
-
-
-def test_core_consumes_fast_jog_without_legacy_request_admission_state() -> None:
-    source = _text(CORE_PATH)
-    for signal in (
-        "fast_jog_valid",
-        "fast_jog_axis",
-        "fast_jog_dir",
-        "fast_jog_steps",
-    ):
-        assert re.search(
-            rf"input\s+wire\s+(?:\[[^\]]+\]\s+)?{signal}\b",
-            source,
-        ), signal
-
-    assert "fast_jog_ack_pending" in source
-    assert "ST_JOG_WAIT_START" not in source
-    assert "jog_payload_valid" not in source
-    assert "request_steps" not in source
-
-
-def test_top_routes_the_fast_jog_event_from_rx_to_core() -> None:
-    source = _text(TOP_PATH)
-    for signal in (
-        "fast_jog_valid",
-        "fast_jog_axis",
-        "fast_jog_dir",
-        "fast_jog_steps",
-    ):
-        assert re.search(rf"wire\s+(?:\[[^\]]+\]\s+)?{signal}\b", source)
-        assert source.count(f".{signal}({signal})") == 2
-
-
-def test_motor_rtl_has_no_cap_busy_limit_or_completion_ack_regression() -> None:
-    sources = {
-        path.name: _text(path)
-        for path in (AXIS_PATH, HUB_PATH, CORE_PATH, RX_PATH)
-    }
-    combined = "\n".join(sources.values())
-
-    assert not re.search(r"\b16\s*'d800\b", combined, re.IGNORECASE)
-    assert "STATUS_BUSY" not in combined
-    for forbidden in (
-        "x_limit",
-        "y_limit",
-        "limit_active",
-        "limit_ready",
-        "ST_JOG_WAIT_DONE",
-        "axis_done",
-        "completion_ack",
-    ):
-        assert forbidden not in combined
-
-
-def test_axis_formal_strengthens_the_independent_oracle_with_dut_state() -> None:
-    source = _text(AXIS_FORMAL_PATH)
-
-    for signal in (
-        "formal_motion_phase",
-        "formal_phase_counter",
-        "formal_remaining_steps",
-    ):
-        assert f".{signal}(dut_{signal.removeprefix('formal_')})" in source
-
-    for required in (
-        "assert(dut_remaining_steps == spec_steps_left);",
-        "assert(dut_motion_phase == 2'd0);",
-        "assert(dut_motion_phase == 2'd1);",
-        "assert(dut_motion_phase == 2'd2);",
-        "assert(dut_motion_phase == 2'd3);",
-        "assert(dut_phase_counter == (spec_setup_left - 1'b1));",
-        "assert(dut_phase_counter == (spec_high_left - 1'b1));",
-        "assert(dut_phase_counter == (spec_low_left - 1'b1));",
-    ):
-        assert required in source
-
-
-def test_formal_covers_rx_fast_exit_and_nonidle_core_state() -> None:
-    core = _text(CORE_PATH)
-    formal = _text(FAST_FORMAL_PATH)
-    sby = _text(FAST_SBY_PATH)
-    manifest = _json(TARGET_MANIFEST_PATH)
-    target = next(
-        item
-        for item in manifest["layers"]["formal"]
-        if item["name"] == "prod2u_p4_fast_jog_path"
-    )
-
-    assert "formal_state" in core
-    assert "assign formal_state = state;" in core
-    assert "module prod2u_p4_fast_jog_rx_formal;" in formal
-    assert ".formal_state(dut_state)" in formal
-    assert "fast_jog_valid && (dut_state != 3'd0)" in formal
-    assert "cover(saw_nonidle_fast" in formal
-    assert "bmc_rx_path: prep -top prod2u_p4_fast_jog_rx_formal" in sby
-    assert "cover_rx_path: prep -top prod2u_p4_fast_jog_rx_formal" in sby
-    assert target["tasks"] == [
-        "prove_path",
-        "cover_path",
-        "bmc_rx_path",
-        "cover_rx_path",
-        "prove_production_timing",
-    ]
-
-
-def test_rx_payload_formal_uses_an_arbitrary_bit_oracle() -> None:
-    source = _compact_verilog(_text(RX_PAYLOAD_FORMAL_PATH))
-
-    assert "reg[271:0]expected_payload" not in source
-    assert "assert(request_payload==expected_payload);" not in source
-    assert "(*anyconst*)reg[8:0]payload_bit_index;" in source
-    assert "assume(payload_bit_index<9'd272);" in source
-    assert "if(selected_payload_byte<selected_length)" in source
-    assert (
-        "assert(request_payload[payload_bit_index]==expected_payload_bit);"
-        in source
-    )
-    assert "assert(request_payload[payload_bit_index]==1'b0);" in source
-    assert "if(frame_index>=(crc_high_index+7'd1))" in source
-    assert "assert(request_valid||request_seen);" in source
-    assert "crc_high_index+7'd2" not in source
-
-
-def test_docs_define_host_responsibility_without_old_motion_semantics() -> None:
-    for path in (ROOT / "AGENTS.md", RUNBOOK_PATH):
-        source = _text(path)
-        for required in (
-            RAW_STEP_POLICY,
-            FAST_PATH_POLICY,
-            SAME_AXIS_HOST_RULE,
-            SAME_AXIS_VIOLATION_POLICY,
-            COMPLETION_POLICY,
-        ):
-            assert required in source, f"{required} missing from {path.name}"
-
-        lowered = source.casefold()
-        assert "min(steps, 800)" not in lowered
-        assert "ack means completion" not in lowered
-        assert "limit stops jog" not in lowered
-        assert "valid jog returns busy" not in lowered
-
-
-def test_sender_waits_for_start_ack_without_deriving_a_completion_timeout() -> None:
-    source = _text(SEND_HEX_PATH)
-    timeout_function = re.search(
-        r"function\s+Get-ResponseTimeoutMs\b(?P<body>.*?)(?=\r?\nfunction\s+)",
-        source,
-        re.DOTALL,
-    )
-
-    assert timeout_function is not None
-    body = timeout_function.group("body").casefold()
-    assert "steps" not in body
-    assert "1000" not in body
-    assert "3000" in body
-    assert "ordinary command must receive exactly one host_ack" in source.casefold()
-    assert "motion_status" not in body
-
-
-def test_initialize_disable_does_not_claim_to_stop_fast_jog() -> None:
-    source = _text(INITIALIZE_PATH).casefold()
-
-    assert "disable does not stop" in source
-    assert "jog" in source
-    assert "reset" in source
-    assert "power-off" in source
-    assert "reconfiguration" in source

+ 0 - 61
tests/unit/test_prod2u_p4_fast_jog_rx_contract.py

@@ -1,61 +0,0 @@
-#!/usr/bin/env python3
-"""Run the independent RX fast-JOG contract directly with Icarus."""
-
-from __future__ import annotations
-
-import subprocess
-import tempfile
-from pathlib import Path
-
-from tools import prod2u_p4_harness as harness
-
-
-ROOT = Path(__file__).resolve().parents[2]
-TESTBENCH = ROOT / "tests/sim/prod2u_p4_normal_v3_rx_fast_jog_tb.v"
-SOURCES = (
-    ROOT / "src/rtl/binary921_crc16.v",
-    ROOT / "src/rtl/prod2u_p4_normal_v3_rx.v",
-    TESTBENCH,
-)
-
-
-def test_rx_fast_jog_bypasses_held_normal_request_slot() -> None:
-    iverilog = harness.resolve_tool("iverilog")
-    vvp = harness.resolve_tool("vvp")
-    assert iverilog is not None, "Icarus Verilog is required"
-    assert vvp is not None, "vvp is required"
-
-    with tempfile.TemporaryDirectory(prefix="p4-rx-fast-jog-") as temporary:
-        executable = Path(temporary) / "rx_fast_jog.vvp"
-        compile_result = subprocess.run(
-            [
-                str(iverilog),
-                "-g2005-sv",
-                "-s",
-                "prod2u_p4_normal_v3_rx_fast_jog_tb",
-                "-o",
-                str(executable),
-                *(str(path) for path in SOURCES),
-            ],
-            cwd=ROOT,
-            env=harness.tool_env(),
-            capture_output=True,
-            text=True,
-            timeout=60,
-            check=False,
-        )
-        compile_output = compile_result.stdout + compile_result.stderr
-        assert compile_result.returncode == 0, compile_output
-
-        run_result = subprocess.run(
-            [str(vvp), str(executable)],
-            cwd=ROOT,
-            env=harness.tool_env(),
-            capture_output=True,
-            text=True,
-            timeout=60,
-            check=False,
-        )
-        output = run_result.stdout + run_result.stderr
-        assert run_result.returncode == 0, output
-        assert "PASS: prod2u_p4_normal_v3_rx_fast_jog_tb" in output

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


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


+ 0 - 67
tests/unit/test_prod2u_p4_minimal_snapshot_contract_rtl.py

@@ -1,67 +0,0 @@
-#!/usr/bin/env python3
-"""Run the minimal independent-axis snapshot contract directly with Icarus."""
-
-from __future__ import annotations
-
-import subprocess
-import tempfile
-from pathlib import Path
-
-from tools import prod2u_p4_harness as harness
-
-
-ROOT = Path(__file__).resolve().parents[2]
-TESTBENCH = ROOT / "tests/sim/prod2u_p4_minimal_snapshot_contract_tb.v"
-SOURCES = (
-    ROOT / "src/rtl/binary921_crc16.v",
-    ROOT / "src/rtl/prod2u_p4_normal_v3_output_state.v",
-    ROOT / "src/rtl/prod2u_p4_normal_v3_watchdog.v",
-    ROOT / "src/rtl/prod2u_p4_axis_executor.v",
-    ROOT / "src/rtl/prod2u_p4_motor_hub.v",
-    ROOT / "src/rtl/prod2u_p4_response_scheduler.v",
-    ROOT / "src/rtl/prod2u_p4_normal_v3_core.v",
-    TESTBENCH,
-)
-
-
-def test_minimal_snapshot_contract_rtl() -> None:
-    iverilog = harness.resolve_tool("iverilog")
-    vvp = harness.resolve_tool("vvp")
-    assert iverilog is not None, "Icarus Verilog is required"
-    assert vvp is not None, "vvp is required"
-
-    with tempfile.TemporaryDirectory(prefix="p4-minimal-snapshot-") as temporary:
-        executable = Path(temporary) / "minimal_snapshot.vvp"
-        compile_result = subprocess.run(
-            [
-                str(iverilog),
-                "-g2005-sv",
-                "-s",
-                "prod2u_p4_minimal_snapshot_contract_tb",
-                "-o",
-                str(executable),
-                *(str(path) for path in SOURCES),
-            ],
-            cwd=ROOT,
-            env=harness.tool_env(),
-            capture_output=True,
-            text=True,
-            timeout=60,
-            check=False,
-        )
-        assert compile_result.returncode == 0, (
-            compile_result.stdout + compile_result.stderr
-        )
-
-        run_result = subprocess.run(
-            [str(vvp), str(executable)],
-            cwd=ROOT,
-            env=harness.tool_env(),
-            capture_output=True,
-            text=True,
-            timeout=60,
-            check=False,
-        )
-        output = run_result.stdout + run_result.stderr
-        assert run_result.returncode == 0, output
-        assert "PASS: prod2u_p4_minimal_snapshot_contract_tb" in output

+ 0 - 655
tests/unit/test_prod2u_p4_motion_source_mutations.py

@@ -1,655 +0,0 @@
-#!/usr/bin/env python3
-"""Kill high-risk motion regressions through real Icarus simulations."""
-
-from __future__ import annotations
-
-import subprocess
-import sys
-import tempfile
-import textwrap
-import time
-import unittest
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Iterable
-
-
-ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(ROOT / "tools"))
-
-import prod2u_p4_harness as harness  # noqa: E402
-
-
-AXIS_SOURCE = ROOT / "src/rtl/prod2u_p4_axis_executor.v"
-HUB_SOURCE = ROOT / "src/rtl/prod2u_p4_motor_hub.v"
-CORE_SOURCE = ROOT / "src/rtl/prod2u_p4_normal_v3_core.v"
-TOP_SOURCE = ROOT / "src/top/prod2u_p4_normal_v3_top.v"
-AXIS_16BIT_TB = ROOT / "tests/sim/prod2u_p4_axis_jog_16bit_tb.v"
-FAST_JOG_CORE_TB = ROOT / "tests/sim/prod2u_p4_fast_jog_core_tb.v"
-TOP_TB = ROOT / "tests/sim/prod2u_p4_normal_v3_top_tb.v"
-
-
-@dataclass(frozen=True)
-class IcarusResult:
-    compile_returncode: int
-    run_returncode: int | None
-    output: str
-    elapsed_seconds: float
-
-
-def _replace_exact(
-    source: str,
-    old: str,
-    new: str,
-    *,
-    label: str,
-    expected_count: int = 1,
-) -> str:
-    actual_count = source.count(old)
-    if actual_count != expected_count:
-        raise AssertionError(
-            f"{label}: expected {expected_count} mutation sites, found {actual_count}"
-        )
-    return source.replace(old, new)
-
-
-def _run_icarus(
-    *,
-    iverilog: Path,
-    vvp: Path,
-    top: str,
-    sources: Iterable[Path],
-    workdir: Path,
-    timeout_seconds: float = 120.0,
-    defines: Iterable[str] = (),
-) -> IcarusResult:
-    executable = workdir / f"{top}.vvp"
-    started = time.perf_counter()
-    compile_result = subprocess.run(
-        [
-            str(iverilog),
-            "-g2005-sv",
-            *(f"-D{define}" for define in defines),
-            "-s",
-            top,
-            "-o",
-            str(executable),
-            *(str(path) for path in sources),
-        ],
-        cwd=workdir,
-        env=harness.tool_env(),
-        capture_output=True,
-        text=True,
-        timeout=timeout_seconds,
-        check=False,
-    )
-    output = compile_result.stdout + compile_result.stderr
-    if compile_result.returncode != 0:
-        return IcarusResult(
-            compile_result.returncode,
-            None,
-            output,
-            time.perf_counter() - started,
-        )
-
-    run_result = subprocess.run(
-        [str(vvp), str(executable)],
-        cwd=workdir,
-        env=harness.tool_env(),
-        capture_output=True,
-        text=True,
-        timeout=timeout_seconds,
-        check=False,
-    )
-    return IcarusResult(
-        compile_result.returncode,
-        run_result.returncode,
-        output + run_result.stdout + run_result.stderr,
-        time.perf_counter() - started,
-    )
-
-
-def _mutate_axis_with_800_step_clamp(source: str) -> str:
-    return _replace_exact(
-        source,
-        "                remaining_steps <= command_steps;",
-        "                remaining_steps <= (command_steps > 16'd800) ? "
-        "16'd800 : command_steps;",
-        label="800-step clamp",
-    )
-
-
-def _mutate_axis_with_speed_tiers(source: str) -> str:
-    source = _replace_exact(
-        source,
-        "    input  wire [15:0] command_steps,\n"
-        "    output wire        step_out,",
-        "    input  wire [15:0] command_steps,\n"
-        "    input  wire [1:0]  command_speed,\n"
-        "    output wire        step_out,",
-        label="axis speed port",
-    )
-    source = _replace_exact(
-        source,
-        "    localparam integer MAX_PHASE_CYCLES =\n"
-        "        (DIR_SETUP_CYCLES > STEP_HALF_CYCLES) ?\n"
-        "        DIR_SETUP_CYCLES : STEP_HALF_CYCLES;",
-        "    localparam integer MAX_STEP_HALF_CYCLES = STEP_HALF_CYCLES * 8;\n"
-        "    localparam integer MAX_PHASE_CYCLES =\n"
-        "        (DIR_SETUP_CYCLES > MAX_STEP_HALF_CYCLES) ?\n"
-        "        DIR_SETUP_CYCLES : MAX_STEP_HALF_CYCLES;",
-        label="axis speed counter width",
-    )
-    source = _replace_exact(
-        source,
-        "    reg dir_reg;\n    reg [15:0] remaining_steps;",
-        "    reg dir_reg;\n"
-        "    reg [1:0] speed_reg;\n"
-        "    reg [15:0] remaining_steps;",
-        label="axis speed register",
-    )
-    source = _replace_exact(
-        source,
-        "    assign step_out = (motion_phase == PHASE_STEP_HIGH);\n"
-        "    assign dir_out = dir_reg;",
-        "    assign step_out = (motion_phase == PHASE_STEP_HIGH);\n"
-        "    assign dir_out = dir_reg;\n"
-        "    wire [PHASE_COUNTER_BITS-1:0] speed_step_half_cycles =\n"
-        "        STEP_HALF_CYCLES << (3 - speed_reg);\n"
-        "    wire [PHASE_COUNTER_BITS-1:0] speed_step_half_last =\n"
-        "        speed_step_half_cycles - 1'b1;",
-        label="axis speed reload",
-    )
-    source = _replace_exact(
-        source,
-        "            dir_reg <= 1'b0;\n"
-        "            remaining_steps <= 16'd0;",
-        "            dir_reg <= 1'b0;\n"
-        "            speed_reg <= 2'd0;\n"
-        "            remaining_steps <= 16'd0;",
-        label="axis speed reset",
-    )
-    source = _replace_exact(
-        source,
-        "                dir_reg <= command_dir;\n"
-        "                remaining_steps <= command_steps;",
-        "                dir_reg <= command_dir;\n"
-        "                speed_reg <= command_speed;\n"
-        "                remaining_steps <= command_steps;",
-        label="axis speed capture",
-    )
-    return _replace_exact(
-        source,
-        "phase_counter <= STEP_HALF_LAST;",
-        "phase_counter <= speed_step_half_last;",
-        label="axis speed phase reloads",
-        expected_count=3,
-    )
-
-
-def _mutate_core_with_request_ready_gate(source: str) -> str:
-    return _replace_exact(
-        source,
-        "        .jog_start(fast_jog_valid),",
-        "        .jog_start(fast_jog_valid && request_ready),",
-        label="fast JOG request_ready gate",
-    )
-
-
-def _mutate_top_with_motor_safety_gates(source: str) -> str:
-    return _replace_exact(
-        source,
-        "    assign x_step = motor_steps[0];\n"
-        "    assign y_step = motor_steps[1];\n"
-        "    assign z_step = motor_steps[2];\n"
-        "    assign x_dir = motor_dirs[0];\n"
-        "    assign y_dir = motor_dirs[1];\n"
-        "    assign z_dir = motor_dirs[2];\n"
-        "    assign motor_en_n = 1'b0;",
-        "    wire motor_gate_open = !disabled && !watchdog_timeout;\n"
-        "    assign x_step = motor_steps[0] && motor_gate_open && !x_limit_raw;\n"
-        "    assign y_step = motor_steps[1] && motor_gate_open && !y_limit_raw;\n"
-        "    assign z_step = motor_steps[2] && motor_gate_open;\n"
-        "    assign x_dir = motor_dirs[0];\n"
-        "    assign y_dir = motor_dirs[1];\n"
-        "    assign z_dir = motor_dirs[2];\n"
-        "    assign motor_en_n = !motor_gate_open;",
-        label="top LS/DISABLE/watchdog/EN safety gate",
-    )
-
-
-def _mutate_top_with_individual_step_gate(
-    source: str,
-    *,
-    gate_expression: str,
-    label: str,
-) -> str:
-    return _replace_exact(
-        source,
-        "    assign x_step = motor_steps[0];",
-        f"    assign x_step = motor_steps[0] && {gate_expression};",
-        label=label,
-    )
-
-
-def _top_individual_gate_tb(
-    *,
-    marker: str,
-    x_limit_raw: int,
-    disabled: int,
-    watchdog_timeout: int,
-) -> str:
-    return textwrap.dedent(
-        f"""
-        `timescale 1ns/1ps
-
-        module prod2u_p4_individual_safety_gate_mutation_tb;
-            reg clk = 1'b0;
-            reg x_limit_raw = 1'b{x_limit_raw};
-            reg y_limit_raw = 1'b0;
-            wire x_step;
-            integer x_rises = 0;
-            integer guard = 0;
-
-            always #5 clk = ~clk;
-            always @(posedge x_step) x_rises = x_rises + 1;
-
-            prod2u_p4_normal_v3_top #(
-                .CLK_HZ(4000000),
-                .HOST_UART_CLKS_PER_BIT(4),
-                .POR_CYCLES(4),
-                .INTER_BYTE_TIMEOUT_MS(2),
-                .PTC_STEP_CLKS(1),
-                .FAN_STEP_CLKS(1),
-                .SOLENOID_ACTIVE_HIGH(1)
-            ) dut (
-                .sys_clk(clk), .host_uart_rx(1'b1), .host_uart_tx(),
-                .ptc_pwm_out(), .fan_pwm_out(), .solenoid_out(),
-                .motor_en_n(), .x_step(x_step), .x_dir(),
-                .y_step(), .y_dir(), .z_step(), .z_dir(),
-                .x_limit_raw(x_limit_raw), .y_limit_raw(y_limit_raw)
-            );
-
-            initial begin
-                wait (dut.sys_rst_n === 1'b1);
-                repeat (4) @(negedge clk);
-                force dut.disabled = 1'b{disabled};
-                force dut.watchdog_timeout = 1'b{watchdog_timeout};
-                force dut.fast_jog_axis = 2'd0;
-                force dut.fast_jog_dir = 1'b1;
-                force dut.fast_jog_steps = 16'd1;
-                force dut.fast_jog_valid = 1'b1;
-                @(negedge clk);
-                force dut.fast_jog_valid = 1'b0;
-                while (x_rises == 0 && guard < 60000) begin
-                    @(negedge clk);
-                    guard = guard + 1;
-                end
-                if (x_rises != 1) $fatal(1, "{marker}");
-                $display("PASS: prod2u_p4_individual_safety_gate_mutation_tb");
-                $finish;
-            end
-        endmodule
-        """
-    ).strip() + "\n"
-
-
-FIXED_SPEED_TB = textwrap.dedent(
-    r"""
-    `timescale 1ns/1ps
-
-    module prod2u_p4_fixed_speed_contract_mutation_tb;
-        reg clk = 1'b0;
-        reg rst_n = 1'b0;
-        reg command_start = 1'b0;
-        reg command_dir = 1'b0;
-        reg [1:0] command_speed = 2'd0;
-        reg [15:0] command_steps = 16'd2;
-        wire step_out;
-        integer cycle_count = 0;
-        integer interval0;
-        integer interval1;
-        integer interval2;
-        integer interval3;
-
-        always #5 clk = ~clk;
-        always @(posedge clk) cycle_count = cycle_count + 1;
-
-        prod2u_p4_axis_executor #(
-            .DIR_SETUP_CYCLES(2),
-            .STEP_HALF_CYCLES(2)
-        ) dut (
-            .clk(clk), .rst_n(rst_n),
-            .command_start(command_start), .command_dir(command_dir),
-            .command_steps(command_steps),
-`ifdef MUTANT_SPEED_PORT
-            .command_speed(command_speed),
-`endif
-            .step_out(step_out), .dir_out(), .started_pulse()
-        );
-
-        task reset_axis;
-            begin
-                rst_n = 1'b0;
-                command_start = 1'b0;
-                command_dir = 1'b0;
-                command_speed = 2'd0;
-                command_steps = 16'd2;
-                repeat (3) @(negedge clk);
-                rst_n = 1'b1;
-                repeat (2) @(negedge clk);
-            end
-        endtask
-
-        task measure_speed;
-            input [1:0] speed_code;
-            output integer interval;
-            integer first_cycle;
-            begin
-                reset_axis();
-                @(negedge clk);
-                command_speed = speed_code;
-                command_steps = 16'd2;
-                command_start = 1'b1;
-                @(negedge clk);
-                command_start = 1'b0;
-
-                @(posedge step_out);
-                first_cycle = cycle_count;
-                @(posedge step_out);
-                interval = cycle_count - first_cycle;
-                if (interval <= 0) $fatal(1, "SPEED_FIXED_RATE_NO_SECOND_STEP");
-            end
-        endtask
-
-        initial begin
-            measure_speed(2'd0, interval0);
-            measure_speed(2'd1, interval1);
-            measure_speed(2'd2, interval2);
-            measure_speed(2'd3, interval3);
-            if ((interval0 != interval1) || (interval0 != interval2) ||
-                (interval0 != interval3)) begin
-                $fatal(1,
-                    "SPEED_FIXED_RATE_FAIL intervals=%0d/%0d/%0d/%0d",
-                    interval0, interval1, interval2, interval3);
-            end
-            $display("PASS: prod2u_p4_fixed_speed_contract_mutation_tb");
-            $finish;
-        end
-    endmodule
-    """
-).strip() + "\n"
-
-
-class MotionSourceMutationTests(unittest.TestCase):
-    @classmethod
-    def setUpClass(cls) -> None:
-        cls.iverilog = harness.resolve_tool("iverilog")
-        cls.vvp = harness.resolve_tool("vvp")
-        if cls.iverilog is None or cls.vvp is None:
-            raise RuntimeError("Icarus Verilog and vvp are required for mutation tests")
-
-    def assert_baseline_passed(self, result: IcarusResult, marker: str) -> None:
-        self.assertEqual(result.compile_returncode, 0, result.output)
-        self.assertEqual(result.run_returncode, 0, result.output)
-        self.assertIn(marker, result.output)
-
-    def assert_mutant_killed(self, result: IcarusResult, marker: str) -> None:
-        self.assertEqual(
-            result.compile_returncode,
-            0,
-            "mutant must elaborate before it can count as killed:\n" + result.output,
-        )
-        self.assertIsNotNone(result.run_returncode, result.output)
-        self.assertNotEqual(result.run_returncode, 0, result.output)
-        self.assertIn(marker, result.output)
-
-    def assert_individual_top_gate_killed(
-        self,
-        *,
-        gate_expression: str,
-        label: str,
-        marker: str,
-        x_limit_raw: int,
-        disabled: int,
-        watchdog_timeout: int,
-    ) -> None:
-        with tempfile.TemporaryDirectory(
-            prefix=f"p4-mutant-{label}-", dir=ROOT.parent
-        ) as temporary:
-            workdir = Path(temporary)
-            testbench = workdir / "prod2u_p4_individual_safety_gate_mutation_tb.v"
-            testbench.write_text(
-                _top_individual_gate_tb(
-                    marker=marker,
-                    x_limit_raw=x_limit_raw,
-                    disabled=disabled,
-                    watchdog_timeout=watchdog_timeout,
-                ),
-                encoding="ascii",
-                newline="\n",
-            )
-            production_sources = tuple(
-                ROOT / relative for relative in harness.active_rtl_sources()
-            )
-            baseline = _run_icarus(
-                iverilog=self.iverilog,
-                vvp=self.vvp,
-                top="prod2u_p4_individual_safety_gate_mutation_tb",
-                sources=(*production_sources, testbench),
-                workdir=workdir,
-            )
-            self.assert_baseline_passed(
-                baseline,
-                "PASS: prod2u_p4_individual_safety_gate_mutation_tb",
-            )
-
-            mutant_top = workdir / f"prod2u_p4_normal_v3_top_{label}.v"
-            mutant_top.write_text(
-                _mutate_top_with_individual_step_gate(
-                    TOP_SOURCE.read_text(encoding="ascii"),
-                    gate_expression=gate_expression,
-                    label=label,
-                ),
-                encoding="ascii",
-                newline="\n",
-            )
-            mutant_sources = tuple(
-                mutant_top if source == TOP_SOURCE else source
-                for source in production_sources
-            )
-            mutant = _run_icarus(
-                iverilog=self.iverilog,
-                vvp=self.vvp,
-                top="prod2u_p4_individual_safety_gate_mutation_tb",
-                sources=(*mutant_sources, testbench),
-                workdir=workdir,
-            )
-            self.assert_mutant_killed(mutant, marker)
-
-    def test_800_step_clamp_is_killed_by_real_16bit_boundary_tb(self) -> None:
-        with tempfile.TemporaryDirectory(
-            prefix="p4-mutant-clamp-", dir=ROOT.parent
-        ) as temporary:
-            workdir = Path(temporary)
-            baseline = _run_icarus(
-                iverilog=self.iverilog,
-                vvp=self.vvp,
-                top="prod2u_p4_axis_jog_16bit_tb",
-                sources=(AXIS_SOURCE, AXIS_16BIT_TB),
-                workdir=workdir,
-            )
-            self.assert_baseline_passed(
-                baseline, "PASS: prod2u_p4_axis_jog_16bit_tb"
-            )
-
-            mutant_axis = workdir / "prod2u_p4_axis_executor_clamped.v"
-            mutant_axis.write_text(
-                _mutate_axis_with_800_step_clamp(
-                    AXIS_SOURCE.read_text(encoding="ascii")
-                ),
-                encoding="ascii",
-                newline="\n",
-            )
-            mutant = _run_icarus(
-                iverilog=self.iverilog,
-                vvp=self.vvp,
-                top="prod2u_p4_axis_jog_16bit_tb",
-                sources=(mutant_axis, AXIS_16BIT_TB),
-                workdir=workdir,
-            )
-            self.assert_mutant_killed(mutant, "16-bit JOG mismatch")
-
-    def test_reintroduced_speed_tiers_are_killed_by_fixed_rate_rtl(self) -> None:
-        with tempfile.TemporaryDirectory(
-            prefix="p4-mutant-speed-", dir=ROOT.parent
-        ) as temporary:
-            workdir = Path(temporary)
-            speed_tb = workdir / "prod2u_p4_fixed_speed_contract_mutation_tb.v"
-            speed_tb.write_text(FIXED_SPEED_TB, encoding="ascii", newline="\n")
-            baseline = _run_icarus(
-                iverilog=self.iverilog,
-                vvp=self.vvp,
-                top="prod2u_p4_fixed_speed_contract_mutation_tb",
-                sources=(AXIS_SOURCE, speed_tb),
-                workdir=workdir,
-            )
-            self.assert_baseline_passed(
-                baseline, "PASS: prod2u_p4_fixed_speed_contract_mutation_tb"
-            )
-
-            mutant_axis = workdir / "prod2u_p4_axis_executor_speed.v"
-            mutant_axis.write_text(
-                _mutate_axis_with_speed_tiers(
-                    AXIS_SOURCE.read_text(encoding="ascii")
-                ),
-                encoding="ascii",
-                newline="\n",
-            )
-            mutant = _run_icarus(
-                iverilog=self.iverilog,
-                vvp=self.vvp,
-                top="prod2u_p4_fixed_speed_contract_mutation_tb",
-                sources=(mutant_axis, speed_tb),
-                workdir=workdir,
-                defines=("MUTANT_SPEED_PORT",),
-            )
-            self.assert_mutant_killed(mutant, "SPEED_FIXED_RATE_FAIL")
-
-    def test_fast_jog_request_ready_gate_is_killed_by_core_bypass_tb(self) -> None:
-        with tempfile.TemporaryDirectory(
-            prefix="p4-mutant-request-ready-", dir=ROOT.parent
-        ) as temporary:
-            workdir = Path(temporary)
-            sources = (
-                ROOT / "src/rtl/binary921_crc16.v",
-                ROOT / "src/rtl/prod2u_p4_normal_v3_output_state.v",
-                ROOT / "src/rtl/prod2u_p4_normal_v3_watchdog.v",
-                AXIS_SOURCE,
-                HUB_SOURCE,
-                ROOT / "src/rtl/prod2u_p4_response_scheduler.v",
-            )
-            baseline = _run_icarus(
-                iverilog=self.iverilog,
-                vvp=self.vvp,
-                top="prod2u_p4_fast_jog_core_tb",
-                sources=(*sources, CORE_SOURCE, FAST_JOG_CORE_TB),
-                workdir=workdir,
-            )
-            self.assert_baseline_passed(
-                baseline, "PASS: prod2u_p4_fast_jog_core_tb"
-            )
-
-            mutant_core = workdir / "prod2u_p4_normal_v3_core_request_ready.v"
-            mutant_core.write_text(
-                _mutate_core_with_request_ready_gate(
-                    CORE_SOURCE.read_text(encoding="ascii")
-                ),
-                encoding="ascii",
-                newline="\n",
-            )
-            mutant = _run_icarus(
-                iverilog=self.iverilog,
-                vvp=self.vvp,
-                top="prod2u_p4_fast_jog_core_tb",
-                sources=(*sources, mutant_core, FAST_JOG_CORE_TB),
-                workdir=workdir,
-            )
-            self.assert_mutant_killed(
-                mutant,
-                "fast X JOG did not finish while the old response was stalled",
-            )
-
-    def test_top_motor_safety_gates_are_killed_by_real_uart_top_tb(self) -> None:
-        with tempfile.TemporaryDirectory(
-            prefix="p4-mutant-top-gates-", dir=ROOT.parent
-        ) as temporary:
-            workdir = Path(temporary)
-            production_sources = tuple(
-                ROOT / relative for relative in harness.active_rtl_sources()
-            )
-            baseline = _run_icarus(
-                iverilog=self.iverilog,
-                vvp=self.vvp,
-                top="prod2u_p4_normal_v3_top_tb",
-                sources=(*production_sources, TOP_TB),
-                workdir=workdir,
-            )
-            self.assert_baseline_passed(
-                baseline, "PASS: prod2u_p4_normal_v3_top_tb"
-            )
-
-            mutant_top = workdir / "prod2u_p4_normal_v3_top_gated.v"
-            mutant_top.write_text(
-                _mutate_top_with_motor_safety_gates(
-                    TOP_SOURCE.read_text(encoding="ascii")
-                ),
-                encoding="ascii",
-                newline="\n",
-            )
-            mutant_sources = tuple(
-                mutant_top if source == TOP_SOURCE else source
-                for source in production_sources
-            )
-            mutant = _run_icarus(
-                iverilog=self.iverilog,
-                vvp=self.vvp,
-                top="prod2u_p4_normal_v3_top_tb",
-                sources=(*mutant_sources, TOP_TB),
-                workdir=workdir,
-            )
-            self.assert_mutant_killed(mutant, "NO_GATES_TOP_FAIL")
-
-    def test_limit_gate_is_independently_killed(self) -> None:
-        self.assert_individual_top_gate_killed(
-            gate_expression="!x_limit_raw",
-            label="limit_gate",
-            marker="LIMIT_GATE_FAIL",
-            x_limit_raw=1,
-            disabled=0,
-            watchdog_timeout=0,
-        )
-
-    def test_disable_gate_is_independently_killed(self) -> None:
-        self.assert_individual_top_gate_killed(
-            gate_expression="!disabled",
-            label="disable_gate",
-            marker="DISABLE_GATE_FAIL",
-            x_limit_raw=0,
-            disabled=1,
-            watchdog_timeout=0,
-        )
-
-    def test_watchdog_gate_is_independently_killed(self) -> None:
-        self.assert_individual_top_gate_killed(
-            gate_expression="!watchdog_timeout",
-            label="watchdog_gate",
-            marker="WATCHDOG_GATE_FAIL",
-            x_limit_raw=0,
-            disabled=0,
-            watchdog_timeout=1,
-        )
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 403
tests/unit/test_prod2u_p4_normal_v3_model.py

@@ -1,403 +0,0 @@
-#!/usr/bin/env python3
-"""Independent model tests for the unprotected JOG-only Normal-v3 contract."""
-
-from __future__ import annotations
-
-import inspect
-import sys
-import unittest
-from itertools import product
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(ROOT / "tools"))
-
-import prod2u_p4_normal_v3_model as model  # noqa: E402
-import prod2u_p4_protocol as protocol  # noqa: E402
-
-
-def snapshot(
-    *,
-    ptc: int = 0,
-    fan: int = 30,
-    solenoid: int = 0,
-    xyz: tuple[int, int, int] = (0, 0, 0),
-) -> bytes:
-    wire = bytearray(
-        protocol.build_output_snapshot(
-            ptc_percent=(ptc,) * 24,
-            fan_percent=(fan,) * 4,
-            solenoid=solenoid,
-            xyz=(0, 0, 0),
-        )
-    )
-    wire[45:48] = bytes(xyz)
-    wire[-2:] = protocol.crc16_ccitt(wire[2:-2]).to_bytes(2, "little")
-    return bytes(wire)
-
-
-def zero_step_jog() -> bytes:
-    wire = bytearray(
-        protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=3, steps=1)
-    )
-    wire[18:20] = b"\x00\x00"
-    wire[-2:] = protocol.crc16_ccitt(wire[2:-2]).to_bytes(2, "little")
-    return bytes(wire)
-
-
-def motion_tuple(subject: model.NormalV3Model, axis_index: int) -> tuple[object, ...]:
-    axis = subject.axes[axis_index]
-    return (
-        axis.drive_active,
-        axis.raw_dir,
-        axis.remaining_steps,
-        axis.dir_setup_remaining_ms,
-        axis.step_phase,
-        axis.pending_jog,
-    )
-
-
-class Prod2UP4NormalV3ModelTests(unittest.TestCase):
-    def test_temperature_request_returns_compact_frame_without_state_change(self) -> None:
-        subject = model.NormalV3Model(temperature_values=range(27))
-        before = subject.state_fingerprint()
-
-        result = subject.apply_frame(protocol.build_get_temperatures())
-
-        self.assertTrue(result.accepted)
-        self.assertEqual(result.command, protocol.CommandId.GET_TEMPERATURES)
-        self.assertEqual(result.status, protocol.StatusCode.OK)
-        self.assertEqual(result.response_type, 0x10)
-        self.assertEqual(result.response, protocol.build_temperature_response(range(27)))
-        self.assertEqual(subject.state_fingerprint(), before)
-
-    def test_temperature_request_before_powerup_returns_all_ff_without_state_change(self) -> None:
-        subject = model.NormalV3Model(
-            temperature_values=range(27),
-            powerup_ready=False,
-        )
-        before = subject.state_fingerprint()
-
-        result = subject.apply_frame(protocol.build_get_temperatures())
-
-        self.assertTrue(result.accepted)
-        self.assertEqual(result.response, protocol.build_temperature_response([0xFF] * 27))
-        self.assertEqual(subject.state_fingerprint(), before)
-
-    def test_temperature_request_preserves_mixed_ff_values_from_nacks(self) -> None:
-        values = list(range(27))
-        values[4] = 0xFF
-        values[10] = 0xFF
-        subject = model.NormalV3Model(temperature_values=values)
-
-        result = subject.apply_frame(protocol.build_get_temperatures())
-
-        self.assertTrue(result.accepted)
-        self.assertEqual(
-            protocol.decode_temperature_response(result.response),
-            bytes(values),
-        )
-
-    def test_temperature_bus_error_returns_status_0x0a_without_compact_frame(self) -> None:
-        subject = model.NormalV3Model(temperature_bus_error=True)
-        before = subject.state_fingerprint()
-
-        result = subject.apply_frame(protocol.build_get_temperatures())
-
-        self.assertFalse(result.accepted)
-        self.assertEqual(result.command, protocol.CommandId.GET_TEMPERATURES)
-        self.assertEqual(result.status, protocol.StatusCode.TEMPERATURE_BUS_ERROR)
-        self.assertIsNone(result.response)
-        self.assertEqual(subject.state_fingerprint(), before)
-
-    def test_snapshot_encoder_preserves_arbitrary_xyz_u8(self) -> None:
-        xyz = (255, 1, 127)
-
-        wire = model.encode_snapshot_frame(
-            ptc_percent=(11,) * 24,
-            fan_percent=(22,) * 4,
-            solenoid=100,
-            xyz=xyz,
-        )
-        result = model.NormalV3Model().apply_frame(wire)
-
-        self.assertTrue(result.accepted)
-        self.assertEqual(wire[45:48], bytes(xyz))
-
-    def test_snapshot_xyz_accepts_any_u8_but_never_drives_a_motor(self) -> None:
-        for xyz in ((0, 100, 0), (255, 1, 127), (50, 200, 33)):
-            with self.subTest(xyz=xyz):
-                subject = model.NormalV3Model()
-
-                result = subject.apply_frame(
-                    snapshot(ptc=11, fan=22, solenoid=100, xyz=xyz)
-                )
-
-                self.assertTrue(result.accepted)
-                self.assertEqual(result.status, protocol.StatusCode.OK)
-                self.assertEqual(subject.ptc_percent, (11,) * 24)
-                self.assertEqual(subject.fan_percent, (22,) * 4)
-                self.assertEqual(subject.solenoid, 100)
-                self.assertEqual(subject.active_mask, 0)
-                self.assertEqual(subject.busy_mask, 0)
-                self.assertEqual(subject.position_valid_mask, 0)
-                self.assertEqual(
-                    tuple(axis.remaining_steps for axis in subject.axes[:2]),
-                    (0, 0),
-                )
-
-    def test_only_jog_opcode_can_create_motor_activity(self) -> None:
-        subject = model.NormalV3Model()
-        requests = (
-            snapshot(xyz=(100, 0, 255)),
-            protocol.build_host_command(command=protocol.CommandId.GET_STATUS),
-            protocol.build_get_motor_status(),
-            protocol.build_host_command(command=protocol.CommandId.DISABLE),
-        )
-
-        for request in requests:
-            with self.subTest(request=request.hex()):
-                subject.apply_frame(request)
-                self.assertEqual(subject.active_mask, 0)
-
-        result = subject.apply_frame(
-            protocol.build_motor_jog(axis=0, raw_dir=1, speed_code=0, steps=2)
-        )
-        self.assertTrue(result.accepted)
-        self.assertEqual(subject.active_mask, 0x01)
-
-    def test_jog_uses_full_raw_u16_steps_and_acks_after_first_step_rise(self) -> None:
-        for requested in (1, 799, 800, 801, 8191, 65535):
-            with self.subTest(requested=requested):
-                subject = model.NormalV3Model()
-                request = protocol.build_motor_jog(
-                    axis=0,
-                    raw_dir=1,
-                    speed_code=2,
-                    steps=requested,
-                )
-
-                result = subject.apply_frame(request)
-
-                self.assertTrue(result.accepted)
-                self.assertEqual(result.status, protocol.StatusCode.OK)
-                self.assertEqual(
-                    protocol.decode_motion_command(protocol.decode_frame(request)).steps,
-                    requested,
-                )
-                self.assertTrue(subject.axes[0].drive_active)
-                self.assertEqual(subject.axes[0].step_phase, "high")
-                self.assertEqual(subject.axes[0].remaining_steps, requested)
-                self.assertEqual(subject.axes[0].steps_executed, 0)
-                self.assertEqual(subject.busy_mask, 0)
-
-    def test_all_valid_speed_codes_are_ignored_for_fixed_1000_step_rate(self) -> None:
-        for speed_code in range(4):
-            with self.subTest(speed_code=speed_code):
-                subject = model.NormalV3Model()
-                subject.apply_frame(
-                    protocol.build_motor_jog(
-                        axis=0,
-                        raw_dir=0,
-                        speed_code=speed_code,
-                        steps=2,
-                    )
-                )
-
-                self.assertEqual(subject.axes[0].step_phase, "high")
-                subject.advance_time(1)
-
-                self.assertEqual(subject.axes[0].steps_executed, 1)
-                self.assertEqual(subject.axes[0].remaining_steps, 1)
-                self.assertEqual(subject.busy_mask, 0)
-
-    def test_zero_step_jog_is_a_host_precondition_violation(self) -> None:
-        subject = model.NormalV3Model()
-        before = subject.state_fingerprint()
-
-        with self.assertRaisesRegex(
-            ValueError,
-            "RAW_U16_TRUSTED_HOST_NO_CPLD_CAP",
-        ):
-            subject.apply_frame(zero_step_jog())
-
-        self.assertEqual(subject.state_fingerprint(), before)
-
-    def test_x_and_y_jog_can_overlap_without_busy_or_cross_axis_rejection(self) -> None:
-        for x_dir, y_dir, x_speed, y_speed in product((0, 1), (0, 1), range(4), range(4)):
-            with self.subTest(
-                x_dir=x_dir,
-                y_dir=y_dir,
-                x_speed=x_speed,
-                y_speed=y_speed,
-            ):
-                subject = model.NormalV3Model()
-                x_result = subject.apply_frame(
-                    protocol.build_motor_jog(
-                        axis=0,
-                        raw_dir=x_dir,
-                        speed_code=x_speed,
-                        steps=10,
-                    )
-                )
-                y_result = subject.apply_frame(
-                    protocol.build_motor_jog(
-                        axis=1,
-                        raw_dir=y_dir,
-                        speed_code=y_speed,
-                        steps=20,
-                    )
-                )
-
-                self.assertTrue(x_result.accepted)
-                self.assertTrue(y_result.accepted)
-                self.assertEqual(subject.active_mask, 0x03)
-                self.assertEqual(subject.busy_mask, 0)
-                self.assertEqual(subject.axes[0].raw_dir, x_dir)
-                self.assertEqual(subject.axes[1].raw_dir, y_dir)
-
-    def test_new_same_axis_jog_immediately_truncates_and_reloads_old_step(self) -> None:
-        subject = model.NormalV3Model()
-        subject.apply_frame(
-            protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=0, steps=10)
-        )
-        self.assertEqual(subject.axes[0].step_phase, "high")
-
-        result = subject.apply_frame(
-            protocol.build_motor_jog(axis=0, raw_dir=1, speed_code=3, steps=20)
-        )
-
-        self.assertTrue(result.accepted)
-        self.assertEqual(subject.axes[0].raw_dir, 1)
-        self.assertEqual(subject.axes[0].speed_code, 3)
-        self.assertEqual(subject.axes[0].remaining_steps, 20)
-        self.assertEqual(subject.axes[0].steps_executed, 0)
-        self.assertEqual(subject.axes[0].step_phase, "high")
-        self.assertIsNone(subject.axes[0].pending_jog)
-
-    def test_jog_does_not_arm_or_refresh_watchdog(self) -> None:
-        subject = model.NormalV3Model()
-        before = (
-            subject.disabled,
-            subject.watchdog_timeout,
-            subject.watchdog_armed,
-            subject.watchdog_elapsed_ms,
-        )
-
-        subject.apply_frame(
-            protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=3, steps=10)
-        )
-
-        self.assertEqual(
-            (
-                subject.disabled,
-                subject.watchdog_timeout,
-                subject.watchdog_armed,
-                subject.watchdog_elapsed_ms,
-            ),
-            before,
-        )
-        self.assertEqual(subject.active_mask, 0x01)
-
-    def test_disable_and_watchdog_only_safe_non_motor_outputs(self) -> None:
-        for stop in ("disable", "watchdog"):
-            with self.subTest(stop=stop):
-                subject = model.NormalV3Model()
-                subject.apply_frame(
-                    protocol.build_motor_jog(
-                        axis=0,
-                        raw_dir=1,
-                        speed_code=0,
-                        steps=32,
-                    )
-                )
-                subject.ptc_percent = (25,) * 24
-                subject.fan_percent = (40,) * 4
-                subject.solenoid = 100
-                before_motion = motion_tuple(subject, 0)
-
-                if stop == "disable":
-                    subject.disable()
-                else:
-                    subject.disabled = False
-                    subject.watchdog_armed = True
-                    subject.watchdog_expire()
-
-                self.assertEqual(subject.ptc_percent, (0,) * 24)
-                self.assertEqual(subject.fan_percent, (30,) * 4)
-                self.assertEqual(subject.solenoid, 0)
-                self.assertEqual(motion_tuple(subject, 0), before_motion)
-
-    def test_motor_status_is_constant_unknown_zero_masks_and_enable_active(self) -> None:
-        for active in (False, True):
-            with self.subTest(active=active):
-                subject = model.NormalV3Model()
-                if active:
-                    subject.apply_frame(
-                        protocol.build_motor_jog(
-                            axis=1,
-                            raw_dir=1,
-                            speed_code=1,
-                            steps=10,
-                        )
-                    )
-                subject.axes[0].busy = True
-                subject.axes[0].fault = True
-
-                payload = subject.motor_status_payload()
-
-                self.assertEqual(payload[0] & 0x01, 0)
-                self.assertEqual(payload[0] & 0x02, 0x02)
-                self.assertEqual(payload[1], 0)
-                self.assertEqual(payload[2], 0)
-                self.assertEqual(payload[3:9], b"\xFF" * 6)
-                self.assertEqual(payload[9], 0)
-                self.assertEqual(subject.busy_mask, 0)
-                self.assertEqual(subject.fault_mask, 0)
-
-    def test_model_has_no_limit_input_or_qualification_state(self) -> None:
-        subject = model.NormalV3Model()
-        self.assertNotIn("limit", inspect.getsource(model.NormalV3Model._apply_jog).lower())
-        self.assertFalse(
-            any("limit" in field.lower() for field in model.AxisState.__dataclass_fields__)
-        )
-        self.assertFalse(hasattr(subject, "observe_limits"))
-        self.assertFalse(hasattr(subject, "advance_limit_confirmation"))
-        self.assertFalse(hasattr(model, "HighActiveLimitOracle"))
-
-    def test_unsupported_legacy_commands_are_atomic(self) -> None:
-        subject = model.NormalV3Model()
-        temperature = protocol.encode_frame(
-            frame_type=protocol.FrameType.HOST_CMD,
-            seq=0,
-            timestamp_tick=0,
-            payload=b"\x29\x00\x00\x00",
-        )
-        for request, command in (
-            (model.GOLDEN_VECTORS["mark_x"], 0x36),
-            (temperature, 0x29),
-        ):
-            with self.subTest(command=command):
-                before = subject.state_fingerprint()
-                result = subject.apply_frame(request)
-                self.assertFalse(result.accepted)
-                self.assertEqual(result.command, command)
-                self.assertEqual(result.status, protocol.StatusCode.UNSUPPORTED_IN_PROFILE)
-                self.assertEqual(subject.state_fingerprint(), before)
-
-    def test_model_replay_and_fuzz_follow_the_jog_only_contract(self) -> None:
-        self.assertEqual(model.run_model()["status"], "pass")
-        self.assertEqual(model.run_replay()["status"], "pass")
-        fuzz = model.run_fuzz(seed=921003, iterations=90)
-        self.assertEqual(fuzz["status"], "pass", fuzz)
-
-    def test_source_detector_requires_git_only_identity_and_explicit_solenoid_polarity(self) -> None:
-        detector = model.run_detector(ROOT)
-        self.assertEqual(detector["status"], "pass", detector)
-        self.assertTrue(detector["guards"]["runtime_build_identity_absent"])
-        self.assertTrue(detector["guards"]["solenoid_polarity_default_explicit"])
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 69
tests/unit/test_prod2u_p4_output_storage_structure.py

@@ -1,69 +0,0 @@
-#!/usr/bin/env python3
-"""Structural resource contracts for Normal-v3 output storage."""
-
-from __future__ import annotations
-
-import unittest
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[2]
-OUTPUT_STATE = ROOT / "src" / "rtl" / "prod2u_p4_normal_v3_output_state.v"
-PWM_OUTPUTS = ROOT / "src" / "rtl" / "prod2u_p4_pwm_outputs.v"
-
-
-class OutputStorageStructureTests(unittest.TestCase):
-    def test_committed_outputs_use_narrow_internal_storage(self) -> None:
-        source = OUTPUT_STATE.read_text(encoding="ascii")
-
-        self.assertIn("reg [167:0] ptc_percent_7;", source)
-        self.assertIn("reg [27:0] fan_percent_7;", source)
-        self.assertIn("reg [1:0] solenoid_rail;", source)
-        self.assertIn("reg [167:0] candidate_ptc_7;", source)
-        self.assertIn("reg [27:0] candidate_fan_7;", source)
-        self.assertIn("reg [1:0] candidate_solenoid_rail;", source)
-        self.assertNotIn("motor_target", source)
-        self.assertNotIn("reg [271:0] candidate_payload;", source)
-        self.assertNotIn("output reg  [191:0] ptc_percent", source)
-        self.assertNotIn("output reg  [31:0]  fan_percent", source)
-        self.assertNotIn("output reg  [7:0]   solenoid_percent", source)
-        self.assertNotIn("output reg  [23:0]  motor_targets", source)
-
-    def test_binary_outputs_are_reconstructed_at_the_interface(self) -> None:
-        source = OUTPUT_STATE.read_text(encoding="ascii")
-
-        self.assertIn("localparam [1:0] RAIL_INVALID = 2'b00;", source)
-        self.assertIn("localparam [1:0] RAIL_ZERO = 2'b01;", source)
-        self.assertIn("localparam [1:0] RAIL_HUNDRED = 2'b10;", source)
-        self.assertIn("function [1:0] encode_binary_rail;", source)
-        self.assertIn("function [7:0] decode_binary_rail;", source)
-
-    def test_rx_buffer_and_one_core_snapshot_latch_are_the_only_272_bit_registers(self) -> None:
-        owners = []
-        for path in sorted((ROOT / "src" / "rtl").glob("*.v")):
-            if "reg [271:0]" in path.read_text(encoding="ascii"):
-                owners.append(path.name)
-
-        self.assertEqual(
-            owners,
-            ["prod2u_p4_normal_v3_core.v", "prod2u_p4_normal_v3_rx.v"],
-        )
-        core = (ROOT / "src" / "rtl" / "prod2u_p4_normal_v3_core.v").read_text(
-            encoding="ascii"
-        )
-        self.assertEqual(core.count("reg [271:0]"), 1)
-        self.assertIn("reg [271:0] snapshot_payload_latched;", core)
-
-    def test_pwm_step_counters_use_parameter_sized_storage(self) -> None:
-        source = PWM_OUTPUTS.read_text(encoding="ascii")
-
-        self.assertIn("localparam integer PTC_COUNTER_BITS", source)
-        self.assertIn("localparam integer FAN_COUNTER_BITS", source)
-        self.assertIn("reg [PTC_COUNTER_BITS - 1:0] ptc_step_counter;", source)
-        self.assertIn("reg [FAN_COUNTER_BITS - 1:0] fan_step_counter;", source)
-        self.assertNotIn("reg [31:0] ptc_step_counter;", source)
-        self.assertNotIn("reg [31:0] fan_step_counter;", source)
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 153
tests/unit/test_prod2u_p4_parallel_offline_gate.py

@@ -1,153 +0,0 @@
-#!/usr/bin/env python3
-"""Concurrency contract for the Normal v3 strict offline gate."""
-
-from __future__ import annotations
-
-import tempfile
-import threading
-from pathlib import Path
-from unittest.mock import patch
-
-from tools import prod2u_p4_harness as harness
-
-
-def test_strict_offline_gate_starts_all_five_runners_in_parallel() -> None:
-    barrier = threading.Barrier(5)
-    observed_roots: dict[str, Path] = {}
-
-    def finish(name: str, work_root: Path) -> dict[str, object]:
-        observed_roots[name] = Path(work_root).resolve()
-        barrier.wait(timeout=5)
-        return {"status": "pass", "work_root": str(work_root)}
-
-    def fake_hdl(*, run: bool, backend: str, work_root: Path) -> dict[str, object]:
-        assert run is True
-        payload = finish(backend, work_root)
-        payload.update(
-            {
-                "schema": harness.HDL_RECEIPT_SCHEMA,
-                "verification_layer": "hdl_sim",
-                "backend": backend,
-                "tests": [],
-                "target_manifest": {"status": "pass"},
-            }
-        )
-        return payload
-
-    source_state = {
-        "status": "pass",
-        "clean": True,
-        "commit": "bbc1b20f",
-        "changes": [],
-    }
-    with tempfile.TemporaryDirectory(
-        dir=r"C:\Users\Administrator\CodexTemp"
-    ) as temporary, patch.object(
-        harness, "source_state", return_value=source_state
-    ), patch.object(
-        harness,
-        "source_integrity_payload",
-        return_value={"status": "pass", "source_state": source_state},
-    ), patch.object(
-        harness, "unit_payload", side_effect=lambda root: finish("unit", root)
-    ), patch.object(
-        harness, "hdl_sim_payload", side_effect=fake_hdl
-    ), patch.object(
-        harness,
-        "formal_payload",
-        side_effect=lambda *, run, work_root: finish("formal", work_root),
-    ):
-        receipt = harness.strict_offline_gate_payload(
-            work_root=Path(temporary),
-            verification_run_id="1" * 32,
-        )
-
-    assert receipt["status"] == "pass"
-    assert set(observed_roots) == {
-        "unit",
-        "icarus",
-        "verilator",
-        "cocotb",
-        "formal",
-    }
-    assert len(set(observed_roots.values())) == 5
-    assert all(path.parent == Path(temporary).resolve() for path in observed_roots.values())
-    assert set(receipt["layers"]["hdl_sim"]["backend_results"]) == {
-        "icarus",
-        "verilator",
-        "cocotb",
-    }
-
-
-def test_strict_offline_gate_waits_for_all_runners_and_reports_exceptions() -> None:
-    barrier = threading.Barrier(5)
-    completed: set[str] = set()
-    completed_lock = threading.Lock()
-
-    def finish(name: str, work_root: Path, *, status: str = "pass") -> dict[str, object]:
-        barrier.wait(timeout=5)
-        with completed_lock:
-            completed.add(name)
-        return {"status": status, "work_root": str(work_root)}
-
-    def fake_hdl(*, run: bool, backend: str, work_root: Path) -> dict[str, object]:
-        assert run is True
-        if backend == "verilator":
-            barrier.wait(timeout=5)
-            with completed_lock:
-                completed.add(backend)
-            raise RuntimeError("verilator runner exploded")
-        payload = finish(backend, work_root)
-        payload.update(
-            {
-                "schema": harness.HDL_RECEIPT_SCHEMA,
-                "verification_layer": "hdl_sim",
-                "backend": backend,
-                "tests": [],
-                "target_manifest": {"status": "pass"},
-            }
-        )
-        return payload
-
-    source_state = {
-        "status": "pass",
-        "clean": True,
-        "commit": "bbc1b20f",
-        "changes": [],
-    }
-    with tempfile.TemporaryDirectory(
-        dir=r"C:\Users\Administrator\CodexTemp"
-    ) as temporary, patch.object(
-        harness, "source_state", return_value=source_state
-    ), patch.object(
-        harness,
-        "source_integrity_payload",
-        return_value={"status": "pass", "source_state": source_state},
-    ), patch.object(
-        harness,
-        "unit_payload",
-        side_effect=lambda root: finish("unit", root),
-    ), patch.object(
-        harness, "hdl_sim_payload", side_effect=fake_hdl
-    ), patch.object(
-        harness,
-        "formal_payload",
-        side_effect=lambda *, run, work_root: finish(
-            "formal", work_root, status="fail"
-        ),
-    ):
-        receipt = harness.strict_offline_gate_payload(
-            work_root=Path(temporary),
-            verification_run_id="2" * 32,
-        )
-
-    assert completed == {"unit", "icarus", "verilator", "cocotb", "formal"}
-    assert receipt["status"] == "fail"
-    assert receipt["layers"]["formal"]["status"] == "fail"
-    verilator = receipt["layers"]["hdl_sim"]["backend_results"]["verilator"]
-    assert verilator["status"] == "fail"
-    assert "RuntimeError: verilator runner exploded" in verilator["reason"]
-    assert set(receipt["failures"]) == {
-        "required_layer_not_pass:hdl_sim:fail",
-        "required_layer_not_pass:formal:fail",
-    }

+ 0 - 394
tests/unit/test_prod2u_p4_protocol_v3.py

@@ -1,394 +0,0 @@
-#!/usr/bin/env python3
-"""Wire-contract tests for the minimal ACK-only Normal-v3 protocol."""
-
-from __future__ import annotations
-
-import json
-import sys
-import unittest
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(ROOT / "tools"))
-
-import prod2u_p4_protocol as protocol  # noqa: E402
-
-
-class Prod2UP4ProtocolV3Tests(unittest.TestCase):
-    def test_public_frame_types_are_ack_only_without_boot_or_trace(self) -> None:
-        self.assertEqual(
-            {item.name: int(item) for item in protocol.FrameType},
-            {
-                "HOST_CMD": 0x05,
-                "HOST_ACK": 0x06,
-                "HOST_BATCH_CMD": 0x07,
-                "MOTION_CMD": 0x11,
-                "MOTION_STATUS": 0x12,
-            },
-        )
-        for retired in (
-            "CAPABILITY_FLAGS",
-            "Capability",
-            "BootBuildId",
-            "build_boot_build_id",
-            "decode_boot_build_id",
-            "TRACE_PAYLOAD_LEN",
-        ):
-            self.assertFalse(hasattr(protocol, retired), retired)
-
-    def test_snapshot_frame_remains_exactly_fifty_bytes(self) -> None:
-        wire = protocol.build_output_snapshot(
-            ptc_percent=range(24),
-            fan_percent=(30, 40, 50, 60),
-            solenoid=100,
-            xyz=(100, 0, 100),
-        )
-        decoded = protocol.decode_output_snapshot(protocol.decode_frame(wire))
-
-        self.assertEqual(len(wire), 50)
-        self.assertEqual(wire[:14].hex(), "a55a020407000000000000000022")
-        self.assertEqual(decoded.ptc_percent, tuple(range(24)))
-        self.assertEqual(decoded.fan_percent, (30, 40, 50, 60))
-        self.assertEqual(decoded.solenoid, 100)
-        self.assertEqual(decoded.xyz, (100, 0, 100))
-
-    def test_motion_requests_keep_frozen_payloads_and_full_u16_steps(self) -> None:
-        for speed_code in range(4):
-            for steps in (1, 799, 800, 801, 8191, 65535):
-                with self.subTest(speed_code=speed_code, steps=steps):
-                    wire = protocol.build_motor_jog(
-                        axis=1,
-                        raw_dir=1,
-                        speed_code=speed_code,
-                        steps=steps,
-                    )
-                    frame = protocol.decode_frame(wire)
-                    decoded = protocol.decode_motion_command(frame)
-                    self.assertEqual(len(wire), 24)
-                    self.assertEqual(frame.payload[3], speed_code)
-                    self.assertEqual(frame.payload[4:6], steps.to_bytes(2, "little"))
-                    self.assertEqual(decoded.speed_code, speed_code)
-                    self.assertEqual(decoded.steps, steps)
-
-        with self.assertRaisesRegex(ValueError, "speed_code must be from 0 to 3"):
-            protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=4, steps=1)
-
-        with self.assertRaisesRegex(ValueError, "1 to 65535"):
-            protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=0, steps=0)
-
-        self.assertEqual(
-            protocol.build_mark_closed(axis=0, close_dir=1).hex(),
-            "a55a0204110000000000000000083600010000000000477d",
-        )
-        self.assertEqual(
-            protocol.build_get_motor_status().hex(),
-            "a55a0204110000000000000000083700000000000000347f",
-        )
-
-    def test_zero_step_jog_remains_a_bad_value_on_the_wire(self) -> None:
-        wire = bytearray(
-            protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=3, steps=1)
-        )
-        wire[18:20] = b"\x00\x00"
-        wire[-2:] = protocol.crc16_ccitt(wire[2:-2]).to_bytes(2, "little")
-
-        with self.assertRaisesRegex(ValueError, "steps must be from 1 to 65535"):
-            protocol.decode_motion_command(protocol.decode_frame(bytes(wire)))
-
-    def test_legacy_0x29_stays_retired_while_0x28_has_one_public_builder(self) -> None:
-        wire = protocol.encode_frame(
-            frame_type=protocol.FrameType.HOST_CMD,
-            seq=0,
-            timestamp_tick=0,
-            payload=b"\x29\x00\x00\x00",
-        )
-        self.assertEqual(protocol.decode_frame(wire).payload, b"\x29\x00\x00\x00")
-        for retired in (
-            "TemperatureSnapshot",
-            "decode_temperature_snapshot",
-        ):
-            self.assertFalse(hasattr(protocol, retired), retired)
-        self.assertEqual(
-            protocol.build_get_temperatures().hex(),
-            "a55a020405000000000000000004280000009e0c",
-        )
-
-    def test_host_ack_preserves_partial_detail_and_actual_output_hash(self) -> None:
-        wire = protocol.build_host_ack(
-            ok=True,
-            command=protocol.CommandId.SET_OUTPUT_SNAPSHOT,
-            status=protocol.StatusCode.PARTIAL,
-            detail=0x5A,
-            state_hash16=0xE177,
-            result_flags=0x05,
-        )
-        ack = protocol.decode_host_ack(protocol.decode_frame(wire))
-
-        self.assertEqual(len(wire), 24)
-        self.assertEqual(ack.status, protocol.StatusCode.PARTIAL)
-        self.assertEqual(ack.detail, 0x5A)
-        self.assertEqual(ack.state_hash16, 0xE177)
-        self.assertEqual(ack.result_flags, 0x05)
-
-    def test_motion_status_keeps_ten_byte_layout_with_reserved_zero_busy_and_fault(self) -> None:
-        wire = protocol.build_motion_status(
-            flags=0x02,
-            position_valid_mask=0,
-            busy_mask=0,
-            current_xyz=(0xFF, 0xFF, 0xFF),
-            target_xyz=(0xFF, 0xFF, 0xFF),
-            fault_mask=0,
-        )
-        frame = protocol.decode_frame(wire)
-        status = protocol.decode_motion_status(frame)
-
-        self.assertEqual(len(frame.payload), 10)
-        self.assertEqual(len(wire), 26)
-        self.assertEqual(status.busy_mask, 0)
-        self.assertEqual(status.flags & 0x02, 0x02)
-        self.assertEqual(status.current_xyz, (0xFF, 0xFF, 0xFF))
-        self.assertEqual(status.target_xyz, (0xFF, 0xFF, 0xFF))
-        self.assertEqual(status.fault_mask, 0)
-
-    def test_versioned_host_contract_matches_minimal_motion_semantics(self) -> None:
-        contract = json.loads(
-            (ROOT / "config" / "prod2u_p4_normal_host_contract_v4.json").read_text(
-                encoding="utf-8"
-            )
-        )
-
-        self.assertEqual(contract["profile"], "prod2u-p4-normal-actuator-binary921-v3")
-        self.assertEqual(contract["version_source"], "lowercase_git_sha8")
-        self.assertEqual(contract["wire"]["ordinary_response_order"], ["HOST_ACK"])
-        self.assertEqual(
-            contract["wire"]["motor_status_response_order"],
-            ["HOST_ACK", "MOTION_STATUS"],
-        )
-        self.assertFalse(contract["wire"]["unsolicited_frames"])
-        self.assertEqual(contract["unsupported_commands"]["0x29"]["status_code"], 1)
-        self.assertEqual(contract["unsupported_commands"]["0x36"]["status_code"], 1)
-        self.assertEqual(contract["commands"]["jog"]["step_range"], [1, 65535])
-        self.assertEqual(contract["commands"]["jog"]["cli_axes"], ["X", "Y"])
-        self.assertEqual(contract["commands"]["jog"]["reserved_z_status"], "BAD_VALUE")
-        self.assertIsNone(contract["commands"]["jog"]["executed_step_cap"])
-        self.assertEqual(
-            contract["commands"]["jog"]["over_cap_behavior"],
-            "EXECUTE_REQUESTED_U16_STEPS",
-        )
-        self.assertEqual(
-            contract["commands"]["jog"]["speed_field_policy"],
-            "VALIDATE_0_TO_3_THEN_IGNORE",
-        )
-        self.assertEqual(contract["commands"]["jog"]["effective_step_rate_hz"], 1000)
-        self.assertEqual(
-            contract["commands"]["jog"]["ack_semantics"],
-            "FIRST_STEP_EMITTED",
-        )
-        self.assertFalse(contract["commands"]["jog"]["arms_watchdog"])
-        self.assertEqual(
-            contract["commands"]["jog"]["same_axis_active_policy"],
-            "IMMEDIATE_RELOAD_AND_RESTART_DIR_SETUP",
-        )
-        self.assertEqual(contract["commands"]["jog"]["multiple_pending_policy"], "NONE")
-        self.assertFalse(contract["commands"]["jog"]["rejects_busy"])
-        self.assertEqual(
-            contract["commands"]["jog"]["admission_ignores"],
-            [
-                "AXIS_ACTIVE",
-                "SNAPSHOT_VALID",
-                "LIMIT_INPUTS",
-                "WATCHDOG_TIMEOUT",
-            ],
-        )
-        self.assertEqual(
-            contract["commands"]["jog"]["watchdog_timeout_recovery"],
-            "NOT_APPLICABLE_TIMEOUT_HAS_NO_MOTOR_EFFECT",
-        )
-        self.assertEqual(contract["commands"]["jog"]["limit_policy"], "IGNORE_ALL_INPUTS")
-        self.assertEqual(
-            contract["commands"]["set_output_snapshot"]["xyz_policy"],
-            "IGNORE_ANY_U8_NO_MOTOR_EFFECT",
-        )
-        self.assertEqual(
-            contract["commands"]["set_output_snapshot"]["motor_effect"],
-            "NONE",
-        )
-        self.assertEqual(contract["motion"]["motor_driving_commands"], ["0x35"])
-        self.assertEqual(contract["motion"]["jog_ack_semantics"], "FIRST_STEP_EMITTED")
-        self.assertEqual(
-            contract["motion"]["same_axis_jog_while_active"],
-            "IMMEDIATE_RELOAD_AND_RESTART_DIR_SETUP",
-        )
-        self.assertEqual(
-            contract["motion"]["normal_step_stop"],
-            "NEW_SAME_AXIS_JOG_MAY_TRUNCATE_OLD_STEP",
-        )
-        self.assertEqual(
-            contract["motion"]["motor_stop_sources"],
-            ["RESET", "POWER_LOSS", "RECONFIGURATION"],
-        )
-        self.assertEqual(
-            contract["responses"]["motion_status"]["busy_semantic"],
-            "ALWAYS_ZERO",
-        )
-        self.assertEqual(
-            contract["responses"]["motion_status"]["busy_role"],
-            "RESERVED_CONSTANT_ZERO",
-        )
-        self.assertEqual(contract["responses"]["motion_status"]["busy_mask"], 0)
-        self.assertEqual(contract["responses"]["motion_status"]["position_valid_mask"], 0)
-        self.assertEqual(contract["responses"]["motion_status"]["current_xyz"], [255, 255, 255])
-        self.assertEqual(contract["responses"]["motion_status"]["target_xyz"], [255, 255, 255])
-        self.assertEqual(contract["responses"]["motion_status"]["enable_active"], 1)
-        self.assertEqual(contract["responses"]["motion_status"]["fault_mask"], 0)
-        self.assertEqual(
-            contract["responses"]["host_ack"]["snapshot_result_flag_bits"],
-            {
-                "ptc_fan_solenoid_committed": 0,
-                "axis_bits_3_to_1": "ZERO",
-            },
-        )
-        self.assertEqual(contract["commands"]["disable"]["motor_effect"], "NONE")
-        self.assertEqual(
-            contract["commands"]["disable"]["non_motor_effect"],
-            "IMMEDIATE_SAFE_OUTPUTS",
-        )
-        self.assertEqual(contract["watchdog"]["motor_effect"], "NONE")
-        self.assertEqual(contract["watchdog"]["non_motor_effect"], "SAFE_OUTPUTS")
-        self.assertTrue(contract["watchdog"]["status_query_cannot_arm_or_revive"])
-        self.assertTrue(contract["limit"]["pins_retained"])
-        self.assertEqual(contract["limit"]["logic_consumer"], "NONE")
-        self.assertEqual(
-            contract["limit"]["used_only_for"],
-            "RETAINED_PINS_NO_LOGIC_CONSUMER",
-        )
-        self.assertEqual(contract["responses"]["motion_status"]["fault_mask"], 0)
-
-    def test_host_contract_schema_freezes_force_jog_v1_semantics(self) -> None:
-        schema = json.loads(
-            (ROOT / "schemas" / "prod2u_p4_normal_host_contract_v4.schema.json").read_text(
-                encoding="utf-8"
-            )
-        )
-
-        jog_properties = schema["properties"]["commands"]["properties"]["jog"]
-        snapshot_properties = schema["properties"]["commands"]["properties"]["set_output_snapshot"]
-        motion_properties = schema["properties"]["motion"]["properties"]
-        status_properties = schema["properties"]["responses"]["properties"]["motion_status"]["properties"]
-        limit_properties = schema["properties"]["limit"]["properties"]
-
-        self.assertEqual(jog_properties["$ref"], "#/$defs/jogCommand")
-        self.assertEqual(snapshot_properties["$ref"], "#/$defs/snapshotCommand")
-        self.assertEqual(motion_properties["motor_driving_commands"]["const"], ["0x35"])
-        self.assertEqual(
-            motion_properties["jog_ack_semantics"]["const"],
-            "FIRST_STEP_EMITTED",
-        )
-        self.assertEqual(status_properties["busy_semantic"]["const"], "ALWAYS_ZERO")
-        self.assertEqual(
-            status_properties["busy_role"]["const"],
-            "RESERVED_CONSTANT_ZERO",
-        )
-        self.assertEqual(status_properties["busy_mask"]["const"], 0)
-        self.assertEqual(status_properties["position_valid_mask"]["const"], 0)
-        self.assertEqual(status_properties["current_xyz"]["const"], [255, 255, 255])
-        self.assertEqual(status_properties["target_xyz"]["const"], [255, 255, 255])
-        self.assertEqual(status_properties["enable_active"]["const"], 1)
-        self.assertEqual(status_properties["fault_mask"]["const"], 0)
-        self.assertTrue(limit_properties["pins_retained"]["const"])
-        self.assertEqual(limit_properties["logic_consumer"]["const"], "NONE")
-        self.assertEqual(
-            limit_properties["used_only_for"]["const"],
-            "RETAINED_PINS_NO_LOGIC_CONSUMER",
-        )
-
-        jog_definition = schema["$defs"]["jogCommand"]
-        self.assertIsNone(jog_definition["properties"]["executed_step_cap"]["const"])
-        self.assertEqual(
-            jog_definition["properties"]["speed_field_policy"]["const"],
-            "VALIDATE_0_TO_3_THEN_IGNORE",
-        )
-        self.assertEqual(
-            jog_definition["properties"]["effective_step_rate_hz"]["const"],
-            1000,
-        )
-        self.assertEqual(
-            jog_definition["properties"]["ack_semantics"]["const"],
-            "FIRST_STEP_EMITTED",
-        )
-        self.assertFalse(jog_definition["properties"]["arms_watchdog"]["const"])
-        self.assertEqual(jog_definition["properties"]["rejects_busy"]["const"], False)
-        self.assertEqual(
-            jog_definition["properties"]["same_axis_active_policy"]["const"],
-            "IMMEDIATE_RELOAD_AND_RESTART_DIR_SETUP",
-        )
-        self.assertEqual(
-            jog_definition["properties"]["multiple_pending_policy"]["const"],
-            "NONE",
-        )
-        self.assertEqual(
-            jog_definition["properties"]["admission_ignores"]["const"],
-            [
-                "AXIS_ACTIVE",
-                "SNAPSHOT_VALID",
-                "LIMIT_INPUTS",
-                "WATCHDOG_TIMEOUT",
-            ],
-        )
-        watchdog_properties = schema["properties"]["watchdog"]["properties"]
-        self.assertEqual(watchdog_properties["motor_effect"]["const"], "NONE")
-        self.assertEqual(
-            watchdog_properties["non_motor_effect"]["const"],
-            "SAFE_OUTPUTS",
-        )
-        snapshot_definition = schema["$defs"]["snapshotCommand"]["properties"]
-        self.assertEqual(
-            snapshot_definition["xyz_policy"]["const"],
-            "IGNORE_ANY_U8_NO_MOTOR_EFFECT",
-        )
-        self.assertEqual(snapshot_definition["motor_effect"]["const"], "NONE")
-        motion_schema = schema["properties"]["motion"]["properties"]
-        self.assertEqual(
-            motion_schema["motor_stop_sources"]["const"],
-            ["RESET", "POWER_LOSS", "RECONFIGURATION"],
-        )
-
-    def test_host_contract_machine_freezes_header_offsets_and_crc_parameters(self) -> None:
-        contract = json.loads(
-            (ROOT / "config" / "prod2u_p4_normal_host_contract_v4.json").read_text(
-                encoding="utf-8"
-            )
-        )
-
-        self.assertEqual(
-            contract["wire"]["header_offsets"],
-            {
-                "magic": [0, 1],
-                "version": 2,
-                "profile_id": 3,
-                "frame_type": 4,
-                "seq_u32_le": [5, 8],
-                "timestamp_tick_u32_le": [9, 12],
-                "payload_length_u8": 13,
-                "payload": [14, "14+payload_length-1"],
-                "crc16_le": ["14+payload_length", "15+payload_length"],
-            },
-        )
-        self.assertEqual(
-            contract["wire"]["crc16"],
-            {
-                "name": "CRC-16/CCITT-FALSE",
-                "polynomial": 0x1021,
-                "initial": 0xFFFF,
-                "reflect_input": False,
-                "reflect_output": False,
-                "xor_output": 0x0000,
-                "coverage": "version_through_payload_inclusive",
-                "wire_byte_order": "little-endian",
-            },
-        )
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 142
tests/unit/test_prod2u_p4_retirement_contract.py

@@ -1,142 +0,0 @@
-#!/usr/bin/env python3
-"""Retirement tombstones for the minimal single-top Normal-v3 image."""
-
-from __future__ import annotations
-
-import hashlib
-import json
-import re
-import sys
-import unittest
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[2]
-sys.path.insert(0, str(ROOT / "tools"))
-
-import prod2u_p4_normal_v3_model as model  # noqa: E402
-import prod2u_p4_protocol as protocol  # noqa: E402
-
-
-IMMUTABLE_TREE_DIGESTS = {
-    "reference/original": "1c4255fd3ee9081831b90008be250026f4d6e0f928590d4bdbdf458bcf412292",
-    "receipts": "68ae32c648792ae2a9a0cc19ed17f611c210224c7a5b12708a3027e06bcdcced",
-}
-
-
-def tree_digest(root: Path) -> str:
-    digest = hashlib.sha256()
-    for path in sorted(candidate for candidate in root.rglob("*") if candidate.is_file()):
-        relative = path.relative_to(ROOT).as_posix().encode("utf-8")
-        content = path.read_bytes()
-        digest.update(len(relative).to_bytes(4, "little"))
-        digest.update(relative)
-        digest.update(len(content).to_bytes(8, "little"))
-        digest.update(content)
-    return digest.hexdigest()
-
-
-class Prod2UP4RetirementContractTests(unittest.TestCase):
-    def test_normal_v3_is_the_only_active_top_and_td_project(self) -> None:
-        self.assertEqual(
-            [path.relative_to(ROOT).as_posix() for path in sorted((ROOT / "src/top").glob("*.v"))],
-            ["src/top/prod2u_p4_normal_v3_top.v"],
-        )
-        self.assertEqual(
-            [path.relative_to(ROOT).as_posix() for path in sorted((ROOT / "td").glob("*.prj"))],
-            ["td/prod2u_p4_normal_v3.prj"],
-        )
-
-    def test_trace_legacy_ct7428_boot_and_build_identity_assets_are_absent(self) -> None:
-        roots = (ROOT / "src", ROOT / "td", ROOT / "tools", ROOT / "schemas")
-        offenders = [
-            path.relative_to(ROOT).as_posix()
-            for root in roots
-            for path in root.rglob("*")
-            if path.is_file()
-            and "__pycache__" not in path.parts
-            and re.search(
-                r"(?i)(?:^|[._/-])(trace|ct7428|build[-_]?identity)(?:[._/-]|$)",
-                path.relative_to(ROOT).as_posix(),
-            )
-        ]
-        self.assertEqual(sorted(offenders), [])
-
-    def test_public_protocol_has_no_unsolicited_identity_or_trace_surface(self) -> None:
-        self.assertEqual(
-            {item.name for item in protocol.FrameType},
-            {"HOST_CMD", "HOST_ACK", "HOST_BATCH_CMD", "MOTION_CMD", "MOTION_STATUS"},
-        )
-        for retired in (
-            "CAPABILITY_FLAGS",
-            "build_boot_build_id",
-            "decode_boot_build_id",
-            "TraceEvent",
-            "TRACE_PAYLOAD_LEN",
-        ):
-            self.assertFalse(hasattr(protocol, retired), retired)
-
-    def test_legacy_0x29_and_mark_closed_are_atomic_unsupported_commands(self) -> None:
-        subject = model.NormalV3Model()
-        requests = (
-            protocol.encode_frame(
-                frame_type=protocol.FrameType.HOST_CMD,
-                seq=0,
-                timestamp_tick=0,
-                payload=b"\x29\x00\x00\x00",
-            ),
-            protocol.build_mark_closed(axis=0, close_dir=1),
-        )
-        for request in requests:
-            before = subject.state_fingerprint()
-            result = subject.apply_frame(request)
-            self.assertFalse(result.accepted)
-            self.assertEqual(result.status, protocol.StatusCode.UNSUPPORTED_IN_PROFILE)
-            self.assertEqual(subject.state_fingerprint(), before)
-
-    def test_host_contract_has_no_unsolicited_frames_or_runtime_identity(self) -> None:
-        contract = json.loads(
-            (ROOT / "config" / "prod2u_p4_normal_host_contract_v4.json").read_text(
-                encoding="utf-8"
-            )
-        )
-
-        self.assertEqual(contract["profile"], "prod2u-p4-normal-actuator-binary921-v3")
-        self.assertEqual(contract["version_source"], "lowercase_git_sha8")
-        self.assertFalse(contract["wire"]["unsolicited_frames"])
-        serialized = json.dumps(contract, sort_keys=True).casefold()
-        for retired in ("trace_event", "boot_build_id", "build_id", "capability_flags"):
-            self.assertNotIn(retired, serialized)
-
-    def test_normal_v3_uses_43_pads_and_assigns_temperature_i2c(self) -> None:
-        constraints = (ROOT / "constraints/prod2u_p4_normal_v3.adc").read_text(encoding="ascii")
-        assignments = re.findall(
-            r"set_pin_assignment\s+\{\s*([^}]+?)\s*\}\s+\{[^}]*LOCATION\s*=\s*([^;\s]+)",
-            constraints,
-        )
-        balls = {ball.strip() for _, ball in assignments}
-
-        by_signal = {signal.strip(): ball.strip() for signal, ball in assignments}
-        self.assertEqual(len(assignments), 43)
-        self.assertEqual(len(balls), 43)
-        self.assertNotIn("A5", balls)
-        self.assertEqual(by_signal["temp_scl"], "M8")
-        self.assertEqual(by_signal["temp_sda"], "N9")
-
-    def test_active_roots_have_no_loose_python_bytecode_entrypoints(self) -> None:
-        offenders = [
-            path.relative_to(ROOT).as_posix()
-            for root_name in ("src", "tests", "tools", "td", "config", "constraints", "schemas")
-            for path in (ROOT / root_name).rglob("*.py[co]")
-            if "__pycache__" not in path.parts
-        ]
-        self.assertEqual(sorted(offenders), [])
-
-    def test_reference_and_receipt_trees_remain_byte_identical(self) -> None:
-        for relative, expected in IMMUTABLE_TREE_DIGESTS.items():
-            with self.subTest(relative=relative):
-                self.assertEqual(tree_digest(ROOT / relative), expected)
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 383
tests/unit/test_prod2u_p4_send_hex_template.py

@@ -1,383 +0,0 @@
-#!/usr/bin/env python3
-"""Offline contract tests for the packaged ACK-only SEND_HEX utility."""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-import unittest
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[2]
-TOOLS = ROOT / "tools"
-SEND_HEX = TOOLS / "package_templates" / "SEND_HEX.ps1"
-INITIALIZE_DISABLE = TOOLS / "package_templates" / "INITIALIZE_DISABLE.ps1"
-RUNTIME_MARKER = "# SEND_HEX_RUNTIME_START"
-FROZEN_JOG_HEX = {
-    800: "A55A02041100000000000000000835010003200300003FC8",
-    65535: "A55A02041100000000000000000835010102FFFF000010CD",
-}
-FROZEN_SNAPSHOT_XY_IGNORED_HEX = (
-    "A55A0204070000000000000000222A000000000000000000000000000000000000"
-    "000000000000001E1E1E1E00646400935F"
-)
-sys.path.insert(0, str(TOOLS))
-
-import prod2u_p4_protocol as protocol  # noqa: E402
-
-
-def _with_recomputed_crc(frame: bytes, *, offset: int, value: int) -> bytes:
-    changed = bytearray(frame)
-    changed[offset] = value
-    changed[-2:] = protocol.crc16_ccitt(changed[2:-2]).to_bytes(2, "little")
-    return bytes(changed)
-
-
-def _invoke_parser(request: bytes, response: bytes) -> subprocess.CompletedProcess[str]:
-    source = SEND_HEX.read_text(encoding="utf-8", errors="strict")
-    if RUNTIME_MARKER not in source:
-        raise AssertionError(f"{SEND_HEX} must expose pure parser functions before {RUNTIME_MARKER}")
-    definitions = source.split(RUNTIME_MARKER, 1)[0]
-    response_expression = (
-        f"Convert-HexToBytes '{response.hex()}'" if response else "[byte[]]::new(0)"
-    )
-    invocation = f"""
-$requestBytes = Convert-HexToBytes '{request.hex()}'
-$responseBytes = {response_expression}
-try {{
-    $result = Assert-ResponseContract -Request $requestBytes -ResponseBytes $responseBytes
-    $result | ConvertTo-Json -Depth 8 -Compress
-    exit 0
-}} catch {{
-    [Console]::Error.WriteLine($_.Exception.Message)
-    exit 7
-}}
-"""
-    with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
-        probe = Path(temporary) / "send-hex-parser-probe.ps1"
-        probe.write_text(definitions + invocation, encoding="utf-8")
-        return subprocess.run(
-            [
-                "powershell.exe",
-                "-NoProfile",
-                "-ExecutionPolicy",
-                "Bypass",
-                "-File",
-                str(probe),
-                "-Hex",
-                request.hex(),
-            ],
-            cwd=ROOT,
-            capture_output=True,
-            text=True,
-            timeout=10,
-            check=False,
-        )
-
-
-def _invoke_timeout_policy(
-    request: bytes,
-    *,
-    requested_timeout_ms: int = 750,
-) -> subprocess.CompletedProcess[str]:
-    source = SEND_HEX.read_text(encoding="utf-8", errors="strict")
-    if RUNTIME_MARKER not in source:
-        raise AssertionError(f"{SEND_HEX} must expose pure functions before {RUNTIME_MARKER}")
-    definitions = source.split(RUNTIME_MARKER, 1)[0]
-    invocation = f"""
-$requestBytes = Convert-HexToBytes '{request.hex()}'
-$requestHexBefore = Convert-BytesToHex $requestBytes
-try {{
-    $timeoutMs = Get-ResponseTimeoutMs -Request $requestBytes -RequestedTimeoutMs {requested_timeout_ms}
-    [ordered]@{{
-        timeout_ms = [int]$timeoutMs
-        request_hex_before = $requestHexBefore
-        request_hex_after = Convert-BytesToHex $requestBytes
-    }} | ConvertTo-Json -Compress
-    exit 0
-}} catch {{
-    [Console]::Error.WriteLine($_.Exception.Message)
-    exit 7
-}}
-"""
-    with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
-        probe = Path(temporary) / "send-hex-timeout-probe.ps1"
-        probe.write_text(definitions + invocation, encoding="utf-8")
-        return subprocess.run(
-            [
-                "powershell.exe",
-                "-NoProfile",
-                "-ExecutionPolicy",
-                "Bypass",
-                "-File",
-                str(probe),
-                "-Hex",
-                request.hex(),
-            ],
-            cwd=ROOT,
-            capture_output=True,
-            text=True,
-            timeout=10,
-            check=False,
-        )
-
-
-def _ordinary_request() -> bytes:
-    return protocol.build_host_command(command=protocol.CommandId.GET_STATUS)
-
-
-def _ordinary_ack(
-    *,
-    ok: bool = True,
-    command: int = int(protocol.CommandId.GET_STATUS),
-    status: protocol.StatusCode = protocol.StatusCode.OK,
-) -> bytes:
-    return protocol.build_host_ack(ok=ok, command=command, status=status)
-
-
-def _motor_status_pair() -> tuple[bytes, bytes, bytes]:
-    request = protocol.build_get_motor_status()
-    ack = protocol.build_host_ack(
-        ok=True,
-        command=protocol.MotionOpcode.GET_MOTOR_STATUS,
-        status=protocol.StatusCode.OK,
-        response_type=protocol.FrameType.MOTION_STATUS,
-        result_flags=0x08,
-    )
-    status = protocol.build_motion_status(
-        flags=0x02,
-        position_valid_mask=0,
-        busy_mask=0,
-        current_xyz=(0xFF, 0xFF, 0xFF),
-        target_xyz=(0xFF, 0xFF, 0xFF),
-        fault_mask=0,
-    )
-    return request, ack, status
-
-
-class Prod2UP4SendHexTemplateTests(unittest.TestCase):
-    def assertRejected(self, request: bytes, response: bytes, pattern: str) -> None:
-        completed = _invoke_parser(request, response)
-        output = completed.stdout + completed.stderr
-        self.assertNotEqual(completed.returncode, 0, output)
-        self.assertRegex(output, pattern)
-
-    def test_valid_ordinary_ack_is_parsed_as_the_only_response(self) -> None:
-        completed = _invoke_parser(_ordinary_request(), _ordinary_ack())
-
-        self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
-        result = json.loads(completed.stdout)
-        self.assertEqual(result["status"], "pass")
-        self.assertEqual(result["request_opcode"], "0x24")
-        self.assertEqual(result["ack"]["command"], "0x24")
-        self.assertTrue(result["ack"]["ok"])
-        self.assertEqual(result["ack"]["status"], "OK")
-        self.assertEqual([frame["type"] for frame in result["frames"]], ["0x06"])
-
-    def test_partial_is_an_accepted_ack_status(self) -> None:
-        request = protocol.build_output_snapshot(
-            ptc_percent=(0,) * 24,
-            fan_percent=(30,) * 4,
-            solenoid=0,
-            xyz=(0, 0, 0),
-        )
-        response = protocol.build_host_ack(
-            ok=True,
-            command=protocol.CommandId.SET_OUTPUT_SNAPSHOT,
-            status=protocol.StatusCode.PARTIAL,
-            detail=0x41,
-            result_flags=0x0D,
-        )
-
-        completed = _invoke_parser(request, response)
-
-        self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
-        result = json.loads(completed.stdout)
-        self.assertEqual(result["ack"]["status"], "PARTIAL")
-        self.assertEqual(result["ack"]["detail"], "0x41")
-
-    def test_error_ack_returns_nonzero_for_initialize_disable_propagation(self) -> None:
-        response = _ordinary_ack(ok=False, status=protocol.StatusCode.BUSY)
-
-        self.assertRejected(_ordinary_request(), response, r"(?i)device rejected.*BUSY")
-
-        initialize = INITIALIZE_DISABLE.read_bytes().decode("ascii")
-        self.assertIn("SEND_HEX.ps1", initialize)
-        self.assertRegex(initialize, r"(?i)exit\s+\$LASTEXITCODE")
-        self.assertRegex(initialize, r"(?i)DANGER")
-        self.assertRegex(initialize, r"(?i)DISABLE[^\r\n]*DOES NOT STOP[^\r\n]*JOG")
-        self.assertRegex(initialize, r"(?i)(?:RESET|POWER-OFF|RECONFIGUR)[^\r\n]*STOP")
-
-    def test_ack_ok_and_status_must_agree(self) -> None:
-        for ok, status in (
-            (True, protocol.StatusCode.BUSY),
-            (False, protocol.StatusCode.OK),
-            (False, protocol.StatusCode.PARTIAL),
-        ):
-            with self.subTest(ok=ok, status=status):
-                self.assertRejected(
-                    _ordinary_request(),
-                    _ordinary_ack(ok=ok, status=status),
-                    r"(?i)ACK ok/status mismatch",
-                )
-
-    def test_ack_command_must_match_request_opcode(self) -> None:
-        response = _ordinary_ack(command=int(protocol.CommandId.DISABLE))
-
-        self.assertRejected(_ordinary_request(), response, r"(?i)ACK command mismatch")
-
-    def test_host_ack_payload_must_be_exactly_eight_bytes(self) -> None:
-        request = _ordinary_request()
-        for payload_length in (7, 9):
-            with self.subTest(payload_length=payload_length):
-                response = protocol.encode_frame(
-                    frame_type=protocol.FrameType.HOST_ACK,
-                    seq=0,
-                    timestamp_tick=0,
-                    payload=bytes(payload_length),
-                )
-                self.assertRejected(request, response, r"(?i)HOST_ACK payload length")
-
-    def test_response_crc_and_zeroed_envelope_fields_are_enforced(self) -> None:
-        request = _ordinary_request()
-        ack = _ordinary_ack()
-        bad_crc = bytearray(ack)
-        bad_crc[-1] ^= 0x01
-        cases = (
-            (bytes(bad_crc), r"(?i)Response CRC mismatch"),
-            (_with_recomputed_crc(ack, offset=5, value=1), r"(?i)Response envelope mismatch.*seq"),
-            (_with_recomputed_crc(ack, offset=9, value=1), r"(?i)Response envelope mismatch.*timestamp"),
-            (_with_recomputed_crc(ack, offset=3, value=5), r"(?i)Response envelope mismatch.*profile"),
-        )
-        for response, pattern in cases:
-            with self.subTest(pattern=pattern):
-                self.assertRejected(request, response, pattern)
-
-    def test_ordinary_response_rejects_missing_extra_and_out_of_order_frames(self) -> None:
-        request = _ordinary_request()
-        ack = _ordinary_ack()
-        _, _, status = _motor_status_pair()
-        cases = (
-            (b"", r"(?i)missing HOST_ACK"),
-            (ack + status, r"(?i)exactly one HOST_ACK"),
-            (status + ack, r"(?i)first response is not HOST_ACK"),
-        )
-        for response, pattern in cases:
-            with self.subTest(pattern=pattern):
-                self.assertRejected(request, response, pattern)
-
-    def test_get_motor_status_accepts_exact_ack_then_ten_byte_status(self) -> None:
-        request, ack, status = _motor_status_pair()
-
-        completed = _invoke_parser(request, ack + status)
-
-        self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
-        result = json.loads(completed.stdout)
-        self.assertEqual(result["request_opcode"], "0x37")
-        self.assertEqual(result["ack"]["response_type"], "0x12")
-        self.assertEqual(
-            [frame["type"] for frame in result["frames"]],
-            ["0x06", "0x12"],
-        )
-        self.assertEqual(result["frames"][1]["payload_length"], 10)
-
-    def test_get_motor_status_rejects_missing_extra_out_of_order_or_bad_length(self) -> None:
-        request, ack, status = _motor_status_pair()
-        short_status = protocol.encode_frame(
-            frame_type=protocol.FrameType.MOTION_STATUS,
-            seq=0,
-            timestamp_tick=0,
-            payload=bytes(9),
-        )
-        cases = (
-            (ack, r"(?i)exactly HOST_ACK then MOTION_STATUS"),
-            (status + ack, r"(?i)first response is not HOST_ACK"),
-            (ack + status + status, r"(?i)exactly HOST_ACK then MOTION_STATUS"),
-            (ack + short_status, r"(?i)MOTION_STATUS payload length"),
-        )
-        for response, pattern in cases:
-            with self.subTest(pattern=pattern):
-                self.assertRejected(request, response, pattern)
-
-    def test_jog_response_timeout_is_fixed_and_does_not_wait_for_total_steps(self) -> None:
-        cases = (
-            (1, 3000),
-            (800, 3000),
-            (1001, 3000),
-            (65535, 3000),
-        )
-        for steps, expected_timeout_ms in cases:
-            with self.subTest(steps=steps):
-                request = protocol.build_motor_jog(
-                    axis=1,
-                    raw_dir=0 if steps != 65535 else 1,
-                    speed_code=3 if steps != 65535 else 2,
-                    steps=steps,
-                )
-                if steps in FROZEN_JOG_HEX:
-                    self.assertEqual(request.hex().upper(), FROZEN_JOG_HEX[steps])
-                protocol.decode_frame(request)
-
-                completed = _invoke_timeout_policy(request)
-
-                self.assertEqual(
-                    completed.returncode,
-                    0,
-                    completed.stdout + completed.stderr,
-                )
-                result = json.loads(completed.stdout)
-                self.assertEqual(result["timeout_ms"], expected_timeout_ms)
-                self.assertEqual(result["request_hex_before"], request.hex().upper())
-                self.assertEqual(result["request_hex_after"], request.hex().upper())
-
-    def test_jog_response_timeout_preserves_larger_operator_override(self) -> None:
-        request = bytes.fromhex(FROZEN_JOG_HEX[800])
-
-        completed = _invoke_timeout_policy(request, requested_timeout_ms=90000)
-
-        self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
-        result = json.loads(completed.stdout)
-        self.assertEqual(result["timeout_ms"], 90000)
-        self.assertEqual(result["request_hex_after"], FROZEN_JOG_HEX[800])
-
-    def test_snapshot_xy_noop_uses_the_requested_timeout_without_motion_extension(self) -> None:
-        request = protocol.build_output_snapshot(
-            ptc_percent=(0,) * 24,
-            fan_percent=(30,) * 4,
-            solenoid=0,
-            xyz=(100, 100, 0),
-        )
-        self.assertEqual(request.hex().upper(), FROZEN_SNAPSHOT_XY_IGNORED_HEX)
-        protocol.decode_frame(request)
-
-        for requested_timeout_ms in (1, 750, 3000, 5000):
-            with self.subTest(requested_timeout_ms=requested_timeout_ms):
-                completed = _invoke_timeout_policy(
-                    request,
-                    requested_timeout_ms=requested_timeout_ms,
-                )
-                self.assertEqual(
-                    completed.returncode,
-                    0,
-                    completed.stdout + completed.stderr,
-                )
-                result = json.loads(completed.stdout)
-                self.assertEqual(result["timeout_ms"], requested_timeout_ms)
-                self.assertEqual(
-                    result["request_hex_after"],
-                    FROZEN_SNAPSHOT_XY_IGNORED_HEX,
-                )
-
-    def test_runtime_deadline_uses_request_aware_timeout_policy(self) -> None:
-        source = SEND_HEX.read_text(encoding="utf-8", errors="strict")
-        runtime = source.split(RUNTIME_MARKER, 1)[1]
-
-        self.assertIn("Get-ResponseTimeoutMs", runtime)
-        self.assertNotRegex(runtime, r"AddMilliseconds\(\s*\$TimeoutMs\s*\)")
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 176
tests/unit/test_prod2u_p4_td_cdc_structure.py

@@ -1,176 +0,0 @@
-#!/usr/bin/env python3
-"""CDC and sequential motion-phase contracts for the minimal axis executors."""
-
-from __future__ import annotations
-
-import json
-import re
-import unittest
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[2]
-AXIS = ROOT / "src" / "rtl" / "prod2u_p4_axis_executor.v"
-SYN = ROOT / "td" / "syn" / "prod2u_p4_normal_v3.tcl"
-PHY = ROOT / "td" / "phy" / "prod2u_p4_normal_v3.tcl"
-I2C = ROOT / "src" / "rtl" / "prod2u_p4_i2c_stop_start_read.v"
-TD_RECEIPT_SCHEMA = (
-    ROOT / "schemas" / "prod2u_p4_normal_v3_td_build_receipt.schema.json"
-)
-
-
-class Prod2UP4TdCdcStructureTests(unittest.TestCase):
-    def test_temperature_i2c_marks_both_two_stage_synchronizers_for_td(self) -> None:
-        source = I2C.read_text(encoding="ascii")
-
-        self.assertIn(
-            '(* async_reg = "true" *) reg [1:0] scl_sync;',
-            source,
-        )
-        self.assertIn(
-            '(* async_reg = "true" *) reg [1:0] sda_sync;',
-            source,
-        )
-
-    def test_limit_inputs_have_no_axis_synchronizer_or_hub_connection(self) -> None:
-        axis = AXIS.read_text(encoding="ascii")
-        hub = (ROOT / "src" / "rtl" / "prod2u_p4_motor_hub.v").read_text(encoding="ascii")
-
-        self.assertNotIn("limit_sync_pipe", axis)
-        self.assertNotRegex(axis, r"\blimit_raw\b")
-        self.assertEqual(hub.count(") u_x_axis ("), 1)
-        self.assertEqual(hub.count(") u_y_axis ("), 1)
-        self.assertNotIn("limit_sync_pipe", hub)
-        self.assertNotRegex(hub, r"\b(?:x_limit_raw|y_limit_raw|limit_raw)\b")
-        self.assertFalse((ROOT / "src" / "rtl" / "prod2u_p4_limit_filter.v").exists())
-
-    def test_motion_phase_has_exact_four_state_sequential_encoding(self) -> None:
-        axis = AXIS.read_text(encoding="ascii")
-        expected = {
-            "PHASE_IDLE": 0,
-            "PHASE_DIR_SETUP": 1,
-            "PHASE_STEP_HIGH": 2,
-            "PHASE_STEP_LOW": 3,
-        }
-        observed = {
-            name: int(value)
-            for name, value in re.findall(
-                r"localparam \[1:0\] (PHASE_[A-Z_]+) = 2'd([0-3]);",
-                axis,
-            )
-        }
-
-        self.assertEqual(observed, expected)
-        self.assertIn(
-            '(* keep = "true", syn_encoding = "sequential", fsm_encoding = "none" *)',
-            axis,
-        )
-        self.assertRegex(axis, r"reg \[1:0\] motion_phase;")
-
-    def test_syn_and_phy_track_uart_and_temperature_cdc_registers(self) -> None:
-        expected_groups = {
-            "u_uart_rx/rx_sync_pipe[0] {{u_uart_rx/rx_sync_pipe[0]} {*/u_uart_rx/rx_sync_pipe[0]}}",
-            "u_uart_rx/rx_sync_pipe[1] {{u_uart_rx/rx_sync_pipe[1]} {*/u_uart_rx/rx_sync_pipe[1]}}",
-            "u_temperature_i2c/scl_sync[0] {{u_temperature_i2c/scl_sync[0]} {*/u_temperature_i2c/scl_sync[0]}}",
-            "u_temperature_i2c/scl_sync[1] {{u_temperature_i2c/scl_sync[1]} {*/u_temperature_i2c/scl_sync[1]}}",
-            "u_temperature_i2c/sda_sync[0] {{u_temperature_i2c/sda_sync[0]} {*/u_temperature_i2c/sda_sync[0]}}",
-            "u_temperature_i2c/sda_sync[1] {{u_temperature_i2c/sda_sync[1]} {*/u_temperature_i2c/sda_sync[1]}}",
-        }
-        for path in (SYN, PHY):
-            source = path.read_text(encoding="ascii")
-            block = source.split("set cdc_groups {", 1)[1].split("\n}", 1)[0]
-            observed = {line.strip() for line in block.splitlines() if line.strip()}
-            with self.subTest(path=path.name):
-                self.assertEqual(observed, expected_groups)
-                self.assertIn("proc p4_find_unique_regs {patterns}", source)
-                self.assertIn("lsearch -exact $matches $reg", source)
-                self.assertIn("if {[llength $cdc_regs] != 6}", source)
-                self.assertIn('puts $cdc_report "retained_sync_register=$normalized"', source)
-                self.assertNotIn("limit_sync_pipe", source)
-
-    def test_each_async_input_is_false_pathed_only_to_its_first_stage(self) -> None:
-        expected_pairs = {
-            "host_uart_rx u_uart_rx/rx_sync_pipe[0]",
-            "temp_scl u_temperature_i2c/scl_sync[0]",
-            "temp_sda u_temperature_i2c/sda_sync[0]",
-        }
-        for path in (SYN, PHY):
-            source = path.read_text(encoding="ascii")
-            block = source.split("set cdc_input_pairs {", 1)[1].split("}", 1)[0]
-            observed = {line.strip() for line in block.splitlines() if line.strip()}
-            with self.subTest(path=path.name):
-                self.assertEqual(observed, expected_pairs)
-                self.assertEqual(source.count("set_false_path -from"), 1)
-                self.assertIn("set_false_path -from $source -to $endpoint", source)
-                self.assertNotIn("set_false_path -from $source\n", source)
-                self.assertIn('puts $cdc_report "false_path_endpoint=$normalized"', source)
-                self.assertNotIn("x_limit_raw", source)
-                self.assertNotIn("y_limit_raw", source)
-
-    def test_td_structure_discovery_fails_closed(self) -> None:
-        for path in (SYN, PHY):
-            source = path.read_text(encoding="ascii")
-            with self.subTest(path=path.name):
-                self.assertIn("structural_failure=", source)
-                self.assertIn("set_false_path -from $source -to $endpoint", source)
-                self.assertLess(
-                    source.index("set cdc_report [open"),
-                    source.index("foreach {normalized patterns} $cdc_groups"),
-                )
-                self.assertIn("CDC_GATE_FAIL=", source)
-                self.assertIn("FSM_ENCODING_GATE_FAIL=", source)
-                self.assertIn(
-                    'error "PROD2U_P4_NORMAL_V3_CDC_GATE_FAIL:[join $cdc_failures ,]"',
-                    source,
-                )
-                self.assertIn(
-                    'error "PROD2U_P4_NORMAL_V3_FSM_ENCODING_GATE_FAIL:[join $fsm_failures ,]"',
-                    source,
-                )
-                self.assertNotIn("CDC_GATE_ADVISORY_FAIL=", source)
-                self.assertNotIn("FSM_ENCODING_GATE_ADVISORY_FAIL=", source)
-
-    def test_td_receipt_schema_matches_all_cdc_and_two_bit_axes(self) -> None:
-        schema = json.loads(TD_RECEIPT_SCHEMA.read_text(encoding="utf-8"))
-        structural = schema["$defs"]["structuralGate"]["properties"]
-        cdc = structural["cdc"]["properties"]
-        fsm = structural["fsm_encoding"]["properties"]
-
-        self.assertEqual(cdc["async_reg"]["properties"]["used"]["const"], 6)
-        self.assertEqual(cdc["input_registers"]["properties"]["used"]["const"], 0)
-        self.assertEqual(
-            cdc["retained_sync_registers"]["properties"]["used"]["const"],
-            6,
-        )
-        self.assertEqual(
-            cdc["first_stage_endpoints"]["properties"]["used"]["const"],
-            3,
-        )
-        self.assertEqual(fsm["axes"]["const"], {"x": 2, "y": 2})
-
-    def test_td_reports_x_and_y_two_bit_sequential_motion_phase(self) -> None:
-        for path in (SYN, PHY):
-            source = path.read_text(encoding="ascii")
-            with self.subTest(path=path.name):
-                self.assertIn("schema=prod2u-p4-normal-v3-fsm-encoding-v2", source)
-                self.assertIn(
-                    "x {{u_core/u_motors/u_x_axis/motion_phase*} {*/u_core/u_motors/u_x_axis/motion_phase*}}",
-                    source,
-                )
-                self.assertIn(
-                    "y {{u_core/u_motors/u_y_axis/motion_phase*} {*/u_core/u_motors/u_y_axis/motion_phase*}}",
-                    source,
-                )
-                self.assertIn("(u_core/u_motors/u_%s_axis/motion_phase\\[[0-1]\\])$", source)
-                self.assertNotIn("/motion_phase\\[[0-2]\\]$", source)
-                self.assertIn("lsearch -exact $normalized_matches $normalized", source)
-                self.assertIn(
-                    "if {[llength $matches] != 2 || "
-                    "[llength $normalized_matches] != 2}",
-                    source,
-                )
-                self.assertIn("motion_phase=${axis}:[llength $matches]:sequential", source)
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 200
tests/unit/test_prod2u_p4_temperature_contract.py

@@ -1,200 +0,0 @@
-#!/usr/bin/env python3
-"""Wire-contract tests for the on-demand CT7428 temperature response."""
-
-from __future__ import annotations
-
-import json
-import re
-from pathlib import Path
-
-import pytest
-
-from tools import prod2u_p4_protocol as protocol
-
-
-ROOT = Path(__file__).resolve().parents[2]
-HOST_CONTRACT = ROOT / "config" / "prod2u_p4_normal_host_contract_v4.json"
-HOST_SCHEMA = ROOT / "schemas" / "prod2u_p4_normal_host_contract_v4.schema.json"
-
-GOLDEN_REQUEST = bytes.fromhex(
-    "A55A020405000000000000000004280000009E0C"
-)
-GOLDEN_RESPONSE = bytes.fromhex(
-    "A55A0204101B"
-    "000102030405060708090A0B0C0D0E0F101112131415161718191A"
-    "1FC9"
-)
-ALL_FF_RESPONSE = bytes.fromhex(
-    "A55A0204101B"
-    "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"
-    "1BC4"
-)
-
-
-def test_get_temperatures_request_matches_the_frozen_wire_frame() -> None:
-    assert protocol.CommandId.GET_TEMPERATURES == 0x28
-    assert protocol.build_get_temperatures() == GOLDEN_REQUEST
-
-    decoded = protocol.decode_frame(GOLDEN_REQUEST)
-    assert decoded.frame_type == protocol.FrameType.HOST_CMD
-    assert decoded.payload == bytes.fromhex("28000000")
-
-
-def test_temperature_response_matches_the_frozen_35_byte_frame() -> None:
-    values = bytes(range(27))
-
-    response = protocol.build_temperature_response(values)
-
-    assert response == GOLDEN_RESPONSE
-    assert len(response) == 35
-    assert response[:6] == bytes.fromhex("A55A0204101B")
-    assert response[6:33] == values
-    assert response[-2:] == protocol.crc16_ccitt(response[2:-2]).to_bytes(
-        2, "little"
-    )
-
-
-def test_temperature_response_all_ff_frame_matches_the_frozen_crc() -> None:
-    response = protocol.build_temperature_response(bytes([0xFF] * 27))
-
-    assert response == ALL_FF_RESPONSE
-    assert response[-2:] == bytes.fromhex("1BC4")
-
-
-def test_temperature_response_decoder_accepts_only_the_compact_wire_contract() -> None:
-    assert protocol.decode_temperature_response(GOLDEN_RESPONSE) == bytes(range(27))
-
-    for invalid in (
-        GOLDEN_RESPONSE[:-1],
-        GOLDEN_RESPONSE[:4] + b"\x11" + GOLDEN_RESPONSE[5:],
-        GOLDEN_RESPONSE[:-1] + bytes([GOLDEN_RESPONSE[-1] ^ 0x01]),
-    ):
-        with pytest.raises(protocol.P4FrameError):
-            protocol.decode_temperature_response(invalid)
-
-
-def test_temperature_bus_error_ack_decodes_as_status_0x0a() -> None:
-    wire = protocol.encode_frame(
-        frame_type=protocol.FrameType.HOST_ACK,
-        seq=0,
-        timestamp_tick=0,
-        payload=bytes.fromhex("00280A0000000000"),
-    )
-
-    ack = protocol.decode_host_ack(protocol.decode_frame(wire))
-
-    assert ack.command == protocol.CommandId.GET_TEMPERATURES
-    assert ack.status == protocol.StatusCode.TEMPERATURE_BUS_ERROR
-
-
-def test_machine_contract_freezes_temperature_request_response_and_failures() -> None:
-    contract = json.loads(HOST_CONTRACT.read_text(encoding="utf-8"))
-    command = contract["commands"]["get_temperatures"]
-    response = contract["responses"]["temperature_short"]
-
-    assert contract["frame_types"]["TEMPERATURE_SHORT"] == 0x10
-    assert contract["wire"]["temperature_response_order"] == [
-        "TEMPERATURE_SHORT"
-    ]
-    assert command == {
-        "frame_type": 5,
-        "command": 0x28,
-        "payload_length": 4,
-        "request_payload_hex": "28 00 00 00",
-        "success_response": "TEMPERATURE_SHORT_ONLY_NO_ACK",
-        "powerup_under_one_second": "ALL_FF_NO_I2C",
-        "nack_policy": "CURRENT_VALUE_FF_CONTINUE",
-        "bus_error_status": "TEMPERATURE_BUS_ERROR",
-        "bus_error_status_code": 0x0A,
-        "read_order": ["U6", "U24", "U25"],
-        "addresses": [0x49, 0x48, 0x4B],
-        "registers": list(range(9)),
-    }
-    assert response["frame_type"] == 0x10
-    assert response["payload_length"] == 27
-    assert response["full_frame_length"] == 35
-    assert response["layout"] == "A5 5A 02 04 10 1B values[27] crc16_le"
-    assert response["crc_coverage"] == "02 04 10 1B values[27]"
-    assert response["value_order"] == [
-        "U6.local",
-        "U6.remote1..8",
-        "U24.local",
-        "U24.remote1..8",
-        "U25.local",
-        "U25.remote1..8",
-    ]
-    assert contract["responses"]["host_ack"]["status_codes"][
-        "TEMPERATURE_BUS_ERROR"
-    ] == 0x0A
-
-
-def test_machine_schema_requires_temperature_contract_sections() -> None:
-    schema = json.loads(HOST_SCHEMA.read_text(encoding="utf-8"))
-
-    assert "get_temperatures" in schema["properties"]["commands"]["required"]
-    assert "temperature_short" in schema["properties"]["responses"]["required"]
-    assert schema["properties"]["frame_types"]["const"][
-        "TEMPERATURE_SHORT"
-    ] == 0x10
-    temperature_def = schema["$defs"]["temperatureCommand"]
-    assert temperature_def["properties"]["command"]["const"] == 0x28
-    assert temperature_def["properties"]["bus_error_status_code"]["const"] == 0x0A
-
-
-@pytest.mark.parametrize(
-    ("relative", "declaration"),
-    [
-        ("src/rtl/prod2u_p4_normal_v3_core.v", r"reg\s+\[2:0\]\s+state"),
-        ("src/rtl/prod2u_p4_i2c_stop_start_read.v", r"reg\s+\[4:0\]\s+state"),
-        ("src/rtl/prod2u_p4_temperature_read.v", r"reg\s+\[1:0\]\s+state"),
-        ("src/rtl/prod2u_p4_temperature_short_tx.v", r"reg\s+\[1:0\]\s+state"),
-        ("src/rtl/prod2u_p4_normal_v3_tx.v", r"reg\s+\[1:0\]\s+owner"),
-    ],
-)
-def test_temperature_path_uses_compact_fsm_encoding(
-    relative: str,
-    declaration: str,
-) -> None:
-    source = (ROOT / relative).read_text(encoding="ascii")
-    pattern = (
-        r"\(\*\s*keep\s*=\s*\"true\"\s*,\s*"
-        r"syn_encoding\s*=\s*\"sequential\"\s*,\s*"
-        r"fsm_encoding\s*=\s*\"none\"\s*\*\)\s*"
-        + declaration
-    )
-
-    assert re.search(pattern, source)
-
-
-def test_temperature_store_is_single_block_ram_candidate() -> None:
-    source = (ROOT / "src/rtl/prod2u_p4_temperature_store.v").read_text(
-        encoding="ascii"
-    )
-
-    assert "EF2_LOGIC_BRAM #(\n" in source
-    assert '.IMPLEMENT    ("9K")' in source
-    assert "// synthesis translate_off" in source
-    assert "module prod2u_p4_temperature_bram_sim" in source
-
-
-def test_temperature_store_formal_only_constrains_valid_read_data() -> None:
-    source = (
-        ROOT / "tests/formal/prod2u_p4_temperature_store_contract_formal.v"
-    ).read_text(encoding="ascii")
-
-    assert "$past(!rd_req)" not in source
-    assert "$stable(rd_data)" not in source
-
-
-@pytest.mark.parametrize(
-    "values",
-    [
-        bytes(26),
-        bytes(28),
-        [0] * 26 + [256],
-        [0] * 26 + [-1],
-    ],
-)
-def test_temperature_response_rejects_non_27_byte_payloads(values: object) -> None:
-    with pytest.raises(ValueError):
-        protocol.build_temperature_response(values)

+ 0 - 88
tests/unit/test_prod2u_p4_wrapper_v3.py

@@ -1,88 +0,0 @@
-#!/usr/bin/env python3
-"""Static routing contracts for the minimal package PowerShell wrappers."""
-
-from __future__ import annotations
-
-import re
-import subprocess
-import unittest
-from pathlib import Path
-
-
-ROOT = Path(__file__).resolve().parents[2]
-TEMPLATES = ROOT / "tools" / "package_templates"
-DISABLE_HEX = "A55A02040500000000000000000426000000C4AE"
-
-
-class Prod2UP4WrapperV3Tests(unittest.TestCase):
-    def test_run_wrapper_exposes_only_four_package_operations(self) -> None:
-        source = (TEMPLATES / "run.ps1").read_text(encoding="utf-8")
-        validate_set = re.search(r'\[ValidateSet\((.*?)\)\]', source, flags=re.DOTALL)
-        self.assertIsNotNone(validate_set)
-        commands = set(re.findall(r'"([^"]+)"', validate_set.group(1)))
-
-        self.assertEqual(
-            commands,
-            {"selftest", "send-hex", "initialize-disable", "program-sram"},
-        )
-        for retired in (
-            "normal-actuator-trace-gate",
-            "set-all-outputs",
-            "jog",
-            "mark-closed",
-            "read-temperatures",
-        ):
-            self.assertNotIn(f'"{retired}"', source)
-
-    def test_run_wrapper_rejects_direct_motion_before_any_child_script(self) -> None:
-        completed = subprocess.run(
-            [
-                "powershell.exe",
-                "-NoProfile",
-                "-ExecutionPolicy",
-                "Bypass",
-                "-File",
-                str(TEMPLATES / "run.ps1"),
-                "jog",
-            ],
-            cwd=ROOT,
-            capture_output=True,
-            text=True,
-            check=False,
-        )
-
-        self.assertNotEqual(completed.returncode, 0)
-        self.assertIn("ValidateSet", completed.stderr + completed.stdout)
-
-    def test_initialize_disable_uses_the_frozen_request_through_send_hex(self) -> None:
-        source = (TEMPLATES / "INITIALIZE_DISABLE.ps1").read_text(encoding="utf-8")
-        compact = re.sub(r"\s+", "", source).upper()
-
-        self.assertIn("SEND_HEX.PS1", compact)
-        self.assertIn(DISABLE_HEX, compact)
-        self.assertIn('"COM5"', source)
-        self.assertIn("921600", source)
-
-    def test_programmer_is_one_attempt_sram_only_at_200_khz(self) -> None:
-        source = (TEMPLATES / "PROGRAM_SRAM.ps1").read_text(encoding="utf-8")
-
-        self.assertIn('[ValidateSet("PROGRAM_SRAM")]', source)
-        self.assertEqual(source.count("download -bit"), 1)
-        self.assertIn("-mode jtag -spd 2", source)
-        self.assertIn("attempt_count = 1", source)
-        self.assertIn("speed_hz = 200000", source)
-        self.assertIn("no retry was attempted", source)
-        self.assertIn("$info.commit -cnotmatch '^[0-9a-f]{8}$'", source)
-        self.assertIn('$stage = Join-Path "C:\\P2U" ([string]$info.commit)', source)
-        self.assertNotRegex(source, r"(?i)build[_-]?id")
-        for forbidden in (
-            "PROGRAM_FLASH",
-            "ERASE_FLASH",
-            "PROGRAM_SPIBIN",
-            "DIRECT_FLASH_WRITE",
-        ):
-            self.assertNotIn(forbidden, source)
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 751
tools/prod2u_p4_cli.py

@@ -1,751 +0,0 @@
-#!/usr/bin/env python3
-"""Minimal ACK-only host tooling for Prod2U Profile 4 binary921-v3."""
-
-from __future__ import annotations
-
-import argparse
-import json
-import re
-import subprocess
-import threading
-import time
-from dataclasses import dataclass
-from pathlib import Path
-from typing import Any, Callable
-
-from prod2u_p4_protocol import (
-    CRC_LEN,
-    HEADER_LEN,
-    MAGIC,
-    CommandId,
-    FrameType,
-    HostAck,
-    MotionOpcode,
-    MotionStatus,
-    P4Frame,
-    P4FrameError,
-    StatusCode,
-    build_get_motor_status,
-    build_host_command,
-    build_motor_jog,
-    build_output_snapshot,
-    decode_frame,
-    decode_host_ack,
-    decode_motion_status,
-    state_hash16,
-)
-
-
-PROFILE = "prod2u-p4-normal-actuator-binary921-v3"
-PROFILE_ID = 4
-PROTOCOL_VERSION = 2
-PORT = "COM5"
-BAUD = 921600
-SAFE_STATE_HASH16 = state_hash16(
-    ptc_percent=(0,) * 24,
-    fan_percent=(30,) * 4,
-    solenoid=0,
-)
-
-
-@dataclass(frozen=True)
-class CommandResult:
-    ack: HostAck
-    raw_response: bytes
-    frames: tuple[P4Frame, ...]
-
-
-@dataclass(frozen=True)
-class MotorStatusResult:
-    ack: HostAck
-    status: MotionStatus
-    raw_response: bytes
-
-
-def open_com5(serial_factory: Callable[[], Any] | None = None) -> Any:
-    if serial_factory is None:
-        try:
-            import serial  # type: ignore
-        except ImportError as exc:
-            raise RuntimeError("pyserial is required for live Profile 4 operation") from exc
-        serial_factory = serial.Serial
-    endpoint = serial_factory()
-    endpoint.port = PORT
-    endpoint.baudrate = BAUD
-    endpoint.bytesize = 8
-    endpoint.parity = "N"
-    endpoint.stopbits = 1
-    endpoint.timeout = 0
-    endpoint.write_timeout = 1
-    endpoint.dtr = False
-    endpoint.rts = False
-    if not getattr(endpoint, "is_open", False):
-        endpoint.open()
-    endpoint.dtr = False
-    endpoint.rts = False
-    return endpoint
-
-
-class NormalSession:
-    """One-outstanding-command UART session with one DISABLE fallback."""
-
-    def __init__(
-        self,
-        endpoint: Any,
-        *,
-        timeout_seconds: float = 0.25,
-        quiet_window_seconds: float = 0.010,
-        max_quiet_drain_seconds: float = 0.050,
-        monotonic: Callable[[], float] = time.monotonic,
-        sleep: Callable[[float], None] = time.sleep,
-    ) -> None:
-        if timeout_seconds <= 0:
-            raise ValueError("timeout_seconds must be positive")
-        if quiet_window_seconds <= 0:
-            raise ValueError("quiet_window_seconds must be positive")
-        if max_quiet_drain_seconds < quiet_window_seconds:
-            raise ValueError("max_quiet_drain_seconds must cover the quiet window")
-        self.endpoint = endpoint
-        self.timeout_seconds = timeout_seconds
-        self.quiet_window_seconds = quiet_window_seconds
-        self.max_quiet_drain_seconds = max_quiet_drain_seconds
-        self.disable_attempted = False
-        self._terminated = False
-        self._command_lock = threading.Lock()
-        self._rx_buffer = bytearray()
-        self._rx_journal = bytearray()
-        self._last_exchange: dict[str, Any] | None = None
-        self._best_effort_disable_exchange: dict[str, Any] | None = None
-        self._monotonic = monotonic
-        self._sleep = sleep
-
-    @property
-    def rx_journal(self) -> bytes:
-        return bytes(self._rx_journal)
-
-    @property
-    def last_exchange(self) -> dict[str, Any] | None:
-        return None if self._last_exchange is None else dict(self._last_exchange)
-
-    @property
-    def best_effort_disable_exchange(self) -> dict[str, Any] | None:
-        return (
-            None
-            if self._best_effort_disable_exchange is None
-            else dict(self._best_effort_disable_exchange)
-        )
-
-    def close(self) -> None:
-        close = getattr(self.endpoint, "close", None)
-        if callable(close):
-            close()
-
-    def _write_exact(self, data: bytes) -> None:
-        written = self.endpoint.write(data)
-        if written != len(data):
-            raise IOError(f"short serial write: expected {len(data)}, got {written}")
-
-    def _read_frame(self, *, deadline: float) -> P4Frame:
-        while self._monotonic() < deadline:
-            if len(self._rx_buffer) >= HEADER_LEN + CRC_LEN:
-                if self._rx_buffer[:2] != MAGIC:
-                    raise RuntimeError("unexpected bytes before Profile 4 response")
-                frame_length = HEADER_LEN + self._rx_buffer[13] + CRC_LEN
-                if len(self._rx_buffer) >= frame_length:
-                    raw = bytes(self._rx_buffer[:frame_length])
-                    del self._rx_buffer[:frame_length]
-                    try:
-                        return decode_frame(raw)
-                    except P4FrameError as exc:
-                        raise RuntimeError(f"invalid Profile 4 response: {exc}") from exc
-            chunk = bytes(self.endpoint.read(256))
-            if chunk:
-                self._rx_buffer.extend(chunk)
-                self._rx_journal.extend(chunk)
-                continue
-            self._sleep(0.0005)
-        raise TimeoutError("ACK timeout")
-
-    def _attempt_disable(self) -> None:
-        if self.disable_attempted:
-            return
-        self.disable_attempted = True
-        request = build_host_command(command=CommandId.DISABLE)
-        try:
-            self._write_exact(request)
-            self._best_effort_disable_exchange = {"request_hex": request.hex()}
-        except Exception as exc:  # pragma: no cover - best effort only
-            self._best_effort_disable_exchange = {
-                "request_hex": request.hex(),
-                "error": str(exc),
-            }
-
-    def _require_quiet_tail(self) -> None:
-        if self._rx_buffer:
-            raise RuntimeError("unexpected bytes after completed response")
-        started = self._monotonic()
-        quiet_deadline = started + self.quiet_window_seconds
-        hard_deadline = started + self.max_quiet_drain_seconds
-        while self._monotonic() < quiet_deadline and self._monotonic() < hard_deadline:
-            chunk = bytes(self.endpoint.read(256))
-            if chunk:
-                self._rx_journal.extend(chunk)
-                raise RuntimeError("unexpected bytes after completed response")
-            self._sleep(0.0005)
-
-    def _fail(self, expected_command: CommandId | int, message: str) -> None:
-        self._terminated = True
-        if int(expected_command) == int(CommandId.DISABLE):
-            self.disable_attempted = True
-        else:
-            self._attempt_disable()
-        self._rx_buffer.clear()
-        raise RuntimeError(message)
-
-    def collect_available(self) -> bytes:
-        collected = bytearray()
-        while True:
-            chunk = bytes(self.endpoint.read(256))
-            if not chunk:
-                break
-            collected.extend(chunk)
-            self._rx_journal.extend(chunk)
-        return bytes(collected)
-
-    def drain_unparsed(self, *, timeout_seconds: float | None = None) -> bytes:
-        duration = self.quiet_window_seconds if timeout_seconds is None else timeout_seconds
-        if duration < 0:
-            raise ValueError("timeout_seconds must be non-negative")
-        deadline = self._monotonic() + duration
-        collected = bytearray(self._rx_buffer)
-        self._rx_buffer.clear()
-        while self._monotonic() < deadline:
-            chunk = bytes(self.endpoint.read(256))
-            if chunk:
-                collected.extend(chunk)
-                self._rx_journal.extend(chunk)
-                deadline = self._monotonic() + self.quiet_window_seconds
-            else:
-                self._sleep(0.0005)
-        return bytes(collected)
-
-    @staticmethod
-    def _validate_ack(
-        ack: HostAck,
-        *,
-        expected_command: CommandId | MotionOpcode | int,
-        allowed_statuses: tuple[StatusCode, ...],
-        expected_detail: int | None,
-        expected_state_hash16: int | None,
-        expected_response_type: FrameType | int,
-        required_result_flags: int,
-        allowed_result_flags: int,
-    ) -> None:
-        if int(ack.command) != int(expected_command):
-            raise RuntimeError("ACK command mismatch")
-        if ack.status not in allowed_statuses:
-            raise RuntimeError(f"unexpected ACK status: {ack.status.name}")
-        expected_ok = ack.status in (StatusCode.OK, StatusCode.PARTIAL)
-        if ack.ok != expected_ok:
-            raise RuntimeError("ACK ok/status mismatch")
-        if expected_detail is not None and ack.detail != expected_detail:
-            raise RuntimeError("ACK detail mismatch")
-        if expected_state_hash16 is not None and ack.state_hash16 != expected_state_hash16:
-            raise RuntimeError("ACK state hash mismatch")
-        if int(ack.response_type) != int(expected_response_type):
-            raise RuntimeError("ACK response type mismatch")
-        if ack.result_flags & ~allowed_result_flags:
-            raise RuntimeError("ACK contains disallowed result flags")
-        if ack.result_flags & required_result_flags != required_result_flags:
-            raise RuntimeError("ACK is missing required result flags")
-
-    def _begin(self) -> None:
-        if self._terminated:
-            raise RuntimeError("session is terminated")
-        if not self._command_lock.acquire(blocking=False):
-            raise RuntimeError("only one outstanding command is allowed")
-
-    def _abort(self, expected_command: CommandId | MotionOpcode | int) -> None:
-        self._terminated = True
-        if int(expected_command) == int(CommandId.DISABLE):
-            self.disable_attempted = True
-        else:
-            self._attempt_disable()
-
-    def command(
-        self,
-        request: bytes,
-        *,
-        expected_command: CommandId | MotionOpcode | int,
-        allowed_statuses: tuple[StatusCode, ...] = (StatusCode.OK, StatusCode.PARTIAL),
-        expected_detail: int | None = None,
-        expected_state_hash16: int | None = None,
-        required_result_flags: int = 0,
-        allowed_result_flags: int = 0xFF,
-    ) -> CommandResult:
-        self._begin()
-        try:
-            try:
-                self._write_exact(request)
-                frame = self._read_frame(deadline=self._monotonic() + self.timeout_seconds)
-                if frame.frame_type != FrameType.HOST_ACK:
-                    raise RuntimeError("first response must be HOST_ACK")
-                try:
-                    ack = decode_host_ack(frame)
-                except ValueError as exc:
-                    raise RuntimeError(f"malformed HOST_ACK: {exc}") from exc
-                self._validate_ack(
-                    ack,
-                    expected_command=expected_command,
-                    allowed_statuses=allowed_statuses,
-                    expected_detail=expected_detail,
-                    expected_state_hash16=expected_state_hash16,
-                    expected_response_type=0,
-                    required_result_flags=required_result_flags,
-                    allowed_result_flags=allowed_result_flags,
-                )
-                self._require_quiet_tail()
-                result = CommandResult(ack=ack, raw_response=frame.raw, frames=(frame,))
-                self._last_exchange = {
-                    "request_hex": request.hex(),
-                    "response_hex": frame.raw.hex(),
-                }
-                return result
-            except BaseException:
-                self._abort(expected_command)
-                raise
-        finally:
-            self._command_lock.release()
-
-    def motor_status(self) -> MotorStatusResult:
-        request = build_get_motor_status()
-        expected_command = MotionOpcode.GET_MOTOR_STATUS
-        self._begin()
-        try:
-            try:
-                self._write_exact(request)
-                deadline = self._monotonic() + self.timeout_seconds
-                ack_frame = self._read_frame(deadline=deadline)
-                if ack_frame.frame_type != FrameType.HOST_ACK:
-                    raise RuntimeError("first response must be HOST_ACK")
-                try:
-                    ack = decode_host_ack(ack_frame)
-                except ValueError as exc:
-                    raise RuntimeError(f"malformed HOST_ACK: {exc}") from exc
-                self._validate_ack(
-                    ack,
-                    expected_command=expected_command,
-                    allowed_statuses=(StatusCode.OK,),
-                    expected_detail=0,
-                    expected_state_hash16=None,
-                    expected_response_type=FrameType.MOTION_STATUS,
-                    required_result_flags=0x08,
-                    allowed_result_flags=0x08,
-                )
-                status_frame = self._read_frame(deadline=deadline)
-                if status_frame.frame_type != FrameType.MOTION_STATUS:
-                    raise RuntimeError("HOST_ACK must be followed by MOTION_STATUS")
-                try:
-                    status = decode_motion_status(status_frame)
-                except ValueError as exc:
-                    raise RuntimeError(f"malformed MOTION_STATUS: {exc}") from exc
-                self._require_quiet_tail()
-                raw = ack_frame.raw + status_frame.raw
-                self._last_exchange = {
-                    "request_hex": request.hex(),
-                    "response_hex": raw.hex(),
-                }
-                return MotorStatusResult(ack=ack, status=status, raw_response=raw)
-            except BaseException:
-                self._abort(expected_command)
-                raise
-        finally:
-            self._command_lock.release()
-
-
-def _bounded_int(minimum: int, maximum: int) -> Callable[[str], int]:
-    def parse(value: str) -> int:
-        try:
-            parsed = int(value, 10)
-        except ValueError as exc:
-            raise argparse.ArgumentTypeError("must be an integer") from exc
-        if not minimum <= parsed <= maximum:
-            raise argparse.ArgumentTypeError(f"must be from {minimum} to {maximum}")
-        return parsed
-
-    return parse
-
-
-def build_parser() -> argparse.ArgumentParser:
-    parser = argparse.ArgumentParser(description=__doc__)
-    sub = parser.add_subparsers(dest="command", required=True)
-    sub.add_parser("selftest")
-    sub.add_parser("preflight")
-
-    snapshot = sub.add_parser(
-        "set-all-outputs",
-        description=(
-            "Sets PTC, fan, and solenoid. Legacy X/Y/Z bytes remain on the wire but "
-            "accept any byte value and have no motor effect."
-        ),
-    )
-    snapshot.add_argument("--ptc", type=_bounded_int(0, 100), default=0)
-    snapshot.add_argument("--fan", type=_bounded_int(0, 100), default=30)
-    snapshot.add_argument("--solenoid", type=_bounded_int(0, 100), choices=(0, 100), default=0)
-    snapshot.add_argument("--x", type=_bounded_int(0, 255), default=0)
-    snapshot.add_argument("--y", type=_bounded_int(0, 255), default=0)
-    snapshot.add_argument("--z", type=_bounded_int(0, 255), default=0)
-
-    jog = sub.add_parser(
-        "jog",
-        description=(
-            "The only motor-driving command. Executes the full 1..65535 step field "
-            "at fixed 1000 step/s; speed_code is validated then ignored. ACK follows "
-            "the first emitted STEP."
-        ),
-    )
-    jog.add_argument("--axis", type=_bounded_int(0, 1), required=True)
-    jog.add_argument("--raw-dir", type=_bounded_int(0, 1), required=True)
-    jog.add_argument("--speed-code", type=_bounded_int(0, 3), required=True)
-    jog.add_argument("--steps", type=_bounded_int(1, 65535), required=True)
-
-    sub.add_parser("get-status")
-    sub.add_parser("motor-status")
-    sub.add_parser("disable")
-    return parser
-
-
-def _selftest() -> dict[str, Any]:
-    snapshot = build_output_snapshot(
-        ptc_percent=(0,) * 24,
-        fan_percent=(30,) * 4,
-        solenoid=0,
-        xyz=(0, 0, 0),
-    )
-    jog = build_motor_jog(axis=1, raw_dir=1, speed_code=3, steps=65535)
-    return {
-        "schema": "prod2u-p4-normal-v3-selftest-v2",
-        "status": "pass" if len(snapshot) == 50 and len(jog) == 24 else "fail",
-        "profile": PROFILE,
-        "profile_id": PROFILE_ID,
-        "protocol_version": PROTOCOL_VERSION,
-        "baud": BAUD,
-        "port": PORT,
-        "jog_request_steps_max": 65535,
-        "jog_executed_steps": "requested_u16_without_cap",
-        "jog_effective_step_rate_hz": 1000,
-        "jog_ack_semantics": "FIRST_STEP_EMITTED",
-        "hardware_opened": False,
-        "program_sram_attempted": False,
-    }
-
-
-def enumerate_hardware_candidates(
-    *,
-    runner: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
-) -> dict[str, Any]:
-    """Enumerate COM and AL-Link candidates without opening either interface."""
-    script = r"""
-$ErrorActionPreference = 'Stop'
-$cimSerialPorts = @()
-try {
-    $cimSerialPorts = @(
-        Get-CimInstance Win32_SerialPort |
-            Sort-Object DeviceID |
-            ForEach-Object {
-                [ordered]@{ name = [string]$_.Name; device_id = [string]$_.DeviceID }
-            }
-    )
-} catch {}
-$pnpSerialPorts = @()
-try {
-    if (Get-Command Get-PnpDevice -ErrorAction SilentlyContinue) {
-        $pnpSerialPorts = @(
-            Get-PnpDevice -Class Ports -PresentOnly -ErrorAction Stop |
-                Sort-Object InstanceId |
-                ForEach-Object {
-                    [ordered]@{ name = [string]$_.FriendlyName; device_id = [string]$_.InstanceId }
-                }
-        )
-    }
-} catch {}
-$dotNetSerialPorts = @()
-try {
-    $dotNetSerialPorts = @(
-        [System.IO.Ports.SerialPort]::GetPortNames() |
-            Sort-Object |
-            ForEach-Object {
-                [ordered]@{ name = [string]$_; device_id = [string]$_ }
-            }
-    )
-} catch {}
-$serialPorts = @($cimSerialPorts) + @($pnpSerialPorts) + @($dotNetSerialPorts)
-$pnpDevices = @()
-try {
-    $pnpDevices = @(
-        Get-CimInstance Win32_PnPEntity |
-            Where-Object { ([string]$_.Name) -match '(?i)AL[- ]?Link|Anlogic' } |
-            Sort-Object DeviceID |
-            ForEach-Object {
-                [ordered]@{ name = [string]$_.Name; device_id = [string]$_.DeviceID }
-            }
-    )
-} catch {}
-[ordered]@{ serial_ports = @($serialPorts); pnp_devices = @($pnpDevices) } |
-    ConvertTo-Json -Compress -Depth 4
-""".strip()
-    try:
-        completed = runner(
-            ["powershell.exe", "-NoProfile", "-Command", script],
-            capture_output=True,
-            text=True,
-            check=False,
-            timeout=20,
-        )
-    except (OSError, subprocess.TimeoutExpired) as exc:
-        return {
-            "status": "blocked_hardware_enumeration_failed",
-            "opened_com": False,
-            "opened_jtag": False,
-            "serial_ports": [],
-            "pnp_devices": [],
-            "error": str(exc),
-        }
-    if completed.returncode != 0:
-        return {
-            "status": "blocked_hardware_enumeration_failed",
-            "opened_com": False,
-            "opened_jtag": False,
-            "serial_ports": [],
-            "pnp_devices": [],
-            "error": f"PowerShell enumeration exited {completed.returncode}",
-        }
-    try:
-        payload = json.loads(completed.stdout)
-    except (TypeError, json.JSONDecodeError) as exc:
-        return {
-            "status": "blocked_hardware_enumeration_failed",
-            "opened_com": False,
-            "opened_jtag": False,
-            "serial_ports": [],
-            "pnp_devices": [],
-            "error": f"invalid enumeration JSON: {exc}",
-        }
-
-    def records(name: str) -> list[dict[str, str]]:
-        raw = payload.get(name, []) if isinstance(payload, dict) else []
-        if isinstance(raw, dict):
-            raw = [raw]
-        if not isinstance(raw, list):
-            return []
-        return [
-            {"name": str(item.get("name", "")), "device_id": str(item.get("device_id", ""))}
-            for item in raw
-            if isinstance(item, dict)
-        ]
-
-    serial_ports = records("serial_ports")
-    key_order: list[tuple[str, ...]] = []
-    best: dict[tuple[str, ...], dict[str, str]] = {}
-
-    def score(record: dict[str, str]) -> tuple[int, int, int]:
-        name = record["name"].strip()
-        device_id = record["device_id"].strip()
-        generic_name = re.fullmatch(r"COM[0-9]+", name, re.IGNORECASE) is not None
-        generic_device = re.fullmatch(r"COM[0-9]+", device_id, re.IGNORECASE) is not None
-        return (0 if generic_device else 1, 0 if generic_name else 1, len(name) + len(device_id))
-
-    for record in serial_ports:
-        combined = f"{record['name']} {record['device_id']}"
-        match = re.search(r"(?<![A-Z0-9])COM([0-9]+)(?![0-9])", combined.upper())
-        key = (
-            ("com", str(int(match.group(1))))
-            if match
-            else ("record", record["name"].casefold(), record["device_id"].casefold())
-        )
-        if key not in best:
-            key_order.append(key)
-            best[key] = record
-        elif score(record) > score(best[key]):
-            best[key] = record
-
-    return {
-        "status": "pass",
-        "opened_com": False,
-        "opened_jtag": False,
-        "dtr_rts_toggled": False,
-        "serial_ports": [best[key] for key in key_order],
-        "pnp_devices": records("pnp_devices"),
-    }
-
-
-def _record_text(record: Any) -> str:
-    if not isinstance(record, dict):
-        return ""
-    return " ".join(str(record.get(field, "")) for field in ("name", "device_id"))
-
-
-def run_preflight(
-    *,
-    enumerator: Callable[[], dict[str, Any]] = enumerate_hardware_candidates,
-) -> dict[str, Any]:
-    try:
-        enumeration = enumerator()
-    except Exception as exc:
-        enumeration = {
-            "status": "blocked_hardware_enumeration_failed",
-            "opened_com": False,
-            "opened_jtag": False,
-            "serial_ports": [],
-            "pnp_devices": [],
-            "error": str(exc),
-        }
-    serial_ports = enumeration.get("serial_ports", []) if isinstance(enumeration, dict) else []
-    pnp_devices = enumeration.get("pnp_devices", []) if isinstance(enumeration, dict) else []
-    if not isinstance(serial_ports, list):
-        serial_ports = []
-    if not isinstance(pnp_devices, list):
-        pnp_devices = []
-    com5_present = any(
-        re.search(r"(?<![A-Z0-9])COM5(?![0-9])", _record_text(record).upper())
-        for record in serial_ports
-    )
-    al_link_present = any(
-        any(
-            marker in re.sub(r"[^a-z0-9]", "", _record_text(record).casefold())
-            for marker in ("allink", "anlogic")
-        )
-        for record in pnp_devices
-    )
-    opened_com = enumeration.get("opened_com") is True
-    opened_jtag = enumeration.get("opened_jtag") is True
-    dtr_rts_toggled = enumeration.get("dtr_rts_toggled") is True
-    failures: list[str] = []
-    if enumeration.get("status") != "pass":
-        failures.append("hardware_enumeration_failed")
-    if opened_com:
-        failures.append("enumerator_opened_com")
-    if opened_jtag:
-        failures.append("enumerator_opened_jtag")
-    if dtr_rts_toggled:
-        failures.append("enumerator_toggled_dtr_rts")
-    if not com5_present:
-        failures.append("com5_not_found")
-    if not al_link_present:
-        failures.append("al_link_not_found")
-    return {
-        "schema": "prod2u-p4-normal-v3-preflight-v2",
-        "status": "pass" if not failures else "blocked_hardware_not_ready",
-        "serial": {
-            "port": PORT,
-            "baud": BAUD,
-            "format": "8N1",
-            "com5_present": com5_present,
-            "ports": serial_ports,
-            "opened": opened_com,
-            "dtr_rts_toggled": dtr_rts_toggled,
-        },
-        "jtag": {
-            "adapter": "AL-Link",
-            "speed_hz": 200000,
-            "al_link_present": al_link_present,
-            "devices": pnp_devices,
-            "opened": opened_jtag,
-        },
-        "hardware_opened": opened_com or opened_jtag,
-        "program_sram_attempted": False,
-        "failures": sorted(set(failures)),
-    }
-
-
-def _live_request(args: argparse.Namespace, endpoint: Any) -> dict[str, Any]:
-    session = NormalSession(endpoint)
-    if args.command == "set-all-outputs":
-        request = build_output_snapshot(
-            ptc_percent=(args.ptc,) * 24,
-            fan_percent=(args.fan,) * 4,
-            solenoid=args.solenoid,
-            xyz=(args.x, args.y, args.z),
-        )
-        requested_hash = state_hash16(
-            ptc_percent=(args.ptc,) * 24,
-            fan_percent=(args.fan,) * 4,
-            solenoid=args.solenoid,
-        )
-        result = session.command(
-            request,
-            expected_command=CommandId.SET_OUTPUT_SNAPSHOT,
-            expected_state_hash16=requested_hash,
-            allowed_statuses=(StatusCode.OK,),
-            expected_detail=0,
-            required_result_flags=0x01,
-            allowed_result_flags=0x01,
-        )
-        return {"status": "pass", "ack": result.ack.__dict__}
-    if args.command == "jog":
-        result = session.command(
-            build_motor_jog(
-                axis=args.axis,
-                raw_dir=args.raw_dir,
-                speed_code=args.speed_code,
-                steps=args.steps,
-            ),
-            expected_command=MotionOpcode.JOG,
-            allowed_statuses=(StatusCode.OK,),
-            expected_detail=0,
-            allowed_result_flags=0,
-        )
-        return {"status": "pass", "ack": result.ack.__dict__}
-    if args.command == "get-status":
-        result = session.command(
-            build_host_command(command=CommandId.GET_STATUS),
-            expected_command=CommandId.GET_STATUS,
-            allowed_statuses=(StatusCode.OK,),
-            allowed_result_flags=0,
-        )
-        if result.ack.detail & ~0x03:
-            session._fail(CommandId.GET_STATUS, "GET_STATUS ACK contains reserved detail bits")
-        return {
-            "status": "pass",
-            "ack": result.ack.__dict__,
-            "disabled": bool(result.ack.detail & 0x01),
-            "watchdog_timeout": bool(result.ack.detail & 0x02),
-        }
-    if args.command == "motor-status":
-        result = session.motor_status()
-        return {
-            "status": "pass",
-            "ack": result.ack.__dict__,
-            "motor_status": result.status.__dict__,
-        }
-    if args.command == "disable":
-        result = session.command(
-            build_host_command(command=CommandId.DISABLE),
-            expected_command=CommandId.DISABLE,
-            allowed_statuses=(StatusCode.OK,),
-            expected_detail=0x01,
-            expected_state_hash16=SAFE_STATE_HASH16,
-            allowed_result_flags=0,
-        )
-        return {"status": "pass", "ack": result.ack.__dict__}
-    raise RuntimeError(f"unsupported live command: {args.command}")
-
-
-def main(argv: list[str] | None = None) -> int:
-    args = build_parser().parse_args(argv)
-    if args.command == "selftest":
-        result = _selftest()
-    elif args.command == "preflight":
-        result = run_preflight()
-    else:
-        endpoint = open_com5()
-        try:
-            result = _live_request(args, endpoint)
-        finally:
-            endpoint.close()
-    print(json.dumps(result, indent=2, default=lambda value: int(value), ensure_ascii=False))
-    return 0 if result.get("status") == "pass" else 1
-
-
-if __name__ == "__main__":
-    raise SystemExit(main())

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


+ 0 - 629
tools/prod2u_p4_protocol.py

@@ -1,629 +0,0 @@
-#!/usr/bin/env python3
-"""Prod2U Profile 4 Normal binary921-v3 wire protocol helpers.
-
-Host request frame types and payload layouts are intentionally frozen. The
-temperature command is the sole exception on the response side: it returns a
-compact 35-byte frame instead of a normal 14-byte-header Binary921 frame.
-"""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from enum import IntEnum
-from typing import Iterable
-
-
-PROTOCOL_ID = "binary921-v3"
-MAGIC = b"\xA5\x5A"
-VERSION = 2
-PROFILE_ID = 4
-HEADER_LEN = 14
-CRC_LEN = 2
-MAX_PAYLOAD_LEN = 255
-HOST_CMD_PAYLOAD_LEN = 4
-HOST_ACK_PAYLOAD_LEN = 8
-OUTPUT_SNAPSHOT_PAYLOAD_LEN = 34
-MOTION_COMMAND_PAYLOAD_LEN = 8
-MOTION_STATUS_PAYLOAD_LEN = 10
-PTC_CHANNEL_COUNT = 24
-FAN_CHANNEL_COUNT = 4
-TEMPERATURE_VALUE_COUNT = 27
-TEMPERATURE_RESPONSE_TYPE = 0x10
-TEMPERATURE_RESPONSE_LEN = 6 + TEMPERATURE_VALUE_COUNT + CRC_LEN
-
-
-class P4FrameError(ValueError):
-    """Raised when a Profile 4 frame cannot be decoded safely."""
-
-
-class FrameType(IntEnum):
-    HOST_CMD = 0x05
-    HOST_ACK = 0x06
-    HOST_BATCH_CMD = 0x07
-    MOTION_CMD = 0x11
-    MOTION_STATUS = 0x12
-
-
-class CommandId(IntEnum):
-    GET_STATUS = 0x24
-    DISABLE = 0x26
-    GET_TEMPERATURES = 0x28
-    SET_OUTPUT_SNAPSHOT = 0x2A
-
-
-class MotionOpcode(IntEnum):
-    JOG = 0x35
-    MARK_CLOSED = 0x36
-    GET_MOTOR_STATUS = 0x37
-
-
-class StatusCode(IntEnum):
-    OK = 0x00
-    UNSUPPORTED_IN_PROFILE = 0x01
-    BAD_FLAGS = 0x02
-    BAD_LENGTH = 0x03
-    BAD_VALUE = 0x05
-    BUSY = 0x09
-    TEMPERATURE_BUS_ERROR = 0x0A
-    PARTIAL = 0x16
-
-
-@dataclass(frozen=True)
-class P4Frame:
-    version: int
-    profile_id: int
-    frame_type: FrameType
-    seq: int
-    timestamp_tick: int
-    payload: bytes
-    crc16: int
-    raw: bytes
-
-
-@dataclass(frozen=True)
-class HostCommand:
-    command: CommandId
-    channel: int
-    value: int
-    flags: int
-
-
-@dataclass(frozen=True)
-class HostAck:
-    ok: bool
-    command: CommandId | MotionOpcode | int
-    status: StatusCode
-    detail: int
-    state_hash16: int
-    response_type: FrameType | int
-    result_flags: int
-    request_seq: int | None
-
-
-@dataclass(frozen=True)
-class OutputSnapshot:
-    ptc_percent: tuple[int, ...]
-    fan_percent: tuple[int, ...]
-    solenoid: int
-    xyz: tuple[int, int, int]
-    state_hash16: int
-
-
-@dataclass(frozen=True)
-class MotionCommand:
-    opcode: MotionOpcode
-    axis: int
-    raw_dir: int
-    speed_code: int
-    steps: int
-
-
-@dataclass(frozen=True)
-class MotionStatus:
-    flags: int
-    position_valid_mask: int
-    busy_mask: int
-    current_xyz: tuple[int, int, int]
-    target_xyz: tuple[int, int, int]
-    fault_mask: int
-
-
-def crc16_ccitt(data: bytes | bytearray | Iterable[int], *, initial: int = 0xFFFF) -> int:
-    """Return CRC-16/CCITT-FALSE for *data*."""
-    crc = initial & 0xFFFF
-    for byte in bytes(data):
-        crc ^= byte << 8
-        for _ in range(8):
-            crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
-    return crc
-
-
-def _u8(value: int, name: str) -> int:
-    if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFF:
-        raise ValueError(f"{name} must fit in one byte")
-    return value
-
-
-def _u16(value: int, name: str) -> int:
-    if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFFFF:
-        raise ValueError(f"{name} must fit in 16 bits")
-    return value
-
-
-def _u32(value: int, name: str) -> int:
-    if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 0xFFFFFFFF:
-        raise ValueError(f"{name} must fit in 32 bits")
-    return value
-
-
-def encode_frame(
-    *,
-    frame_type: FrameType | int,
-    seq: int,
-    timestamp_tick: int,
-    payload: bytes | bytearray | Iterable[int],
-) -> bytes:
-    payload_bytes = bytes(payload)
-    if len(payload_bytes) > MAX_PAYLOAD_LEN:
-        raise ValueError("payload too long for binary921-v3")
-    try:
-        typed_frame = FrameType(int(frame_type))
-    except (TypeError, ValueError) as exc:
-        raise ValueError(f"unknown Profile 4 frame type: {frame_type}") from exc
-    seq = _u32(seq, "seq")
-    timestamp_tick = _u32(timestamp_tick, "timestamp_tick")
-    if seq != 0:
-        raise ValueError("binary921-v3 seq must be zero")
-    if timestamp_tick != 0:
-        raise ValueError("binary921-v3 timestamp must be zero")
-    body = bytes([VERSION, PROFILE_ID, int(typed_frame)])
-    body += seq.to_bytes(4, "little")
-    body += timestamp_tick.to_bytes(4, "little")
-    body += bytes([len(payload_bytes)]) + payload_bytes
-    return MAGIC + body + crc16_ccitt(body).to_bytes(2, "little")
-
-
-def decode_frame(frame: bytes | bytearray) -> P4Frame:
-    raw = bytes(frame)
-    if len(raw) < HEADER_LEN + CRC_LEN:
-        raise P4FrameError("short Profile 4 frame")
-    if raw[:2] != MAGIC:
-        raise P4FrameError("bad Profile 4 magic")
-    if raw[2] != VERSION:
-        raise P4FrameError(f"unsupported binary921 version {raw[2]}")
-    if raw[3] != PROFILE_ID:
-        raise P4FrameError(f"unexpected binary921 profile {raw[3]}")
-    payload_len = raw[13]
-    expected_len = HEADER_LEN + payload_len + CRC_LEN
-    if len(raw) != expected_len:
-        raise P4FrameError(f"length mismatch: expected {expected_len}, got {len(raw)}")
-    expected_crc = crc16_ccitt(raw[2:-2])
-    actual_crc = int.from_bytes(raw[-2:], "little")
-    if actual_crc != expected_crc:
-        raise P4FrameError(f"crc mismatch: expected 0x{expected_crc:04x}, got 0x{actual_crc:04x}")
-    if raw[5:9] != b"\x00\x00\x00\x00":
-        raise P4FrameError("binary921-v3 seq must be zero")
-    if raw[9:13] != b"\x00\x00\x00\x00":
-        raise P4FrameError("binary921-v3 timestamp must be zero")
-    try:
-        frame_type = FrameType(raw[4])
-    except ValueError as exc:
-        raise P4FrameError(f"unknown Profile 4 frame type 0x{raw[4]:02x}") from exc
-    return P4Frame(
-        version=raw[2],
-        profile_id=raw[3],
-        frame_type=frame_type,
-        seq=0,
-        timestamp_tick=0,
-        payload=raw[14:-2],
-        crc16=actual_crc,
-        raw=raw,
-    )
-
-
-def decode_stream(data: bytes | bytearray) -> tuple[list[P4Frame], bytes]:
-    """Decode complete valid frames while preserving a possible partial tail."""
-    buf = bytes(data)
-    frames: list[P4Frame] = []
-    offset = 0
-    while True:
-        magic_at = buf.find(MAGIC, offset)
-        if magic_at < 0:
-            remaining = buf[offset:]
-            return frames, remaining[-1:] if remaining.endswith(MAGIC[:1]) else b""
-        if len(buf) - magic_at < HEADER_LEN + CRC_LEN:
-            return frames, buf[magic_at:]
-        end = magic_at + HEADER_LEN + buf[magic_at + 13] + CRC_LEN
-        if end > len(buf):
-            next_magic = buf.find(MAGIC, magic_at + 1)
-            if next_magic < 0:
-                return frames, buf[magic_at:]
-            offset = next_magic
-            continue
-        try:
-            frames.append(decode_frame(buf[magic_at:end]))
-            offset = end
-        except P4FrameError:
-            offset = magic_at + 1
-
-
-def _payload(value: P4Frame | bytes | bytearray, frame_type: FrameType, length: int, words: str) -> bytes:
-    if isinstance(value, P4Frame):
-        if value.frame_type != frame_type:
-            raise ValueError(f"expected {frame_type.name} frame")
-        payload = value.payload
-    else:
-        payload = bytes(value)
-    if len(payload) != length:
-        raise ValueError(f"{frame_type.name} payload must be exactly {words}")
-    return payload
-
-
-def _percent_tuple(values: Iterable[int], *, count: int, label: str) -> tuple[int, ...]:
-    result = tuple(values)
-    if len(result) != count:
-        raise ValueError(f"snapshot requires exactly {count} {label} values")
-    for index, value in enumerate(result):
-        if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 100:
-            raise ValueError(f"{label}[{index}] must be an integer from 0 to 100")
-    return result
-
-
-def _binary_output(value: int, label: str) -> int:
-    if isinstance(value, bool) or not isinstance(value, int) or value not in (0, 100):
-        raise ValueError(f"{label} must be 0 or 100")
-    return value
-
-
-def state_hash16(
-    *,
-    ptc_percent: Iterable[int],
-    fan_percent: Iterable[int],
-    solenoid: int,
-) -> int:
-    """Hash the currently applied PTC, fan, and solenoid values."""
-    ptc = _percent_tuple(ptc_percent, count=PTC_CHANNEL_COUNT, label="PTC")
-    fan = _percent_tuple(fan_percent, count=FAN_CHANNEL_COUNT, label="FAN")
-    checked_solenoid = _binary_output(solenoid, "solenoid")
-    return crc16_ccitt(bytes(ptc + fan + (checked_solenoid,)))
-
-
-def build_output_snapshot(
-    *,
-    ptc_percent: Iterable[int],
-    fan_percent: Iterable[int],
-    solenoid: int,
-    xyz: Iterable[int],
-) -> bytes:
-    ptc = _percent_tuple(ptc_percent, count=PTC_CHANNEL_COUNT, label="PTC")
-    fan = _percent_tuple(fan_percent, count=FAN_CHANNEL_COUNT, label="FAN")
-    checked_solenoid = _binary_output(solenoid, "solenoid")
-    xyz_values = tuple(xyz)
-    if len(xyz_values) != 3:
-        raise ValueError("snapshot requires exactly 3 XYZ values")
-    checked_xyz = tuple(_u8(value, "XYZ") for value in xyz_values)
-    payload = bytes((CommandId.SET_OUTPUT_SNAPSHOT, 0))
-    payload += bytes(ptc + fan + (checked_solenoid,) + checked_xyz)
-    return encode_frame(
-        frame_type=FrameType.HOST_BATCH_CMD,
-        seq=0,
-        timestamp_tick=0,
-        payload=payload,
-    )
-
-
-def decode_output_snapshot(value: P4Frame | bytes | bytearray) -> OutputSnapshot:
-    payload = _payload(value, FrameType.HOST_BATCH_CMD, OUTPUT_SNAPSHOT_PAYLOAD_LEN, "thirty-four bytes")
-    if payload[0] != CommandId.SET_OUTPUT_SNAPSHOT:
-        raise ValueError("HOST_BATCH_CMD command must be SET_OUTPUT_SNAPSHOT")
-    if payload[1] != 0:
-        raise ValueError("SET_OUTPUT_SNAPSHOT flags must be zero")
-    ptc = _percent_tuple(payload[2:26], count=PTC_CHANNEL_COUNT, label="PTC")
-    fan = _percent_tuple(payload[26:30], count=FAN_CHANNEL_COUNT, label="FAN")
-    solenoid = _binary_output(payload[30], "solenoid")
-    xyz_values = tuple(payload[31:34])
-    return OutputSnapshot(
-        ptc_percent=ptc,
-        fan_percent=fan,
-        solenoid=solenoid,
-        xyz=(xyz_values[0], xyz_values[1], xyz_values[2]),
-        state_hash16=state_hash16(ptc_percent=ptc, fan_percent=fan, solenoid=solenoid),
-    )
-
-
-def build_host_command(
-    *,
-    seq: int = 0,
-    command: CommandId | int,
-    channel: int = 0,
-    value: int = 0,
-    flags: int = 0,
-    timestamp_tick: int = 0,
-) -> bytes:
-    try:
-        command = CommandId(int(command))
-    except (TypeError, ValueError) as exc:
-        raise ValueError(f"unknown Profile4 command: {command}") from exc
-    payload = bytes([int(command), _u8(channel, "channel"), _u8(value, "value"), _u8(flags, "flags")])
-    return encode_frame(
-        frame_type=FrameType.HOST_CMD,
-        seq=seq,
-        timestamp_tick=timestamp_tick,
-        payload=payload,
-    )
-
-
-def build_get_temperatures() -> bytes:
-    """Build the exact HOST_CMD request for one on-demand temperature read."""
-    return build_host_command(command=CommandId.GET_TEMPERATURES)
-
-
-def build_temperature_response(values: bytes | bytearray | Iterable[int]) -> bytes:
-    """Build the compact 35-byte temperature response used by command 0x28."""
-    try:
-        payload = bytes(values)
-    except (TypeError, ValueError) as exc:
-        raise ValueError("temperature response values must be bytes") from exc
-    if len(payload) != TEMPERATURE_VALUE_COUNT:
-        raise ValueError("temperature response requires exactly 27 values")
-    body = bytes(
-        [VERSION, PROFILE_ID, TEMPERATURE_RESPONSE_TYPE, TEMPERATURE_VALUE_COUNT]
-    ) + payload
-    return MAGIC + body + crc16_ccitt(body).to_bytes(2, "little")
-
-
-def decode_temperature_response(frame: bytes | bytearray) -> bytes:
-    """Decode the compact 35-byte temperature response used by command 0x28."""
-    raw = bytes(frame)
-    if len(raw) != TEMPERATURE_RESPONSE_LEN:
-        raise P4FrameError(
-            f"temperature response length mismatch: expected "
-            f"{TEMPERATURE_RESPONSE_LEN}, got {len(raw)}"
-        )
-    expected_prefix = bytes(
-        [*MAGIC, VERSION, PROFILE_ID, TEMPERATURE_RESPONSE_TYPE, TEMPERATURE_VALUE_COUNT]
-    )
-    if raw[:6] != expected_prefix:
-        raise P4FrameError("bad compact temperature response header")
-    expected_crc = crc16_ccitt(raw[2:-2])
-    actual_crc = int.from_bytes(raw[-2:], "little")
-    if actual_crc != expected_crc:
-        raise P4FrameError(
-            f"temperature response crc mismatch: expected 0x{expected_crc:04x}, "
-            f"got 0x{actual_crc:04x}"
-        )
-    return raw[6:-2]
-
-
-def decode_host_command(value: P4Frame | bytes | bytearray) -> HostCommand:
-    payload = _payload(value, FrameType.HOST_CMD, HOST_CMD_PAYLOAD_LEN, "four bytes")
-    try:
-        command = CommandId(payload[0])
-    except ValueError as exc:
-        raise ValueError(f"unknown Profile4 command: 0x{payload[0]:02x}") from exc
-    return HostCommand(command=command, channel=payload[1], value=payload[2], flags=payload[3])
-
-
-def build_host_ack(
-    *,
-    ok: bool,
-    command: CommandId | MotionOpcode | int,
-    status: StatusCode | int,
-    seq: int = 0,
-    detail: int = 0,
-    state_hash16: int = 0,
-    response_type: FrameType | int = 0,
-    result_flags: int = 0,
-    timestamp_tick: int = 0,
-) -> bytes:
-    command_value = _u8(int(command), "command")
-    status_value = StatusCode(int(status))
-    if not isinstance(ok, bool):
-        raise ValueError("ok must be a bool")
-    payload = bytes([int(ok), command_value, int(status_value), _u8(detail, "detail")])
-    payload += _u16(state_hash16, "state_hash16").to_bytes(2, "little")
-    payload += bytes([_u8(int(response_type), "response_type"), _u8(result_flags, "result_flags")])
-    return encode_frame(
-        frame_type=FrameType.HOST_ACK,
-        seq=seq,
-        timestamp_tick=timestamp_tick,
-        payload=payload,
-    )
-
-
-def decode_host_ack(value: P4Frame | bytes | bytearray) -> HostAck:
-    request_seq = value.seq if isinstance(value, P4Frame) else None
-    payload = _payload(value, FrameType.HOST_ACK, HOST_ACK_PAYLOAD_LEN, "eight bytes")
-    if payload[0] not in (0, 1):
-        raise ValueError("HOST_ACK ok must be 0 or 1")
-    try:
-        command: CommandId | MotionOpcode | int = CommandId(payload[1])
-    except ValueError:
-        try:
-            command = MotionOpcode(payload[1])
-        except ValueError:
-            command = payload[1]
-    try:
-        status = StatusCode(payload[2])
-    except ValueError as exc:
-        raise ValueError("HOST_ACK contains an unknown status") from exc
-    try:
-        response_type: FrameType | int = FrameType(payload[6])
-    except ValueError:
-        response_type = payload[6]
-    return HostAck(
-        ok=payload[0] == 1,
-        command=command,
-        status=status,
-        detail=payload[3],
-        state_hash16=int.from_bytes(payload[4:6], "little"),
-        response_type=response_type,
-        result_flags=payload[7],
-        request_seq=request_seq,
-    )
-
-
-def _axis(value: int) -> int:
-    if isinstance(value, bool) or not isinstance(value, int) or value not in (0, 1, 2):
-        raise ValueError("axis must be 0, 1, or 2")
-    return value
-
-
-def _bit(value: int, label: str) -> int:
-    if isinstance(value, bool) or not isinstance(value, int) or value not in (0, 1):
-        raise ValueError(f"{label} must be 0 or 1")
-    return value
-
-
-def build_motor_jog(*, axis: int, raw_dir: int, speed_code: int, steps: int) -> bytes:
-    checked_axis = _axis(axis)
-    checked_dir = _bit(raw_dir, "raw_dir")
-    if isinstance(speed_code, bool) or not isinstance(speed_code, int) or speed_code not in range(4):
-        raise ValueError("speed_code must be from 0 to 3")
-    if isinstance(steps, bool) or not isinstance(steps, int) or not 1 <= steps <= 0xFFFF:
-        raise ValueError("steps must be from 1 to 65535")
-    payload = bytes((MotionOpcode.JOG, checked_axis, checked_dir, speed_code))
-    payload += steps.to_bytes(2, "little") + b"\x00\x00"
-    return encode_frame(frame_type=FrameType.MOTION_CMD, seq=0, timestamp_tick=0, payload=payload)
-
-
-def build_mark_closed(*, axis: int, close_dir: int) -> bytes:
-    """Build the frozen legacy request; compliant firmware rejects it."""
-    checked_axis = _axis(axis)
-    if checked_axis == 2:
-        raise ValueError("MARK_CLOSED axis must be X or Y")
-    payload = bytes((MotionOpcode.MARK_CLOSED, checked_axis, _bit(close_dir, "close_dir"))) + b"\x00" * 5
-    return encode_frame(frame_type=FrameType.MOTION_CMD, seq=0, timestamp_tick=0, payload=payload)
-
-
-def build_get_motor_status() -> bytes:
-    payload = bytes((MotionOpcode.GET_MOTOR_STATUS,)) + b"\x00" * 7
-    return encode_frame(frame_type=FrameType.MOTION_CMD, seq=0, timestamp_tick=0, payload=payload)
-
-
-def decode_motion_command(value: P4Frame | bytes | bytearray) -> MotionCommand:
-    payload = _payload(value, FrameType.MOTION_CMD, MOTION_COMMAND_PAYLOAD_LEN, "eight bytes")
-    try:
-        opcode = MotionOpcode(payload[0])
-    except ValueError as exc:
-        raise ValueError(f"unknown motion opcode 0x{payload[0]:02x}") from exc
-    if opcode == MotionOpcode.JOG:
-        if payload[6:8] != b"\x00\x00":
-            raise ValueError("JOG reserved bytes must be zero")
-        axis = _axis(payload[1])
-        raw_dir = _bit(payload[2], "raw_dir")
-        speed_code = payload[3]
-        steps = int.from_bytes(payload[4:6], "little")
-        if speed_code not in range(4):
-            raise ValueError("speed_code must be from 0 to 3")
-        if not 1 <= steps <= 0xFFFF:
-            raise ValueError("steps must be from 1 to 65535")
-        return MotionCommand(opcode, axis, raw_dir, speed_code, steps)
-    if opcode == MotionOpcode.MARK_CLOSED:
-        if payload[1] not in (0, 1):
-            raise ValueError("MARK_CLOSED axis must be X or Y")
-        if payload[3:8] != b"\x00" * 5:
-            raise ValueError("MARK_CLOSED reserved bytes must be zero")
-        return MotionCommand(opcode, payload[1], _bit(payload[2], "close_dir"), 0, 0)
-    if payload[1:8] != b"\x00" * 7:
-        raise ValueError("GET_MOTOR_STATUS reserved bytes must be zero")
-    return MotionCommand(opcode, 0, 0, 0, 0)
-
-
-def _position_triplet(values: Iterable[int], label: str) -> tuple[int, int, int]:
-    result = tuple(values)
-    if len(result) != 3:
-        raise ValueError(f"{label} must contain exactly three values")
-    for value in result:
-        if value not in (0, 100, 0xFE, 0xFF):
-            raise ValueError(f"{label} values must be 0, 100, 254, or 255")
-    return result[0], result[1], result[2]
-
-
-def _validate_motion_status_contract(
-    *,
-    flags: int,
-    position_valid_mask: int,
-    busy_mask: int,
-    current_xyz: tuple[int, int, int],
-    target_xyz: tuple[int, int, int],
-    fault_mask: int,
-) -> None:
-    if position_valid_mask != 0 or busy_mask != 0 or fault_mask != 0:
-        raise ValueError("MOTION_STATUS valid, busy, and fault fields must be zero")
-    if current_xyz != (0xFF, 0xFF, 0xFF) or target_xyz != (0xFF, 0xFF, 0xFF):
-        raise ValueError("MOTION_STATUS current and target must remain unknown")
-    if flags & 0x01:
-        raise ValueError("MOTION_STATUS any_busy must be zero")
-    if not flags & 0x02:
-        raise ValueError("MOTION_STATUS en_active must be one")
-    if flags & 0x08 and not flags & 0x04:
-        raise ValueError("MOTION_STATUS watchdog_timeout requires disabled")
-
-
-def build_motion_status(
-    *,
-    flags: int,
-    position_valid_mask: int,
-    busy_mask: int,
-    current_xyz: Iterable[int],
-    target_xyz: Iterable[int],
-    fault_mask: int,
-) -> bytes:
-    current = _position_triplet(current_xyz, "current_xyz")
-    target = _position_triplet(target_xyz, "target_xyz")
-    for name, value in (
-        ("position_valid_mask", position_valid_mask),
-        ("busy_mask", busy_mask),
-        ("fault_mask", fault_mask),
-    ):
-        if isinstance(value, bool) or not isinstance(value, int) or value & ~0x07:
-            raise ValueError(f"{name} must use only XYZ bits")
-    checked_flags = _u8(flags, "flags")
-    if checked_flags & 0xF0:
-        raise ValueError("motion status flags contain reserved bits")
-    _validate_motion_status_contract(
-        flags=checked_flags,
-        position_valid_mask=position_valid_mask,
-        busy_mask=busy_mask,
-        current_xyz=current,
-        target_xyz=target,
-        fault_mask=fault_mask,
-    )
-    payload = bytes((checked_flags, position_valid_mask, busy_mask, *current, *target, fault_mask))
-    return encode_frame(frame_type=FrameType.MOTION_STATUS, seq=0, timestamp_tick=0, payload=payload)
-
-
-def decode_motion_status(value: P4Frame | bytes | bytearray) -> MotionStatus:
-    payload = _payload(value, FrameType.MOTION_STATUS, MOTION_STATUS_PAYLOAD_LEN, "ten bytes")
-    flags = payload[0]
-    if flags & 0xF0:
-        raise ValueError("motion status flags contain reserved bits")
-    position_valid_mask = payload[1]
-    busy_mask = payload[2]
-    fault_mask = payload[9]
-    for name, field in (
-        ("position_valid_mask", position_valid_mask),
-        ("busy_mask", busy_mask),
-        ("fault_mask", fault_mask),
-    ):
-        if field & ~0x07:
-            raise ValueError(f"{name} must use only XYZ bits")
-    current = _position_triplet(payload[3:6], "current_xyz")
-    target = _position_triplet(payload[6:9], "target_xyz")
-    _validate_motion_status_contract(
-        flags=flags,
-        position_valid_mask=position_valid_mask,
-        busy_mask=busy_mask,
-        current_xyz=current,
-        target_xyz=target,
-        fault_mask=fault_mask,
-    )
-    return MotionStatus(
-        flags=flags,
-        position_valid_mask=position_valid_mask,
-        busy_mask=busy_mask,
-        current_xyz=current,
-        target_xyz=target,
-        fault_mask=fault_mask,
-    )