Browse Source

fix(prod2u): run independent unguarded jog axes

Codex Resource Selftest 4 tháng trước cách đây
mục cha
commit
7bfa0fb7cb
68 tập tin đã thay đổi với 5868 bổ sung và 5537 xóa
  1. 10 7
      AGENTS.md
  2. 10 7
      README.zh-CN.md
  3. 44 44
      config/prod2u_p4_normal_host_contract_v4.json
  4. 19 10
      config/prod2u_p4_normal_v3_hw_binding.json
  5. 4 3
      config/prod2u_p4_verification_targets_v1.json
  6. 41 26
      docs/prod2u-p4-normal-v3-runbook.zh-CN.md
  7. 45 57
      schemas/prod2u_p4_normal_host_contract_v4.schema.json
  8. 77 248
      src/rtl/prod2u_p4_axis_executor.v
  9. 23 164
      src/rtl/prod2u_p4_motor_hub.v
  10. 147 315
      src/rtl/prod2u_p4_normal_v3_core.v
  11. 69 172
      src/rtl/prod2u_p4_normal_v3_rx.v
  12. 14 39
      src/top/prod2u_p4_normal_v3_top.v
  13. 3 11
      td/phy/prod2u_p4_normal_v3.tcl
  14. 3 11
      td/syn/prod2u_p4_normal_v3.tcl
  15. 3 1
      tests/README.md
  16. 4 3
      tests/cocotb/prod2u_p4_normal_v3_ack_only_top.v
  17. 128 182
      tests/cocotb/test_prod2u_p4_normal_v3_ack_only_top_e2e.py
  18. 11 8
      tests/formal/README.md
  19. 2 3
      tests/formal/prod2u_p4_axis_cdc_structure.sby
  20. 22 36
      tests/formal/prod2u_p4_axis_cdc_structure_formal.v
  21. 2 2
      tests/formal/prod2u_p4_axis_force_jog_limit_ignore.sby
  22. 20 64
      tests/formal/prod2u_p4_axis_force_jog_limit_ignore_formal.v
  23. 2 2
      tests/formal/prod2u_p4_axis_force_jog_replace.sby
  24. 22 152
      tests/formal/prod2u_p4_axis_force_jog_replace_formal.v
  25. 2 3
      tests/formal/prod2u_p4_axis_safety.sby
  26. 113 109
      tests/formal/prod2u_p4_axis_safety_formal.v
  27. 2 2
      tests/formal/prod2u_p4_core_disable_motor_safety.sby
  28. 192 55
      tests/formal/prod2u_p4_core_disable_motor_safety_formal.v
  29. 2 2
      tests/formal/prod2u_p4_core_watchdog_race.sby
  30. 255 73
      tests/formal/prod2u_p4_core_watchdog_race_formal.v
  31. 5 10
      tests/formal/prod2u_p4_jog_no_gates.sby
  32. 45 248
      tests/formal/prod2u_p4_jog_no_gates_formal.v
  33. 14 14
      tests/formal/prod2u_p4_motor_hub_axis_isolation.sby
  34. 69 250
      tests/formal/prod2u_p4_motor_hub_axis_isolation_formal.v
  35. 60 61
      tests/formal/prod2u_p4_normal_v3_rx_formal.v
  36. 21 18
      tests/formal/prod2u_p4_normal_v3_rx_payload_formal.v
  37. 231 259
      tests/sim/prod2u_p4_axis_force_jog_v1_tb.v
  38. 37 103
      tests/sim/prod2u_p4_axis_jog_16bit_tb.v
  39. 0 214
      tests/sim/prod2u_p4_axis_minimal_standard_tb.v
  40. 35 52
      tests/sim/prod2u_p4_cdc_sync_depth_tb.v
  41. 443 0
      tests/sim/prod2u_p4_completion_ack_contract_tb.v
  42. 134 251
      tests/sim/prod2u_p4_core_watchdog_refresh_tb.v
  43. 52 307
      tests/sim/prod2u_p4_jog_no_gates_contract_tb.v
  44. 112 454
      tests/sim/prod2u_p4_minimal_snapshot_contract_tb.v
  45. 86 265
      tests/sim/prod2u_p4_motor_hub_axis_isolation_tb.v
  46. 40 238
      tests/sim/prod2u_p4_motor_status_payload_tb.v
  47. 28 94
      tests/sim/prod2u_p4_normal_v3_rx_tb.v
  48. 41 1
      tests/sim/prod2u_p4_normal_v3_top_tb.v
  49. 13 21
      tests/sim/prod2u_p4_production_defaults_tb.v
  50. 7 8
      tests/unit/test_prod2u_p4_ack_only_host_contract.py
  51. 5 3
      tests/unit/test_prod2u_p4_cli_v3.py
  52. 579 57
      tests/unit/test_prod2u_p4_harness.py
  53. 560 45
      tests/unit/test_prod2u_p4_minimal_delivery_contract.py
  54. 546 0
      tests/unit/test_prod2u_p4_motion_source_mutations.py
  55. 228 315
      tests/unit/test_prod2u_p4_normal_v3_model.py
  56. 90 18
      tests/unit/test_prod2u_p4_normal_v3_td_files.py
  57. 10 2
      tests/unit/test_prod2u_p4_output_storage_structure.py
  58. 157 43
      tests/unit/test_prod2u_p4_protocol_v3.py
  59. 136 2
      tests/unit/test_prod2u_p4_send_hex_template.py
  60. 16 21
      tests/unit/test_prod2u_p4_td_cdc_structure.py
  61. 250 35
      tools/package_prod2u_p4_normal_v3.ps1
  62. 1 0
      tools/package_templates/INITIALIZE_DISABLE.ps1
  63. 19 5
      tools/package_templates/SEND_HEX.ps1
  64. 113 14
      tools/package_templates/selftest.ps1
  65. 20 28
      tools/prod2u_p4_cli.py
  66. 248 44
      tools/prod2u_p4_harness.py
  67. 116 215
      tools/prod2u_p4_normal_v3_model.py
  68. 10 11
      tools/prod2u_p4_protocol.py

+ 10 - 7
AGENTS.md

@@ -12,13 +12,16 @@
 
 
 ## 功能合同
 ## 功能合同
 
 
-- 保留 24 路 PTC、4 路 FAN、solenoid、UART、X/Y 电机和关闭端限位;Z 只保留协议位置。
+- 保留 24 路 PTC、4 路 FAN、solenoid、UART 和 X/Y 电机;LS1/LS2 仅保留物理引脚,Z 只保留协议位置。
 - binary921-v3 输入 envelope、Profile ID 4、50 字节输出 snapshot 和 10 字节 MOTION_STATUS 保持兼容。
 - binary921-v3 输入 envelope、Profile ID 4、50 字节输出 snapshot 和 10 字节 MOTION_STATUS 保持兼容。
 - X/Y 固定 `DIR=0` 打开、`DIR=1` 关闭,使用独立执行器并允许同时运动。
 - X/Y 固定 `DIR=0` 打开、`DIR=1` 关闭,使用独立执行器并允许同时运动。
-- 标准 OPEN/CLOSE 每次固定执行 3200 步且不读取限位。当前 V1 强制运动镜像的 JOG 两个方向都忽略限位,每条最多实际执行 800 步。
-- 合法 X/Y JOG 永不返回 BUSY;轴 active、snapshot 状态、限位输入和已锁存 watchdog timeout 均不参与 JOG 准入。请求帧和 HEX 不变,非法 axis/方向/速度/零步仍返回 BAD_VALUE。
-- 同轴新 JOG 可以替换标准动作或旧 JOG;完成当前完整 STEP 低相后采用 latest-wins,重新等待 1 ms DIR setup。对外 `busy_mask` 是只读遥测,只在首个实际 STEP 上升沿后置位,不参与 JOG 准入。
-- watchdog 到期仍硬停旧运动;下一条合法 JOG 清除 timeout 并重新 arm,无需先发送 DISABLE。GET_STATUS 和 GET_MOTOR_STATUS 都不能复活已超时的旧运动。
+- 只有 `0x35 JOG` 驱动电机。Snapshot 的 X/Y/Z 字节保持线格式兼容、允许任意 `u8`,但完全忽略且无电机作用;旧标准 OPEN/CLOSE CLI 仅发送这些无作用字段。
+- 合法 X/Y JOG 永不返回 BUSY;超过 800 步的请求仍会完整执行,完整范围为 `1..65535`。`speed_code=0..3` 的 speed 字段仅校验,执行时忽略并统一固定 1000 step/s;非法 axis/方向/速度/零步仍返回 BAD_VALUE。
+- JOG ACK 仅在首个实际 STEP 上升沿已经发出后返回。同轴新 JOG 立即将旧 STEP 拉低、丢弃旧剩余步数并重新等待完整 1 ms DIR setup;旧脉冲允许被截短。
+- JOG 忽略限位;同轴新 JOG 直接替换旧命令,不保留待处理队列。
+- `busy_mask`、`fault_mask` 和 `position_valid_mask` 是恒为 0 的只读遥测,current/target 恒为 `0xFF`,EN active 恒为 1。
+- LS1/LS2 不接入同步、滤波、状态机或任何运动判断。JOG 不 arm/refresh watchdog;DISABLE 和 watchdog 只把 PTC/FAN/solenoid 置安全值,不停止电机。电机只会因复位、断电或重新配置停止。
+- 合法 JOG 无需先发送 DISABLE;GET_STATUS 和 GET_MOTOR_STATUS 都不能复活、暂停或停止电机运动。
 - X/LS1 绑定 B9,Y/LS2 绑定 A11;`0V=未触发`、`3.3V=关闭端触发`,A5 不得分配。
 - X/LS1 绑定 B9,Y/LS2 绑定 A11;`0V=未触发`、`3.3V=关闭端触发`,A5 不得分配。
 - MARK_CLOSED、方向学习、距离模型、恢复步数、永久锁定和运行中反向均不属于当前产品。
 - MARK_CLOSED、方向学习、距离模型、恢复步数、永久锁定和运行中反向均不属于当前产品。
 - 生产响应为普通命令 HOST_ACK;GET_MOTOR_STATUS 为 ACK 后紧跟 MOTION_STATUS。
 - 生产响应为普通命令 HOST_ACK;GET_MOTOR_STATUS 为 ACK 后紧跟 MOTION_STATUS。
@@ -27,7 +30,7 @@
 ## 验证边界
 ## 验证边界
 
 
 - 离线 gate 覆盖源码完整性、协议、模型、RTL、formal、CDC、STA、TD、资源和包自检。
 - 离线 gate 覆盖源码完整性、协议、模型、RTL、formal、CDC、STA、TD、资源和包自检。
-- TD 结构要求所有 9K/32K/128K/256K BRAM 均为 0、`DSP=0`、`IO=41`、正 setup/hold、非空 bitstream、8 个 CDC 同步寄存器和 X/Y 三位顺序 `motion_phase`。
+- TD 结构要求所有 9K/32K/128K/256K BRAM 均为 0、`DSP=0`、`IO=41`、正 setup/hold、非空 bitstream、仅 UART 的 2 个 CDC 同步寄存器和 X/Y 两位顺序 `motion_phase`。
 - 总 LUT/FF/slice 差值仅为 advisory,不得改变 bitgen 状态。
 - 总 LUT/FF/slice 差值仅为 advisory,不得改变 bitgen 状态。
 - Windows 运行 Verilator 前使用 `tools/activate_verification_toolchain.ps1` 或仓库 resolver,不得修改全局 PATH。
 - Windows 运行 Verilator 前使用 `tools/activate_verification_toolchain.ps1` 或仓库 resolver,不得修改全局 PATH。
 - blocked、fail、dry-run、fixture 或缺少证据均不等于 pass;离线通过不等于实板机械验收。只要 TD 已产生非空 bitstream,验证失败不得阻止临时镜像打包,但必须原样随包记录。
 - blocked、fail、dry-run、fixture 或缺少证据均不等于 pass;离线通过不等于实板机械验收。只要 TD 已产生非空 bitstream,验证失败不得阻止临时镜像打包,但必须原样随包记录。
@@ -37,4 +40,4 @@
 - 禁止 Flash、驱动安装/重装、真实 PTC 加热、温度实验和 Z 轴运动。
 - 禁止 Flash、驱动安装/重装、真实 PTC 加热、温度实验和 Z 轴运动。
 - 本仓库默认只生成和验证刷机包,不打开 COM5/JTAG,不执行编程。
 - 本仓库默认只生成和验证刷机包,不打开 COM5/JTAG,不执行编程。
 - 明确授权的板测最多一次 `PROGRAM_SRAM @ 200 kHz`,异常不得自动重试;编程后立即发送 DISABLE。
 - 明确授权的板测最多一次 `PROGRAM_SRAM @ 200 kHz`,异常不得自动重试;编程后立即发送 DISABLE。
-- 标准 CLOSE 和长 JOG 存在已接受的机械越程风险。任何异常应立即断电。
+- JOG 完全无机械保护且单条可执行 65535 步;DISABLE、watchdog 和限位均不能停电机。任何异常必须立即断电或复位/重新配置。

+ 10 - 7
README.zh-CN.md

@@ -1,21 +1,24 @@
 # Prod2U Profile 4 Normal v3
 # Prod2U Profile 4 Normal v3
 
 
-本仓库构建一个 binary921-v3、921600 baud 的 CPLD 生产镜像,保留 PTC、FAN、solenoid、X/Y 电机、关闭端限位、5 秒 watchdog 和 SRAM 编程支持。
+本仓库构建一个 binary921-v3、921600 baud 的 CPLD 生产镜像,保留 PTC、FAN、solenoid、X/Y 电机、LS1/LS2 物理引脚、非电机输出 watchdog 和 SRAM 编程支持。
 
 
 当前极简运动合同:
 当前极简运动合同:
 
 
 - X/Y 可独立并行运动,`DIR=0` 打开、`DIR=1` 关闭。
 - X/Y 可独立并行运动,`DIR=0` 打开、`DIR=1` 关闭。
-- 标准 OPEN/CLOSE 每次固定 3200 步,不根据限位提前停止。
-- V1 强制 JOG 保持既有 `1..65535` 请求字段,但每条只实际执行 `min(steps, 800)`,两个方向都忽略限位。
-- 同轴新 JOG 在当前完整 STEP 低相结束后替换旧动作,多条待替换命令只保留最后一条;X/Y 互不阻塞。
-- 对外 busy 只在首个实际 STEP 上升沿后置位,DIR setup 和替换等待期间为 0。
+- 只有 `0x35 JOG` 能驱动电机;legacy 标准 OPEN/CLOSE 只修改 Snapshot 的兼容字段,不产生 STEP。
+- Snapshot 的 X/Y/Z 字段允许任意 `u8`,但全部忽略且没有电机作用。
+- JOG 保持 `1..65535` 请求字段;超过 800 步的请求也会完整执行,两个方向都忽略限位。
+- 合法 X/Y JOG 永不返回 BUSY。ACK 在首个实际 STEP 上升沿已经发出后返回,但不表示整段运动完成。
+- 同轴新 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 不使用。
 - LS1/X=`B9`、LS2/Y=`A11`,A5 不使用。
 - 版本号为完整 Git commit,不在设备运行时发送额外身份帧。
 - 版本号为完整 Git commit,不在设备运行时发送额外身份帧。
 
 
 ## 离线验证
 ## 离线验证
 
 
 ```powershell
 ```powershell
-Set-Location 'C:\Users\Administrator\CodexTemp\p4-normal-actuator-temp-921600-from-831'
+Set-Location 'C:\Users\Administrator\CodexTemp\p4-normal-v1-no-gates-73df4ee'
 python tools\prod2u_p4_harness.py p4-normal-v3-strict-offline-gate `
 python tools\prod2u_p4_harness.py p4-normal-v3-strict-offline-gate `
   --work-root C:\Users\Administrator\CodexTemp\p4-normal-v3-minimal-offline `
   --work-root C:\Users\Administrator\CodexTemp\p4-normal-v3-minimal-offline `
   --json `
   --json `
@@ -47,6 +50,6 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass `
   -ValidationReceipt '<offline-or-layer-receipt>.json'
   -ValidationReceipt '<offline-or-layer-receipt>.json'
 ```
 ```
 
 
-输出固定为 `C:\Users\Administrator\CodexTemp\p4-normal-images\<40位commit>\prod2u-p4-normal-<40位commit>-<bitstream-sha256前16位>`。包内包含两份 TD receipt/报告、验证矩阵、包自检结果、SRAM 脚本、初始化 DISABLE、通用 HEX 发送方法以及标准动作和 JOG 的冻结 HEX。
+输出固定为 `C:\Users\Administrator\CodexTemp\p4-normal-images\<40位commit>\prod2u-p4-normal-<40位commit>-<bitstream-sha256前16位>`。包内包含两份 TD receipt/报告、验证矩阵、包自检结果、SRAM 脚本、初始化 DISABLE、通用 HEX 发送方法以及兼容 Snapshot 和 JOG 的冻结 HEX。
 
 
 仓库构建和打包不会连接串口或 JTAG,也不会执行 SRAM/Flash 操作。详细风险与实板步骤见 [运行手册](docs/prod2u-p4-normal-v3-runbook.zh-CN.md)。
 仓库构建和打包不会连接串口或 JTAG,也不会执行 SRAM/Flash 操作。详细风险与实板步骤见 [运行手册](docs/prod2u-p4-normal-v3-runbook.zh-CN.md)。

+ 44 - 44
config/prod2u_p4_normal_host_contract_v4.json

@@ -58,7 +58,9 @@
       "payload_hex": "26 00 00 00",
       "payload_hex": "26 00 00 00",
       "response": "HOST_ACK",
       "response": "HOST_ACK",
       "always_accepted": true,
       "always_accepted": true,
-      "effect": "IMMEDIATE_SAFE_OUTPUTS_AND_AXIS_STOP"
+      "effect": "IMMEDIATE_SAFE_NON_MOTOR_OUTPUTS",
+      "motor_effect": "NONE",
+      "non_motor_effect": "IMMEDIATE_SAFE_OUTPUTS"
     },
     },
     "set_output_snapshot": {
     "set_output_snapshot": {
       "frame_type": 7,
       "frame_type": 7,
@@ -69,10 +71,12 @@
       "ptc_range": [0, 100],
       "ptc_range": [0, 100],
       "fan_range": [0, 100],
       "fan_range": [0, 100],
       "binary_values": [0, 100],
       "binary_values": [0, 100],
+      "xyz_range": [0, 255],
+      "xyz_policy": "IGNORE_ANY_U8_NO_MOTOR_EFFECT",
+      "motor_effect": "NONE",
       "ptc_fan_commit_when_motion_busy": true,
       "ptc_fan_commit_when_motion_busy": true,
-      "solenoid_change_when_any_xy_busy": "IGNORE_AND_SET_DETAIL_BIT_6",
-      "axis_policy": "INDEPENDENT_ACCEPT_BUSY_INVALID",
-      "active_axis_precedence": "BUSY_IGNORED_BEFORE_TARGET_VALIDATION",
+      "solenoid_change_when_any_xy_busy": "ALWAYS_COMMIT",
+      "axis_policy": "IGNORE_ANY_U8_NO_MOTOR_EFFECT",
       "response": "HOST_ACK"
       "response": "HOST_ACK"
     },
     },
     "jog": {
     "jog": {
@@ -87,11 +91,15 @@
       "direction": {"OPEN_UP": 0, "CLOSE_DOWN": 1},
       "direction": {"OPEN_UP": 0, "CLOSE_DOWN": 1},
       "speed_codes": [0, 1, 2, 3],
       "speed_codes": [0, 1, 2, 3],
       "step_range": [1, 65535],
       "step_range": [1, 65535],
-      "executed_step_cap": 800,
-      "over_cap_status": "OK",
-      "over_cap_behavior": "EXECUTE_800_STEPS_WITH_REQUEST_BYTES_UNCHANGED",
-      "same_axis_active_policy": "REPLACE_LATEST_AFTER_CURRENT_FULL_STEP",
-      "multiple_pending_policy": "LATEST_WINS_EACH_COMMAND_ACKED",
+      "executed_step_cap": null,
+      "over_cap_status": "NOT_APPLICABLE",
+      "over_cap_behavior": "EXECUTE_REQUESTED_U16_STEPS",
+      "speed_field_policy": "VALIDATE_0_TO_3_THEN_IGNORE",
+      "effective_step_rate_hz": 1000,
+      "ack_semantics": "FIRST_STEP_EMITTED",
+      "arms_watchdog": false,
+      "same_axis_active_policy": "IMMEDIATE_RELOAD_AND_RESTART_DIR_SETUP",
+      "multiple_pending_policy": "NONE",
       "replacement_dir_setup_us": 1000,
       "replacement_dir_setup_us": 1000,
       "limit_policy": "IGNORE_ALL_INPUTS",
       "limit_policy": "IGNORE_ALL_INPUTS",
       "rejects_busy": false,
       "rejects_busy": false,
@@ -101,7 +109,7 @@
         "LIMIT_INPUTS",
         "LIMIT_INPUTS",
         "WATCHDOG_TIMEOUT"
         "WATCHDOG_TIMEOUT"
       ],
       ],
-      "watchdog_timeout_recovery": "CLEAR_TIMEOUT_REARM_WITHOUT_DISABLE",
+      "watchdog_timeout_recovery": "NOT_APPLICABLE_TIMEOUT_HAS_NO_MOTOR_EFFECT",
       "peer_axis_busy_does_not_block": true,
       "peer_axis_busy_does_not_block": true,
       "response": "HOST_ACK"
       "response": "HOST_ACK"
     },
     },
@@ -160,21 +168,10 @@
         "input_order": ["applied_PTC1..24", "applied_FAN1..4", "applied_solenoid"],
         "input_order": ["applied_PTC1..24", "applied_FAN1..4", "applied_solenoid"],
         "semantic": "ACTUAL_APPLIED_SYNCHRONOUS_OUTPUTS"
         "semantic": "ACTUAL_APPLIED_SYNCHRONOUS_OUTPUTS"
       },
       },
-      "snapshot_detail_bits": {
-        "x_busy": 0,
-        "y_busy": 1,
-        "z_busy": 2,
-        "x_invalid": 3,
-        "y_invalid": 4,
-        "z_invalid": 5,
-        "solenoid_change_ignored": 6,
-        "reserved_zero": 7
-      },
+      "snapshot_detail_bits": {"all_bits": "ZERO"},
       "snapshot_result_flag_bits": {
       "snapshot_result_flag_bits": {
-        "ptc_fan_committed": 0,
-        "x_accepted_or_noop": 1,
-        "y_accepted_or_noop": 2,
-        "z_accepted_or_noop": 3
+        "ptc_fan_solenoid_committed": 0,
+        "axis_bits_3_to_1": "ZERO"
       },
       },
       "status_codes": {
       "status_codes": {
         "OK": 0,
         "OK": 0,
@@ -191,13 +188,14 @@
       "payload_length": 10,
       "payload_length": 10,
       "full_frame_length": 26,
       "full_frame_length": 26,
       "layout": "flags valid_mask busy_mask current_xyz target_xyz fault_mask",
       "layout": "flags valid_mask busy_mask current_xyz target_xyz fault_mask",
-      "position_values": {"CLOSED_COMMAND_COMPLETE": 0, "OPEN_COMMAND_COMPLETE": 100, "MOVING": 254, "UNKNOWN": 255},
-      "standard_motion_valid_during_busy": false,
-      "jog_or_limit_stop_position": 255,
-      "busy_semantic": "FIRST_STEP_RISE_THROUGH_FINAL_LOW",
-      "busy_role": "READ_ONLY_TELEMETRY_NOT_JOG_ADMISSION",
-      "setup_busy": false,
-      "active_not_busy_allowed": true,
+      "position_values": {"UNKNOWN": 255},
+      "position_valid_mask": 0,
+      "current_xyz": [255, 255, 255],
+      "target_xyz": [255, 255, 255],
+      "busy_mask": 0,
+      "busy_semantic": "ALWAYS_ZERO",
+      "busy_role": "RESERVED_CONSTANT_ZERO",
+      "enable_active": 1,
       "fault_mask": 0,
       "fault_mask": 0,
       "z_current_target": 255,
       "z_current_target": 255,
       "z_valid_busy_fault": 0
       "z_valid_busy_fault": 0
@@ -206,39 +204,41 @@
   "motion": {
   "motion": {
     "axes": ["X", "Y"],
     "axes": ["X", "Y"],
     "execution": "TWO_INDEPENDENT_PARALLEL_EXECUTORS",
     "execution": "TWO_INDEPENDENT_PARALLEL_EXECUTORS",
-    "snapshot_arbitration_signal": "AXIS_ACTIVE",
-    "same_axis_standard_while_active": "BUSY_OR_PARTIAL",
-    "same_axis_jog_while_active": "REPLACE_LATEST_AFTER_CURRENT_FULL_STEP",
+    "motor_driving_commands": ["0x35"],
+    "jog_ack_semantics": "FIRST_STEP_EMITTED",
+    "same_axis_jog_while_active": "IMMEDIATE_RELOAD_AND_RESTART_DIR_SETUP",
     "peer_axis_may_start": true,
     "peer_axis_may_start": true,
-    "standard_open": {"direction": 0, "steps": 3200, "checks_limit": false},
-    "standard_close": {"direction": 1, "steps": 3200, "checks_limit": false},
-    "repeated_standard_command": "START_NEW_3200_STEP_MOVE",
     "dir_setup_us": 1000,
     "dir_setup_us": 1000,
-    "normal_step_stop": "COMPLETE_CURRENT_HIGH_AND_LOW_PHASE",
-    "hard_stop_sources": ["DISABLE", "WATCHDOG_EXPIRY"]
+    "effective_step_rate_hz": 1000,
+    "normal_step_stop": "NEW_SAME_AXIS_JOG_MAY_TRUNCATE_OLD_STEP",
+    "motor_stop_sources": ["RESET", "POWER_LOSS", "RECONFIGURATION"]
   },
   },
   "limit": {
   "limit": {
     "axes": ["X", "Y"],
     "axes": ["X", "Y"],
     "polarity": "ACTIVE_HIGH",
     "polarity": "ACTIVE_HIGH",
     "open_voltage_v": 0.0,
     "open_voltage_v": 0.0,
     "closed_voltage_v": 3.3,
     "closed_voltage_v": 3.3,
-    "synchronizer_stages": 3,
-    "used_only_for": "NOT_USED_BY_FORCE_JOG_IMAGE",
+    "synchronizer_stages": 0,
+    "pins_retained": true,
+    "logic_consumer": "NONE",
+    "used_only_for": "RETAINED_PINS_NO_LOGIC_CONSUMER",
     "motion_effect": "NONE",
     "motion_effect": "NONE",
     "dir0_jog_ignores_limit": true,
     "dir0_jog_ignores_limit": true,
     "dir1_jog_ignores_limit": true,
     "dir1_jog_ignores_limit": true,
-    "standard_motion_ignores_limit": true,
     "position_memory": false,
     "position_memory": false,
     "direction_learning": false
     "direction_learning": false
   },
   },
   "watchdog": {
   "watchdog": {
     "timeout_seconds": 5,
     "timeout_seconds": 5,
-    "accepted_output_or_motion_arms": true,
+    "accepted_output_arms": true,
+    "accepted_motion_arms": false,
     "armed_get_motor_status_refreshes": true,
     "armed_get_motor_status_refreshes": true,
     "status_query_cannot_arm_or_revive": true,
     "status_query_cannot_arm_or_revive": true,
     "expiry_beats_same_cycle_refresh": true,
     "expiry_beats_same_cycle_refresh": true,
     "expiry_requires_disable_before_rearm": false,
     "expiry_requires_disable_before_rearm": false,
-    "next_valid_jog_clears_timeout_and_rearms": true
+    "next_valid_output_clears_timeout_and_rearms": true,
+    "motor_effect": "NONE",
+    "non_motor_effect": "SAFE_OUTPUTS"
   },
   },
   "programming": {
   "programming": {
     "operation": "PROGRAM_SRAM",
     "operation": "PROGRAM_SRAM",

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 19 - 10
config/prod2u_p4_normal_v3_hw_binding.json


+ 4 - 3
config/prod2u_p4_verification_targets_v1.json

@@ -11,6 +11,7 @@
       "tests.unit.test_prod2u_p4_harness",
       "tests.unit.test_prod2u_p4_harness",
       "tests.unit.test_prod2u_p4_minimal_delivery_contract",
       "tests.unit.test_prod2u_p4_minimal_delivery_contract",
       "tests.unit.test_prod2u_p4_minimal_snapshot_contract_rtl",
       "tests.unit.test_prod2u_p4_minimal_snapshot_contract_rtl",
+      "tests.unit.test_prod2u_p4_motion_source_mutations",
       "tests.unit.test_prod2u_p4_normal_v3_model",
       "tests.unit.test_prod2u_p4_normal_v3_model",
       "tests.unit.test_prod2u_p4_normal_v3_td_files",
       "tests.unit.test_prod2u_p4_normal_v3_td_files",
       "tests.unit.test_prod2u_p4_output_storage_structure",
       "tests.unit.test_prod2u_p4_output_storage_structure",
@@ -24,8 +25,8 @@
     "icarus": [
     "icarus": [
       "prod2u_p4_axis_force_jog_v1_tb",
       "prod2u_p4_axis_force_jog_v1_tb",
       "prod2u_p4_axis_jog_16bit_tb",
       "prod2u_p4_axis_jog_16bit_tb",
-      "prod2u_p4_axis_minimal_standard_tb",
       "prod2u_p4_cdc_sync_depth_tb",
       "prod2u_p4_cdc_sync_depth_tb",
+      "prod2u_p4_completion_ack_contract_tb",
       "prod2u_p4_core_watchdog_refresh_tb",
       "prod2u_p4_core_watchdog_refresh_tb",
       "prod2u_p4_jog_no_gates_contract_tb",
       "prod2u_p4_jog_no_gates_contract_tb",
       "prod2u_p4_minimal_snapshot_contract_tb",
       "prod2u_p4_minimal_snapshot_contract_tb",
@@ -86,8 +87,8 @@
           "cover_isolation",
           "cover_isolation",
           "bmc_overlap",
           "bmc_overlap",
           "cover_overlap",
           "cover_overlap",
-          "prove_hard_stop",
-          "cover_hard_stop"
+          "prove_reserved_axis",
+          "cover_reserved_axis"
         ]
         ]
       },
       },
       {
       {

+ 41 - 26
docs/prod2u-p4-normal-v3-runbook.zh-CN.md

@@ -4,19 +4,21 @@
 
 
 - 上位机输入仍使用 binary921-v3、Profile ID 4、921600 baud、8N1。
 - 上位机输入仍使用 binary921-v3、Profile ID 4、921600 baud、8N1。
 - X/Y 是独立执行器,可以同时运动;`DIR=0` 为打开,`DIR=1` 为关闭。
 - X/Y 是独立执行器,可以同时运动;`DIR=0` 为打开,`DIR=1` 为关闭。
-- X/Y 的 STEP、DIR 和 busy 独立,但板上 `motor_en_n` 为两轴共享。任一轴仍在运动时共享使能保持有效;只有两轴均停止或 DISABLE/watchdog 硬停时才撤销共享使能。
-- 标准 OPEN 和 CLOSE 每次固定产生 3200 个完整 STEP,不读取限位输入。
-- JOG 请求步数沿用 16 位字段,合法范围为 `1..65535`;每条命令实际执行 `min(requested_steps, 800)`,超过 800 仍返回 OK,但只走 800 步。
-- 合法 X/Y JOG 永不返回 BUSY。目标轴正在执行标准动作或旧 JOG、内部仍有 snapshot 提交状态、LS 电平变化、已经锁存 watchdog timeout,都不构成 JOG 拒绝条件;新 JOG 仍按 latest-wins 合同接收。
-- 两个方向 JOG 都忽略限位。LS1/X=B9、LS2/Y=A11 的物理绑定保留正确,但本 V1 镜像不使用 LS 打断运动。
+- 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 步数保持 16 位,合法范围 `1..65535`;超过 800 步的请求也会完整执行,不再截断。
+- `speed_code=0..3` 的 speed 字段仍会校验,但执行时忽略该值,四个值的实际速度都固定为 1000 step/s。
+- 合法 X/Y JOG 永不返回 BUSY,也不受 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 不使用。
 - LS1/X 使用 B9,LS2/Y 使用 A11;`0V=未触发`,`3.3V=关闭端触发`。A5 不使用。
-- 同轴新 JOG 可以替换正在执行的标准动作或旧 JOG:先完成当前完整 STEP 高相和低相,丢弃旧剩余距离,只保留最后到达的 JOG,再重新等待 1 ms DIR setup。X/Y 可独立同时替换和运行。
-- 对外 `busy_mask` 是只读遥测,不参与 JOG 准入。它只在首个实际 STEP 上升沿后置位,并保持到该命令最终完整低相结束;DIR setup、替换等待和未产生 STEP 的状态均上报 busy=0。该信号只证明 CPLD 输出过 STEP,不能证明转子或机构实际运动。
-- Snapshot 中活动轴的新标准目标会被忽略并返回 PARTIAL;另一轴仍可启动。PTC/FAN 的合法更新不受电机活动影响,任一轴活动时 solenoid 变化被忽略。
-- 保留 5 秒失联停机和 DISABLE 硬停。watchdog 到期仍立即停止旧运动;下一条合法 JOG 会清除 timeout 并重新 arm,无需先发送 DISABLE。GET_STATUS 和 GET_MOTOR_STATUS 都不能复活已经超时的运动;长 JOG 必须在 5 秒内持续查询电机状态。
+- 同轴新 JOG 会立即把旧 STEP 拉低并丢弃旧剩余步数,然后重新等待完整 1 ms DIR setup;旧 STEP 高脉冲允许被截短。X/Y 可独立重载并重叠运行。
+- `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、恢复步数、永久锁定或开端保护。
 - 固件不保存限位位置,不自动学习方向,不提供 MARK_CLOSED、恢复步数、永久锁定或开端保护。
 
 
-标准动作完成后的 `current=0/100` 只表示 3200 步命令执行完成,不表示机械端点由传感器确认。
+固件不提供电机位置、完成进度或机械端点确认。
 
 
 ## 离线检查
 ## 离线检查
 
 
@@ -38,7 +40,7 @@ Set-Location '<package-path>'
 powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\PROGRAM_SRAM.ps1 -Confirm PROGRAM_SRAM
 powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\PROGRAM_SRAM.ps1 -Confirm PROGRAM_SRAM
 ```
 ```
 
 
-脚本若发现 TD 或 BitWriter 进程已经运行会直接停止,且不会自动结束这些进程。编程成功后立即执行初始化 DISABLE:
+脚本若发现 TD 或 BitWriter 进程已经运行会直接停止,且不会自动结束这些进程。编程成功后立即执行初始化 DISABLE;该命令只初始化非电机输出,不具备电机停机作用:
 
 
 ```powershell
 ```powershell
 powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\INITIALIZE_DISABLE.ps1 -Port COM5
 powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\INITIALIZE_DISABLE.ps1 -Port COM5
@@ -59,18 +61,22 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\SEND_HEX.ps1 -Port COM
 | GET_STATUS | `A55A02040500000000000000000424000000AC43` |
 | GET_STATUS | `A55A02040500000000000000000424000000AC43` |
 | DISABLE | `A55A02040500000000000000000426000000C4AE` |
 | DISABLE | `A55A02040500000000000000000426000000C4AE` |
 | GET_MOTOR_STATUS | `A55A0204110000000000000000083700000000000000347F` |
 | GET_MOTOR_STATUS | `A55A0204110000000000000000083700000000000000347F` |
-| 全输出关闭并请求 X/Y CLOSE | `A55A0204070000000000000000222A0000000000000000000000000000000000000000000000000000000000000000005528` |
-| FAN 1..4=30%,其余关闭并请求 X/Y CLOSE | `A55A0204070000000000000000222A000000000000000000000000000000000000000000000000001E1E1E1E00000000D6DF` |
-| PTC1=10%,FAN 1..4=30%,其余关闭并请求 X/Y CLOSE | `A55A0204070000000000000000222A000A00000000000000000000000000000000000000000000001E1E1E1E000000002887` |
-| 仅 FAN3=30%,其余关闭并请求 X/Y CLOSE | `A55A0204070000000000000000222A0000000000000000000000000000000000000000000000000000001E000000000072B2` |
-| solenoid=100,FAN 1..4=30%,请求 X/Y CLOSE | `A55A0204070000000000000000222A000000000000000000000000000000000000000000000000001E1E1E1E64000000F54C` |
-| 全输出关闭并请求 X/Y OPEN | `A55A0204070000000000000000222A00000000000000000000000000000000000000000000000000000000000064640010A8` |
-| FAN 1..4=30%,X OPEN、Y CLOSE | `A55A0204070000000000000000222A000000000000000000000000000000000000000000000000001E1E1E1E006400007D98` |
-| FAN 1..4=30%,X CLOSE、Y OPEN | `A55A0204070000000000000000222A000000000000000000000000000000000000000000000000001E1E1E1E000064003818` |
+| 全输出关闭;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 步 | `A55A0204110000000000000000083500000301000000F468` |
 | X JOG 关闭,speed=3,1 步 | `A55A0204110000000000000000083500010301000000542D` |
 | X JOG 关闭,speed=3,1 步 | `A55A0204110000000000000000083500010301000000542D` |
 | Y JOG 打开,speed=3,1 步 | `A55A020411000000000000000008350100030100000095D0` |
 | Y JOG 打开,speed=3,1 步 | `A55A020411000000000000000008350100030100000095D0` |
 | Y JOG 关闭,speed=3,1 步 | `A55A02041100000000000000000835010103010000003595` |
 | 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 步 | `A55A02041100000000000000000835000003FFFF0000809A` |
 | X JOG 关闭,speed=3,65535 步 | `A55A02041100000000000000000835000103FFFF000020DF` |
 | X JOG 关闭,speed=3,65535 步 | `A55A02041100000000000000000835000103FFFF000020DF` |
 | Y JOG 打开,speed=3,65535 步 | `A55A02041100000000000000000835010003FFFF0000E122` |
 | Y JOG 打开,speed=3,65535 步 | `A55A02041100000000000000000835010003FFFF0000E122` |
@@ -78,16 +84,25 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\SEND_HEX.ps1 -Port COM
 | 旧 `0x29` 请求,固定返回 UNSUPPORTED | `A55A020405000000000000000004290000002A7A` |
 | 旧 `0x29` 请求,固定返回 UNSUPPORTED | `A55A020405000000000000000004290000002A7A` |
 | 旧 MARK_CLOSED X/DIR0,固定返回 UNSUPPORTED | `A55A0204110000000000000000083600000000000000E738` |
 | 旧 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` 的完整步周期分别是 `50/25/10/1 ms`。表中 65535 步 JOG 在 V1 中只实际执行 800 步。修改字段后必须重新计算 CRC,不能只替换表格 HEX 中的字节。
+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 步。修改字段后必须重新计算 CRC,不能只替换表格 HEX 中的字节。
 
 
-本次仅移除 CPLD 内部的 JOG busy/限位/watchdog-timeout 准入门,请求帧和 HEX 不变。`axis` 非 X/Y、非法方向或速度、`steps=0` 等线格式或字段错误仍返回 BAD_VALUE;这不属于 BUSY。
+请求帧和 HEX 不变。`axis` 非 X/Y、非法方向或速度、`steps=0` 等线格式或字段错误仍返回 BAD_VALUE;合法 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'
+```
 
 
 ## 已接受风险
 ## 已接受风险
 
 
-- 标准 CLOSE 即使已经到达机械关闭端仍会执行完整 3200 步。
-- 标准 OPEN 没有开端传感器保护。
-- JOG 完全忽略限位;单条最多 800 步,但重复发送可累计远超 800 步并造成机械损坏。
-- 同轴 JOG 可以替换标准 3200 步动作,ACK 只表示命令被接受,不表示机械已经到位。
-- watchdog 到期后的新 JOG 可以在不先 DISABLE 的情况下重新使能运动;操作员不能把 timeout 当作永久锁定。
+- legacy 标准 OPEN/CLOSE 命令不会驱动电机,必须使用 JOG。
+- JOG 完全忽略限位,单条最多实际执行 65535 步,可直接造成严重机械越程。
+- 同轴新 JOG 会截短旧 STEP 并立即覆盖旧剩余距离;ACK 只证明首个新 STEP 已发出。
+- DISABLE、watchdog、失联和 LS 都不能停止电机;异常时必须立即断电或复位/重新配置。
 - 固件不检测堵转、失步、限位卡低、相线接反或机械方向错误。
 - 固件不检测堵转、失步、限位卡低、相线接反或机械方向错误。
 - 本包生成和离线验证不等于实板机械验收。任何异常应立即断电;不得自动再次编程。
 - 本包生成和离线验证不等于实板机械验收。任何异常应立即断电;不得自动再次编程。

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 45 - 57
schemas/prod2u_p4_normal_host_contract_v4.schema.json


+ 77 - 248
src/rtl/prod2u_p4_axis_executor.v

@@ -1,291 +1,120 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
 
 
 module prod2u_p4_axis_executor #(
 module prod2u_p4_axis_executor #(
-    parameter integer STANDARD_STEPS = 3200,
-    /* verilator lint_off UNUSEDPARAM */
-    parameter integer LIMIT_CONFIRM_US = 1000,
-    /* verilator lint_on UNUSEDPARAM */
-    parameter integer DIR_SETUP_US = 1000,
-    parameter integer SPEED0_HALF_US = 25000,
-    parameter integer SPEED1_HALF_US = 12500,
-    parameter integer SPEED2_HALF_US = 5000,
-    parameter integer SPEED3_HALF_US = 500
+    parameter integer DIR_SETUP_CYCLES = 25000,
+    parameter integer STEP_HALF_CYCLES = 12500
 ) (
 ) (
     input  wire        clk,
     input  wire        clk,
     input  wire        rst_n,
     input  wire        rst_n,
-    input  wire        tick_1us,
-    input  wire        force_stop,
-    input  wire        limit_raw,
-    input  wire        jog_start,
-    input  wire        jog_dir,
-    input  wire [1:0]  jog_speed_code,
-    input  wire [15:0] jog_steps,
-    input  wire        standard_start,
-    input  wire        standard_target_open,
+    input  wire        command_start,
+    input  wire        command_dir,
+    input  wire [15:0] command_steps,
     output wire        step_out,
     output wire        step_out,
     output wire        dir_out,
     output wire        dir_out,
-    output wire        busy,
-    output wire        drive_active,
-    output wire        position_valid,
-    output wire [7:0]  current_aperture,
-    output wire [7:0]  target_aperture
+    output reg         started_pulse
 );
 );
-    localparam [2:0] PHASE_IDLE = 3'd0;
-    localparam [2:0] PHASE_DIR_SETUP = 3'd1;
-    localparam [2:0] PHASE_STEP_HIGH = 3'd2;
-    localparam [2:0] PHASE_STEP_LOW = 3'd3;
-
-    localparam [15:0] STANDARD_STEPS_16 = STANDARD_STEPS[15:0];
-    localparam [15:0] MAX_JOG_STEPS = 16'd800;
-    localparam [15:0] DIR_SETUP_TICKS =
-        (DIR_SETUP_US < 1) ? 16'd1 : DIR_SETUP_US[15:0];
-
-    // Retain only the physical input synchronizer for pin/CDC evidence. Its
-    // sampled value has no path into JOG or standard-motion control.
-    (* keep = "true" *)
-    /* verilator lint_off UNUSEDSIGNAL */
-    (* async_reg = "true" *) reg [2:0] limit_sync_pipe;
-    /* verilator lint_on UNUSEDSIGNAL */
+    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" *)
     (* keep = "true", syn_encoding = "sequential", fsm_encoding = "none" *)
-    reg [2:0] motion_phase;
-    reg step_reg;
+    reg [1:0] motion_phase;
     reg dir_reg;
     reg dir_reg;
-    reg busy_reg;
-    reg drive_reg;
-    reg position_valid_reg;
-    reg [7:0] current_aperture_reg;
-    reg [7:0] target_aperture_reg;
-    reg [15:0] remaining_steps_reg;
-    reg [15:0] phase_remaining_us;
-    reg [1:0] active_speed_code;
-    reg active_is_jog;
-
-    reg pending_jog_valid;
-    reg pending_jog_dir;
-    reg [1:0] pending_jog_speed_code;
-    reg [15:0] pending_jog_steps;
-
-    /* verilator lint_off UNUSEDSIGNAL */
-    wire unused_limit_cdc_tail = limit_sync_pipe[2];
-    /* verilator lint_on UNUSEDSIGNAL */
-    wire valid_jog_request = jog_start && (jog_steps != 16'd0);
-    wire [15:0] clamped_jog_steps =
-        (jog_steps > MAX_JOG_STEPS) ? MAX_JOG_STEPS : jog_steps;
-    wire replacement_jog_valid = valid_jog_request || pending_jog_valid;
-    wire replacement_jog_dir =
-        valid_jog_request ? jog_dir : pending_jog_dir;
-    wire [1:0] replacement_jog_speed_code =
-        valid_jog_request ? jog_speed_code : pending_jog_speed_code;
-    wire [15:0] replacement_jog_steps =
-        valid_jog_request ? clamped_jog_steps : pending_jog_steps;
-    wire [15:0] active_half_period_us =
-        half_period_for_speed(active_speed_code);
+    reg [15:0] remaining_steps;
+    reg [PHASE_COUNTER_BITS-1:0] phase_counter;
 
 
-    assign step_out = force_stop ? 1'b0 : step_reg;
+    assign step_out = (motion_phase == PHASE_STEP_HIGH);
     assign dir_out = dir_reg;
     assign dir_out = dir_reg;
-    assign busy = force_stop ? 1'b0 : busy_reg;
-    assign drive_active = force_stop ? 1'b0 : drive_reg;
-    assign position_valid = position_valid_reg;
-    assign current_aperture = current_aperture_reg;
-    assign target_aperture = target_aperture_reg;
 
 
-    function [15:0] half_period_for_speed;
-        input [1:0] speed_code;
-        begin
-            case (speed_code)
-                2'd0: half_period_for_speed =
-                    (SPEED0_HALF_US < 1) ? 16'd1 : SPEED0_HALF_US[15:0];
-                2'd1: half_period_for_speed =
-                    (SPEED1_HALF_US < 1) ? 16'd1 : SPEED1_HALF_US[15:0];
-                2'd2: half_period_for_speed =
-                    (SPEED2_HALF_US < 1) ? 16'd1 : SPEED2_HALF_US[15:0];
-                default: half_period_for_speed =
-                    (SPEED3_HALF_US < 1) ? 16'd1 : SPEED3_HALF_US[15:0];
-            endcase
+    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
         end
-    endfunction
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            limit_sync_pipe <= 3'b000;
-        end else begin
-            limit_sync_pipe <= {limit_sync_pipe[1:0], limit_raw};
-        end
-    end
+    endgenerate
 
 
     always @(posedge clk or negedge rst_n) begin
     always @(posedge clk or negedge rst_n) begin
         if (!rst_n) begin
         if (!rst_n) begin
             motion_phase <= PHASE_IDLE;
             motion_phase <= PHASE_IDLE;
-            step_reg <= 1'b0;
             dir_reg <= 1'b0;
             dir_reg <= 1'b0;
-            busy_reg <= 1'b0;
-            drive_reg <= 1'b0;
-            position_valid_reg <= 1'b0;
-            current_aperture_reg <= 8'hff;
-            target_aperture_reg <= 8'hff;
-            remaining_steps_reg <= 16'd0;
-            phase_remaining_us <= 16'd0;
-            active_speed_code <= 2'd0;
-            active_is_jog <= 1'b0;
-            pending_jog_valid <= 1'b0;
-            pending_jog_dir <= 1'b0;
-            pending_jog_speed_code <= 2'd0;
-            pending_jog_steps <= 16'd0;
-        end else if (force_stop) begin
-            motion_phase <= PHASE_IDLE;
-            step_reg <= 1'b0;
-            busy_reg <= 1'b0;
-            drive_reg <= 1'b0;
-            position_valid_reg <= 1'b0;
-            current_aperture_reg <= 8'hff;
-            target_aperture_reg <= 8'hff;
-            remaining_steps_reg <= 16'd0;
-            phase_remaining_us <= 16'd0;
-            active_is_jog <= 1'b0;
-            pending_jog_valid <= 1'b0;
-            pending_jog_steps <= 16'd0;
+            remaining_steps <= 16'd0;
+            phase_counter <= {PHASE_COUNTER_BITS{1'b0}};
+            started_pulse <= 1'b0;
         end else begin
         end else begin
-            // While a complete STEP cycle is in flight, each valid JOG only
-            // replaces this one-slot mailbox. The low-tail boundary consumes
-            // the latest values atomically.
-            if (valid_jog_request &&
-                ((motion_phase == PHASE_STEP_HIGH) ||
-                 (motion_phase == PHASE_STEP_LOW))) begin
-                pending_jog_valid <= 1'b1;
-                pending_jog_dir <= jog_dir;
-                pending_jog_speed_code <= jog_speed_code;
-                pending_jog_steps <= clamped_jog_steps;
-                position_valid_reg <= 1'b0;
-                current_aperture_reg <= 8'hff;
-                target_aperture_reg <= 8'hff;
-            end
-
-            case (motion_phase)
-                PHASE_IDLE: begin
-                    step_reg <= 1'b0;
-                    busy_reg <= 1'b0;
-                    drive_reg <= 1'b0;
-                    remaining_steps_reg <= 16'd0;
-                    pending_jog_valid <= 1'b0;
-
-                    if (valid_jog_request) begin
-                        dir_reg <= jog_dir;
-                        drive_reg <= 1'b1;
-                        position_valid_reg <= 1'b0;
-                        current_aperture_reg <= 8'hff;
-                        target_aperture_reg <= 8'hff;
-                        remaining_steps_reg <= clamped_jog_steps;
-                        phase_remaining_us <= DIR_SETUP_TICKS;
-                        active_speed_code <= jog_speed_code;
-                        active_is_jog <= 1'b1;
-                        motion_phase <= PHASE_DIR_SETUP;
-                    end else if (standard_start) begin
-                        dir_reg <= !standard_target_open;
-                        drive_reg <= 1'b1;
-                        position_valid_reg <= 1'b0;
-                        current_aperture_reg <= 8'hfe;
-                        target_aperture_reg <=
-                            standard_target_open ? 8'd100 : 8'd0;
-                        remaining_steps_reg <= STANDARD_STEPS_16;
-                        phase_remaining_us <= DIR_SETUP_TICKS;
-                        active_speed_code <= 2'd3;
-                        active_is_jog <= 1'b0;
-                        motion_phase <= PHASE_DIR_SETUP;
-                    end
+            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;
+                if (command_steps == 16'd0) begin
+                    motion_phase <= PHASE_IDLE;
+                    phase_counter <= {PHASE_COUNTER_BITS{1'b0}};
+                end else begin
+                    motion_phase <= PHASE_DIR_SETUP;
+                    phase_counter <= DIR_SETUP_LAST;
                 end
                 end
+            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
-                    step_reg <= 1'b0;
-                    busy_reg <= 1'b0;
-                    drive_reg <= 1'b1;
-
-                    if (valid_jog_request) begin
-                        dir_reg <= jog_dir;
-                        position_valid_reg <= 1'b0;
-                        current_aperture_reg <= 8'hff;
-                        target_aperture_reg <= 8'hff;
-                        remaining_steps_reg <= clamped_jog_steps;
-                        phase_remaining_us <= DIR_SETUP_TICKS;
-                        active_speed_code <= jog_speed_code;
-                        active_is_jog <= 1'b1;
-                        pending_jog_valid <= 1'b0;
-                    end else if (tick_1us) begin
-                        if (phase_remaining_us > 16'd1) begin
-                            phase_remaining_us <= phase_remaining_us - 16'd1;
+                    PHASE_DIR_SETUP: begin
+                        if (phase_counter != {PHASE_COUNTER_BITS{1'b0}}) begin
+                            phase_counter <= phase_counter - 1'b1;
                         end else begin
                         end else begin
-                            step_reg <= 1'b1;
-                            busy_reg <= 1'b1;
-                            phase_remaining_us <= active_half_period_us;
                             motion_phase <= PHASE_STEP_HIGH;
                             motion_phase <= PHASE_STEP_HIGH;
+                            phase_counter <= STEP_HALF_LAST;
+                            started_pulse <= 1'b1;
                         end
                         end
                     end
                     end
-                end
 
 
-                PHASE_STEP_HIGH: begin
-                    if (tick_1us) begin
-                        if (phase_remaining_us > 16'd1) begin
-                            phase_remaining_us <= phase_remaining_us - 16'd1;
+                    PHASE_STEP_HIGH: begin
+                        if (phase_counter != {PHASE_COUNTER_BITS{1'b0}}) begin
+                            phase_counter <= phase_counter - 1'b1;
                         end else begin
                         end else begin
-                            step_reg <= 1'b0;
-                            phase_remaining_us <= active_half_period_us;
                             motion_phase <= PHASE_STEP_LOW;
                             motion_phase <= PHASE_STEP_LOW;
+                            phase_counter <= STEP_HALF_LAST;
                         end
                         end
                     end
                     end
-                end
 
 
-                PHASE_STEP_LOW: begin
-                    step_reg <= 1'b0;
-                    if (tick_1us) begin
-                        if (phase_remaining_us > 16'd1) begin
-                            phase_remaining_us <= phase_remaining_us - 16'd1;
-                        end else if (replacement_jog_valid) begin
-                            dir_reg <= replacement_jog_dir;
-                            busy_reg <= 1'b0;
-                            drive_reg <= 1'b1;
-                            position_valid_reg <= 1'b0;
-                            current_aperture_reg <= 8'hff;
-                            target_aperture_reg <= 8'hff;
-                            remaining_steps_reg <= replacement_jog_steps;
-                            phase_remaining_us <= DIR_SETUP_TICKS;
-                            active_speed_code <=
-                                replacement_jog_speed_code;
-                            active_is_jog <= 1'b1;
-                            pending_jog_valid <= 1'b0;
-                            motion_phase <= PHASE_DIR_SETUP;
-                        end else if (remaining_steps_reg <= 16'd1) begin
-                            remaining_steps_reg <= 16'd0;
-                            busy_reg <= 1'b0;
-                            drive_reg <= 1'b0;
+                    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;
                             motion_phase <= PHASE_IDLE;
-                            if (!active_is_jog) begin
-                                position_valid_reg <= 1'b1;
-                                current_aperture_reg <= target_aperture_reg;
-                            end
-                            active_is_jog <= 1'b0;
+                            remaining_steps <= 16'd0;
+                            phase_counter <= {PHASE_COUNTER_BITS{1'b0}};
                         end else begin
                         end else begin
-                            remaining_steps_reg <= remaining_steps_reg - 16'd1;
-                            step_reg <= 1'b1;
-                            phase_remaining_us <= active_half_period_us;
                             motion_phase <= PHASE_STEP_HIGH;
                             motion_phase <= PHASE_STEP_HIGH;
+                            remaining_steps <= remaining_steps - 16'd1;
+                            phase_counter <= STEP_HALF_LAST;
                         end
                         end
                     end
                     end
-                end
 
 
-                default: begin
-                    motion_phase <= PHASE_IDLE;
-                    step_reg <= 1'b0;
-                    busy_reg <= 1'b0;
-                    drive_reg <= 1'b0;
-                    position_valid_reg <= 1'b0;
-                    current_aperture_reg <= 8'hff;
-                    target_aperture_reg <= 8'hff;
-                    remaining_steps_reg <= 16'd0;
-                    active_is_jog <= 1'b0;
-                    pending_jog_valid <= 1'b0;
-                end
-            endcase
+                    default: begin
+                        motion_phase <= PHASE_IDLE;
+                        remaining_steps <= 16'd0;
+                        phase_counter <= {PHASE_COUNTER_BITS{1'b0}};
+                    end
+                endcase
+            end
         end
         end
     end
     end
-
 endmodule
 endmodule

+ 23 - 164
src/rtl/prod2u_p4_motor_hub.v

@@ -1,199 +1,58 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
 
 
 module prod2u_p4_motor_hub #(
 module prod2u_p4_motor_hub #(
-    parameter integer STANDARD_STEPS = 3200,
-    parameter integer LIMIT_CONFIRM_US = 1000,
-    parameter integer DIR_SETUP_US = 1000,
-    parameter integer SPEED0_HALF_US = 25000,
-    parameter integer SPEED1_HALF_US = 12500,
-    parameter integer SPEED2_HALF_US = 5000,
-    parameter integer SPEED3_HALF_US = 500
+    parameter integer DIR_SETUP_CYCLES = 25000,
+    parameter integer STEP_HALF_CYCLES = 12500
 ) (
 ) (
     input  wire        clk,
     input  wire        clk,
     input  wire        rst_n,
     input  wire        rst_n,
-    input  wire        tick_1us,
-    input  wire        force_stop,
-    input  wire        disabled,
-    input  wire        watchdog_timeout,
-    input  wire        x_limit_raw,
-    input  wire        y_limit_raw,
-    input  wire        snapshot_valid,
-    input  wire [23:0] snapshot_targets,
-    input  wire [2:0]  snapshot_busy_at_accept,
-    output reg         snapshot_result_valid,
-    output reg  [2:0]  snapshot_busy_mask,
-    output reg  [2:0]  snapshot_invalid_mask,
-    output reg  [2:0]  snapshot_accepted_mask,
-    input  wire        jog_valid,
+    input  wire        jog_start,
     input  wire [1:0]  jog_axis,
     input  wire [1:0]  jog_axis,
     input  wire        jog_dir,
     input  wire        jog_dir,
-    input  wire [1:0]  jog_speed_code,
     input  wire [15:0] jog_steps,
     input  wire [15:0] jog_steps,
-    output reg         jog_result_valid,
-    output reg         jog_accepted,
-    output wire [2:0]  axis_active_mask,
-    output wire [2:0]  axis_busy_mask,
+    output wire [1:0]  axis_started_pulse,
     output wire [2:0]  step_out,
     output wire [2:0]  step_out,
-    output wire [2:0]  dir_out,
-    output wire        en_n,
-    output reg  [79:0] status_payload
+    output wire [2:0]  dir_out
 );
 );
-    wire command_hard_stop = force_stop || disabled || watchdog_timeout;
-    wire output_inhibit = force_stop || disabled || watchdog_timeout;
-
-    wire [7:0] x_requested_target = snapshot_targets[7:0];
-    wire [7:0] y_requested_target = snapshot_targets[15:8];
-    wire [7:0] z_requested_target = snapshot_targets[23:16];
-    wire x_target_valid = (x_requested_target == 8'd0) ||
-        (x_requested_target == 8'd100);
-    wire y_target_valid = (y_requested_target == 8'd0) ||
-        (y_requested_target == 8'd100);
-    wire z_target_valid = (z_requested_target == 8'd0) ||
-        (z_requested_target == 8'd100);
-
     wire x_step;
     wire x_step;
     wire y_step;
     wire y_step;
     wire x_dir;
     wire x_dir;
     wire y_dir;
     wire y_dir;
-    wire x_busy;
-    wire y_busy;
-    wire x_drive_request;
-    wire y_drive_request;
-    wire x_position_valid;
-    wire y_position_valid;
-    wire [7:0] x_current;
-    wire [7:0] y_current;
-    wire [7:0] x_target;
-    wire [7:0] y_target;
-    wire [2:0] axis_active = {1'b0, y_drive_request, x_drive_request};
-    wire [2:0] axis_busy = {1'b0, y_busy, x_busy};
-    wire [2:0] snapshot_busy_now = snapshot_busy_at_accept;
-    wire [2:0] snapshot_invalid_now = {
-        !z_target_valid,
-        !snapshot_busy_now[1] && !y_target_valid,
-        !snapshot_busy_now[0] && !x_target_valid
-    };
-    wire [2:0] snapshot_accepted_now = {
-        !snapshot_busy_now[2] && z_target_valid && !command_hard_stop,
-        !snapshot_busy_now[1] && y_target_valid && !command_hard_stop,
-        !snapshot_busy_now[0] && x_target_valid && !command_hard_stop
-    };
+    wire x_started_pulse;
+    wire y_started_pulse;
 
 
-    wire jog_parameters_valid = (jog_axis < 2'd2) &&
-        (jog_steps != 16'd0);
-    wire jog_accept_now = jog_parameters_valid;
+    wire x_command_start = jog_start && (jog_axis == 2'd0);
+    wire y_command_start = jog_start && (jog_axis == 2'd1);
 
 
-    wire x_standard_start = snapshot_valid && snapshot_accepted_now[0];
-    wire y_standard_start = snapshot_valid && snapshot_accepted_now[1];
-    wire x_jog_start = jog_valid && jog_accept_now && (jog_axis == 2'd0);
-    wire y_jog_start = jog_valid && jog_accept_now && (jog_axis == 2'd1);
-
-    assign axis_active_mask = axis_active;
-    assign axis_busy_mask = axis_busy;
-    assign step_out = output_inhibit ? 3'b000 : {1'b0, y_step, x_step};
+    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};
     assign dir_out = {1'b0, y_dir, x_dir};
-    assign en_n = output_inhibit || !(x_drive_request || y_drive_request);
 
 
     prod2u_p4_axis_executor #(
     prod2u_p4_axis_executor #(
-        .STANDARD_STEPS(STANDARD_STEPS),
-        .LIMIT_CONFIRM_US(LIMIT_CONFIRM_US),
-        .DIR_SETUP_US(DIR_SETUP_US),
-        .SPEED0_HALF_US(SPEED0_HALF_US),
-        .SPEED1_HALF_US(SPEED1_HALF_US),
-        .SPEED2_HALF_US(SPEED2_HALF_US),
-        .SPEED3_HALF_US(SPEED3_HALF_US)
+        .DIR_SETUP_CYCLES(DIR_SETUP_CYCLES),
+        .STEP_HALF_CYCLES(STEP_HALF_CYCLES)
     ) u_x_axis (
     ) u_x_axis (
         .clk(clk),
         .clk(clk),
         .rst_n(rst_n),
         .rst_n(rst_n),
-        .tick_1us(tick_1us),
-        .force_stop(command_hard_stop),
-        .limit_raw(x_limit_raw),
-        .jog_start(x_jog_start),
-        .jog_dir(jog_dir),
-        .jog_speed_code(jog_speed_code),
-        .jog_steps(jog_steps),
-        .standard_start(x_standard_start),
-        .standard_target_open(x_requested_target == 8'd100),
+        .command_start(x_command_start),
+        .command_dir(jog_dir),
+        .command_steps(jog_steps),
         .step_out(x_step),
         .step_out(x_step),
         .dir_out(x_dir),
         .dir_out(x_dir),
-        .busy(x_busy),
-        .drive_active(x_drive_request),
-        .position_valid(x_position_valid),
-        .current_aperture(x_current),
-        .target_aperture(x_target)
+        .started_pulse(x_started_pulse)
     );
     );
 
 
     prod2u_p4_axis_executor #(
     prod2u_p4_axis_executor #(
-        .STANDARD_STEPS(STANDARD_STEPS),
-        .LIMIT_CONFIRM_US(LIMIT_CONFIRM_US),
-        .DIR_SETUP_US(DIR_SETUP_US),
-        .SPEED0_HALF_US(SPEED0_HALF_US),
-        .SPEED1_HALF_US(SPEED1_HALF_US),
-        .SPEED2_HALF_US(SPEED2_HALF_US),
-        .SPEED3_HALF_US(SPEED3_HALF_US)
+        .DIR_SETUP_CYCLES(DIR_SETUP_CYCLES),
+        .STEP_HALF_CYCLES(STEP_HALF_CYCLES)
     ) u_y_axis (
     ) u_y_axis (
         .clk(clk),
         .clk(clk),
         .rst_n(rst_n),
         .rst_n(rst_n),
-        .tick_1us(tick_1us),
-        .force_stop(command_hard_stop),
-        .limit_raw(y_limit_raw),
-        .jog_start(y_jog_start),
-        .jog_dir(jog_dir),
-        .jog_speed_code(jog_speed_code),
-        .jog_steps(jog_steps),
-        .standard_start(y_standard_start),
-        .standard_target_open(y_requested_target == 8'd100),
+        .command_start(y_command_start),
+        .command_dir(jog_dir),
+        .command_steps(jog_steps),
         .step_out(y_step),
         .step_out(y_step),
         .dir_out(y_dir),
         .dir_out(y_dir),
-        .busy(y_busy),
-        .drive_active(y_drive_request),
-        .position_valid(y_position_valid),
-        .current_aperture(y_current),
-        .target_aperture(y_target)
+        .started_pulse(y_started_pulse)
     );
     );
-
-    always @(*) begin
-        status_payload = 80'd0;
-        status_payload[7:0] = {
-            4'd0,
-            watchdog_timeout,
-            disabled,
-            !en_n,
-            |axis_busy
-        };
-        status_payload[15:8] = {5'd0, 1'b0,
-            y_position_valid, x_position_valid};
-        status_payload[23:16] = {5'd0, axis_busy};
-        status_payload[31:24] = x_current;
-        status_payload[39:32] = y_current;
-        status_payload[47:40] = 8'hff;
-        status_payload[55:48] = x_target;
-        status_payload[63:56] = y_target;
-        status_payload[71:64] = 8'hff;
-        status_payload[79:72] = 8'd0;
-    end
-
-    always @(posedge clk or negedge rst_n) begin
-        if (!rst_n) begin
-            snapshot_result_valid <= 1'b0;
-            snapshot_busy_mask <= 3'd0;
-            snapshot_invalid_mask <= 3'd0;
-            snapshot_accepted_mask <= 3'd0;
-            jog_result_valid <= 1'b0;
-            jog_accepted <= 1'b0;
-        end else begin
-            snapshot_result_valid <= snapshot_valid;
-            jog_result_valid <= jog_valid;
-
-            if (snapshot_valid) begin
-                snapshot_busy_mask <= snapshot_busy_now;
-                snapshot_invalid_mask <= snapshot_invalid_now;
-                snapshot_accepted_mask <= snapshot_accepted_now;
-            end
-
-            if (jog_valid) begin
-                jog_accepted <= jog_accept_now;
-            end
-        end
-    end
 endmodule
 endmodule

+ 147 - 315
src/rtl/prod2u_p4_normal_v3_core.v

@@ -3,32 +3,22 @@
 module prod2u_p4_normal_v3_core #(
 module prod2u_p4_normal_v3_core #(
     parameter integer CLK_HZ = 25000000,
     parameter integer CLK_HZ = 25000000,
     parameter integer WATCHDOG_SECONDS = 5,
     parameter integer WATCHDOG_SECONDS = 5,
-    parameter integer STANDARD_STEPS = 3200,
-    parameter integer LIMIT_CONFIRM_US = 1000,
-    parameter integer DIR_SETUP_US = 1000,
-    parameter integer SPEED0_HALF_US = 25000,
-    parameter integer SPEED1_HALF_US = 12500,
-    parameter integer SPEED2_HALF_US = 5000,
-    parameter integer SPEED3_HALF_US = 500
+    parameter integer DIR_SETUP_CYCLES = 25000,
+    parameter integer STEP_HALF_CYCLES = 12500
 ) (
 ) (
     input  wire         clk,
     input  wire         clk,
     input  wire         rst_n,
     input  wire         rst_n,
-    input  wire         tick_1us,
     input  wire         request_valid,
     input  wire         request_valid,
     output wire         request_ready,
     output wire         request_ready,
     input  wire [7:0]   request_type,
     input  wire [7:0]   request_type,
     input  wire [5:0]   request_length,
     input  wire [5:0]   request_length,
     input  wire [271:0] request_payload,
     input  wire [271:0] request_payload,
     input  wire [15:0]  request_crc16,
     input  wire [15:0]  request_crc16,
-    input  wire         emergency_disable_valid,
-    input  wire [15:0]  emergency_disable_crc16,
     output wire         frame_valid,
     output wire         frame_valid,
     input  wire         frame_ready,
     input  wire         frame_ready,
     output wire [7:0]   frame_type,
     output wire [7:0]   frame_type,
     output wire [7:0]   frame_payload_len,
     output wire [7:0]   frame_payload_len,
     output wire [143:0] frame_payload,
     output wire [143:0] frame_payload,
-    input  wire         x_limit_raw,
-    input  wire         y_limit_raw,
     output wire [191:0] ptc_percent,
     output wire [191:0] ptc_percent,
     output wire [31:0]  fan_percent,
     output wire [31:0]  fan_percent,
     output wire [7:0]   solenoid_percent,
     output wire [7:0]   solenoid_percent,
@@ -56,17 +46,12 @@ module prod2u_p4_normal_v3_core #(
     localparam [7:0] STATUS_BAD_FLAGS = 8'h02;
     localparam [7:0] STATUS_BAD_FLAGS = 8'h02;
     localparam [7:0] STATUS_BAD_LENGTH = 8'h03;
     localparam [7:0] STATUS_BAD_LENGTH = 8'h03;
     localparam [7:0] STATUS_BAD_VALUE = 8'h05;
     localparam [7:0] STATUS_BAD_VALUE = 8'h05;
-    localparam [7:0] STATUS_BUSY = 8'h09;
-    localparam [7:0] STATUS_PARTIAL = 8'h16;
-    localparam [15:0] SAFE_STATE_HASH16 = 16'he177;
 
 
     localparam [2:0] ST_IDLE = 3'd0;
     localparam [2:0] ST_IDLE = 3'd0;
     localparam [2:0] ST_SNAPSHOT_VALIDATE = 3'd1;
     localparam [2:0] ST_SNAPSHOT_VALIDATE = 3'd1;
-    localparam [2:0] ST_SNAPSHOT_MOTOR = 3'd2;
-    localparam [2:0] ST_SNAPSHOT_COMMIT = 3'd3;
-    localparam [2:0] ST_JOG = 3'd4;
-    localparam [2:0] ST_DISABLE_WAIT = 3'd5;
-    localparam [2:0] ST_WATCHDOG_ABORT = 3'd6;
+    localparam [2:0] ST_SNAPSHOT_COMMIT = 3'd2;
+    localparam [2:0] ST_JOG_WAIT_START = 3'd3;
+    localparam [2:0] ST_DISABLE_WAIT = 3'd4;
 
 
     reg [2:0] state;
     reg [2:0] state;
     wire command_accept = request_valid && request_ready;
     wire command_accept = request_valid && request_ready;
@@ -75,102 +60,64 @@ module prod2u_p4_normal_v3_core #(
     wire [7:0] request_value = request_payload[23:16];
     wire [7:0] request_value = request_payload[23:16];
     wire [7:0] request_flags = request_payload[31:24];
     wire [7:0] request_flags = request_payload[31:24];
     wire [15:0] request_steps = request_payload[47:32];
     wire [15:0] request_steps = request_payload[47:32];
-
     wire host_zeros_valid = (request_channel == 8'd0) &&
     wire host_zeros_valid = (request_channel == 8'd0) &&
         (request_value == 8'd0) && (request_flags == 8'd0);
         (request_value == 8'd0) && (request_flags == 8'd0);
     wire jog_payload_valid = (request_channel <= 8'd1) &&
     wire jog_payload_valid = (request_channel <= 8'd1) &&
         (request_value <= 8'd1) && (request_flags <= 8'd3) &&
         (request_value <= 8'd1) && (request_flags <= 8'd3) &&
         (request_steps != 16'd0) && (request_payload[63:48] == 16'd0);
         (request_steps != 16'd0) && (request_payload[63:48] == 16'd0);
     wire motor_status_payload_valid = (request_payload[63:8] == 56'd0);
     wire motor_status_payload_valid = (request_payload[63:8] == 56'd0);
-    wire watchdog_armed;
-    wire watchdog_force_safe;
-    wire watchdog_expiry_due;
 
 
-    wire snapshot_request_valid = command_accept &&
-        (request_type == FT_HOST_BATCH_CMD) && (request_length == 6'd34) &&
-        !watchdog_timeout && !watchdog_expiry_due;
+    reg snapshot_scan_start;
+    reg snapshot_commit_authorize;
+    reg [271:0] snapshot_payload_latched;
     wire snapshot_ready;
     wire snapshot_ready;
     wire snapshot_output_result_valid;
     wire snapshot_output_result_valid;
     wire snapshot_output_accepted;
     wire snapshot_output_accepted;
     wire snapshot_commit_pulse;
     wire snapshot_commit_pulse;
-    reg snapshot_commit_authorize;
-    reg [23:0] snapshot_targets_latched;
-    reg [2:0] snapshot_busy_at_accept;
-    reg snapshot_solenoid_ignored;
-    reg [2:0] snapshot_busy_latched;
-    reg [2:0] snapshot_invalid_latched;
-    reg [2:0] snapshot_accepted_latched;
 
 
-    reg motor_snapshot_start;
-    wire motor_snapshot_result_valid;
-    wire [2:0] motor_snapshot_busy_mask;
-    wire [2:0] motor_snapshot_invalid_mask;
-    wire [2:0] motor_snapshot_accepted_mask;
     reg motor_jog_start;
     reg motor_jog_start;
     reg [1:0] motor_jog_axis;
     reg [1:0] motor_jog_axis;
     reg motor_jog_dir;
     reg motor_jog_dir;
-    reg [1:0] motor_jog_speed;
     reg [15:0] motor_jog_steps;
     reg [15:0] motor_jog_steps;
-    wire motor_jog_result_valid;
-    wire motor_jog_accepted;
-    wire [2:0] motor_axis_active_mask;
-    wire [2:0] motor_axis_busy_mask;
-    wire [79:0] motor_status_payload;
+    reg [1:0] jog_wait_axis;
+    wire [1:0] motor_axis_started_pulse;
 
 
     reg watchdog_disable;
     reg watchdog_disable;
-    wire watchdog_disable_request = watchdog_disable || emergency_disable_valid;
+    reg watchdog_snapshot_arm;
+    wire watchdog_armed;
+    wire watchdog_force_safe;
+    wire watchdog_expiry_due;
     wire watchdog_status_refresh = command_accept &&
     wire watchdog_status_refresh = command_accept &&
         (request_type == FT_MOTION_CMD) && (request_length == 6'd8) &&
         (request_type == FT_MOTION_CMD) && (request_length == 6'd8) &&
         (request_command == MOTION_GET_STATUS) && motor_status_payload_valid &&
         (request_command == MOTION_GET_STATUS) && motor_status_payload_valid &&
         watchdog_armed;
         watchdog_armed;
-    wire jog_action_accept = command_accept &&
-        (request_type == FT_MOTION_CMD) && (request_length == 6'd8) &&
-        (request_command == MOTION_JOG) && jog_payload_valid;
-    wire snapshot_action_accept = (state == ST_SNAPSHOT_VALIDATE) &&
-        snapshot_output_result_valid && snapshot_output_accepted;
-    wire watchdog_action_arm = jog_action_accept || snapshot_action_accept;
-    wire force_safe = watchdog_force_safe || emergency_disable_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_inflight;
-    reg [7:0] command_frame_type;
-    reg [7:0] command_opcode;
     reg command_response_valid;
     reg command_response_valid;
     reg [63:0] command_ack_payload;
     reg [63:0] command_ack_payload;
     reg command_followup_valid;
     reg command_followup_valid;
     reg [7:0] command_followup_frame_type;
     reg [7:0] command_followup_frame_type;
     reg [79:0] command_followup_payload;
     reg [79:0] command_followup_payload;
-    reg deferred_disable_pending;
-    wire active_disable_command = command_inflight &&
-        (command_frame_type == FT_HOST_CMD) && (command_opcode == CMD_DISABLE);
-
     wire response_command_done;
     wire response_command_done;
     wire response_frame_valid;
     wire response_frame_valid;
     wire [7:0] response_frame_type;
     wire [7:0] response_frame_type;
     wire [7:0] response_payload_len;
     wire [7:0] response_payload_len;
     wire [143:0] response_payload;
     wire [143:0] response_payload;
-    wire [7:0] snapshot_requested_solenoid = request_payload[247:240];
-    wire snapshot_requested_solenoid_valid =
-        (snapshot_requested_solenoid == 8'd0) ||
-        (snapshot_requested_solenoid == 8'd100);
-    wire snapshot_solenoid_ignored_now = snapshot_requested_solenoid_valid &&
-        (|motor_axis_active_mask) &&
-        (snapshot_requested_solenoid != solenoid_percent);
-    wire [7:0] snapshot_effective_solenoid = snapshot_solenoid_ignored_now ?
-        solenoid_percent : snapshot_requested_solenoid;
-    wire [271:0] snapshot_payload_for_outputs = {
-        request_payload[271:248],
-        snapshot_effective_solenoid,
-        request_payload[239:0]
-    };
 
 
     assign request_ready = (state == ST_IDLE) && !command_inflight &&
     assign request_ready = (state == ST_IDLE) && !command_inflight &&
-        !deferred_disable_pending && !watchdog_expiry_due &&
         (!request_valid || (request_type != FT_HOST_BATCH_CMD) ||
         (!request_valid || (request_type != FT_HOST_BATCH_CMD) ||
          (request_length != 6'd34) || snapshot_ready);
          (request_length != 6'd34) || snapshot_ready);
     assign frame_valid = response_frame_valid;
     assign frame_valid = response_frame_valid;
     assign frame_type = response_frame_type;
     assign frame_type = response_frame_type;
     assign frame_payload_len = response_payload_len;
     assign frame_payload_len = response_payload_len;
     assign frame_payload = response_payload;
     assign frame_payload = response_payload;
+    assign en_n = 1'b0;
 
 
     task queue_response;
     task queue_response;
         input response_ok;
         input response_ok;
@@ -203,10 +150,10 @@ module prod2u_p4_normal_v3_core #(
     prod2u_p4_normal_v3_output_state u_outputs (
     prod2u_p4_normal_v3_output_state u_outputs (
         .clk(clk),
         .clk(clk),
         .rst_n(rst_n),
         .rst_n(rst_n),
-        .force_safe(force_safe),
-        .snapshot_valid(snapshot_request_valid),
+        .force_safe(watchdog_force_safe),
+        .snapshot_valid(snapshot_scan_start),
         .snapshot_ready(snapshot_ready),
         .snapshot_ready(snapshot_ready),
-        .snapshot_payload(snapshot_payload_for_outputs),
+        .snapshot_payload(snapshot_payload_latched),
         .commit_authorize(snapshot_commit_authorize),
         .commit_authorize(snapshot_commit_authorize),
         .result_valid(snapshot_output_result_valid),
         .result_valid(snapshot_output_result_valid),
         .result_accepted(snapshot_output_accepted),
         .result_accepted(snapshot_output_accepted),
@@ -223,9 +170,9 @@ module prod2u_p4_normal_v3_core #(
     ) u_watchdog (
     ) u_watchdog (
         .clk(clk),
         .clk(clk),
         .rst_n(rst_n),
         .rst_n(rst_n),
-        .arm(watchdog_action_arm),
+        .arm(watchdog_snapshot_arm),
         .refresh(watchdog_status_refresh),
         .refresh(watchdog_status_refresh),
-        .disable_cmd(watchdog_disable_request),
+        .disable_cmd(watchdog_disable),
         .disabled(disabled),
         .disabled(disabled),
         .armed(watchdog_armed),
         .armed(watchdog_armed),
         .watchdog_timeout(watchdog_timeout),
         .watchdog_timeout(watchdog_timeout),
@@ -234,42 +181,18 @@ module prod2u_p4_normal_v3_core #(
     );
     );
 
 
     prod2u_p4_motor_hub #(
     prod2u_p4_motor_hub #(
-        .STANDARD_STEPS(STANDARD_STEPS),
-        .LIMIT_CONFIRM_US(LIMIT_CONFIRM_US),
-        .DIR_SETUP_US(DIR_SETUP_US),
-        .SPEED0_HALF_US(SPEED0_HALF_US),
-        .SPEED1_HALF_US(SPEED1_HALF_US),
-        .SPEED2_HALF_US(SPEED2_HALF_US),
-        .SPEED3_HALF_US(SPEED3_HALF_US)
+        .DIR_SETUP_CYCLES(DIR_SETUP_CYCLES),
+        .STEP_HALF_CYCLES(STEP_HALF_CYCLES)
     ) u_motors (
     ) u_motors (
         .clk(clk),
         .clk(clk),
         .rst_n(rst_n),
         .rst_n(rst_n),
-        .tick_1us(tick_1us),
-        .force_stop(force_safe),
-        .disabled(disabled),
-        .watchdog_timeout(watchdog_timeout),
-        .x_limit_raw(x_limit_raw),
-        .y_limit_raw(y_limit_raw),
-        .snapshot_valid(motor_snapshot_start),
-        .snapshot_targets(snapshot_targets_latched),
-        .snapshot_busy_at_accept(snapshot_busy_at_accept),
-        .snapshot_result_valid(motor_snapshot_result_valid),
-        .snapshot_busy_mask(motor_snapshot_busy_mask),
-        .snapshot_invalid_mask(motor_snapshot_invalid_mask),
-        .snapshot_accepted_mask(motor_snapshot_accepted_mask),
-        .jog_valid(motor_jog_start),
+        .jog_start(motor_jog_start),
         .jog_axis(motor_jog_axis),
         .jog_axis(motor_jog_axis),
         .jog_dir(motor_jog_dir),
         .jog_dir(motor_jog_dir),
-        .jog_speed_code(motor_jog_speed),
         .jog_steps(motor_jog_steps),
         .jog_steps(motor_jog_steps),
-        .jog_result_valid(motor_jog_result_valid),
-        .jog_accepted(motor_jog_accepted),
-        .axis_active_mask(motor_axis_active_mask),
+        .axis_started_pulse(motor_axis_started_pulse),
         .step_out(step_out),
         .step_out(step_out),
-        .dir_out(dir_out),
-        .en_n(en_n),
-        .status_payload(motor_status_payload),
-        .axis_busy_mask(motor_axis_busy_mask)
+        .dir_out(dir_out)
     );
     );
 
 
     prod2u_p4_response_scheduler u_response_scheduler (
     prod2u_p4_response_scheduler u_response_scheduler (
@@ -291,34 +214,28 @@ module prod2u_p4_normal_v3_core #(
     always @(posedge clk or negedge rst_n) begin
     always @(posedge clk or negedge rst_n) begin
         if (!rst_n) begin
         if (!rst_n) begin
             state <= ST_IDLE;
             state <= ST_IDLE;
+            snapshot_scan_start <= 1'b0;
             snapshot_commit_authorize <= 1'b0;
             snapshot_commit_authorize <= 1'b0;
-            snapshot_targets_latched <= 24'd0;
-            snapshot_busy_at_accept <= 3'd0;
-            snapshot_solenoid_ignored <= 1'b0;
-            snapshot_busy_latched <= 3'd0;
-            snapshot_invalid_latched <= 3'd0;
-            snapshot_accepted_latched <= 3'd0;
-            motor_snapshot_start <= 1'b0;
+            snapshot_payload_latched <= 272'd0;
             motor_jog_start <= 1'b0;
             motor_jog_start <= 1'b0;
             motor_jog_axis <= 2'd0;
             motor_jog_axis <= 2'd0;
             motor_jog_dir <= 1'b0;
             motor_jog_dir <= 1'b0;
-            motor_jog_speed <= 2'd0;
             motor_jog_steps <= 16'd0;
             motor_jog_steps <= 16'd0;
+            jog_wait_axis <= 2'd0;
             watchdog_disable <= 1'b0;
             watchdog_disable <= 1'b0;
+            watchdog_snapshot_arm <= 1'b0;
             command_inflight <= 1'b0;
             command_inflight <= 1'b0;
-            command_frame_type <= 8'd0;
-            command_opcode <= 8'd0;
             command_response_valid <= 1'b0;
             command_response_valid <= 1'b0;
             command_ack_payload <= 64'd0;
             command_ack_payload <= 64'd0;
             command_followup_valid <= 1'b0;
             command_followup_valid <= 1'b0;
             command_followup_frame_type <= 8'd0;
             command_followup_frame_type <= 8'd0;
             command_followup_payload <= 80'd0;
             command_followup_payload <= 80'd0;
-            deferred_disable_pending <= 1'b0;
         end else begin
         end else begin
+            snapshot_scan_start <= 1'b0;
             snapshot_commit_authorize <= 1'b0;
             snapshot_commit_authorize <= 1'b0;
-            motor_snapshot_start <= 1'b0;
             motor_jog_start <= 1'b0;
             motor_jog_start <= 1'b0;
             watchdog_disable <= 1'b0;
             watchdog_disable <= 1'b0;
+            watchdog_snapshot_arm <= 1'b0;
 
 
             if (response_command_done) begin
             if (response_command_done) begin
                 command_inflight <= 1'b0;
                 command_inflight <= 1'b0;
@@ -326,230 +243,145 @@ module prod2u_p4_normal_v3_core #(
                 command_followup_valid <= 1'b0;
                 command_followup_valid <= 1'b0;
             end
             end
 
 
-            if (emergency_disable_valid) begin
-                watchdog_disable <= 1'b1;
-                if (!command_inflight) begin
-                    command_inflight <= 1'b1;
-                    command_frame_type <= FT_HOST_CMD;
-                    command_opcode <= CMD_DISABLE;
-                    command_response_valid <= 1'b0;
-                    command_followup_valid <= 1'b0;
-                end else if (!deferred_disable_pending && !active_disable_command) begin
-                    deferred_disable_pending <= 1'b1;
-                end
-                state <= ST_DISABLE_WAIT;
-            end else if (watchdog_expiry_due && command_inflight &&
-                !command_response_valid && (state != ST_IDLE) &&
-                (state != ST_DISABLE_WAIT)) begin
-                state <= ST_WATCHDOG_ABORT;
-            end else begin
-                case (state)
-                    ST_IDLE: begin
-                        if (deferred_disable_pending && !command_inflight) begin
-                            command_inflight <= 1'b1;
-                            command_frame_type <= FT_HOST_CMD;
-                            command_opcode <= CMD_DISABLE;
-                            command_response_valid <= 1'b0;
-                            command_followup_valid <= 1'b0;
-                            deferred_disable_pending <= 1'b0;
-                            watchdog_disable <= 1'b1;
-                            state <= ST_DISABLE_WAIT;
-                        end else if (command_accept) begin
-                            command_inflight <= 1'b1;
-                            command_frame_type <= request_type;
-                            command_opcode <= request_command;
-                            command_response_valid <= 1'b0;
-                            command_followup_valid <= 1'b0;
+            case (state)
+                ST_IDLE: begin
+                    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 if (watchdog_timeout) begin
-                                    queue_response(1'b0, CMD_SET_SNAPSHOT,
-                                        STATUS_BUSY, 8'd0, state_hash16,
-                                        8'd0, 8'd0, 1'b0, 80'd0);
-                                end else begin
-                                    snapshot_targets_latched <= request_payload[271:248];
-                                    snapshot_busy_at_accept <= motor_axis_active_mask;
-                                    snapshot_solenoid_ignored <=
-                                        snapshot_solenoid_ignored_now;
-                                    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,
+                        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 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
+                                if (!jog_payload_valid) begin
+                                    queue_response(1'b0, MOTION_JOG,
                                         STATUS_BAD_VALUE, 8'd0, state_hash16,
                                         STATUS_BAD_VALUE, 8'd0, state_hash16,
                                         8'd0, 8'd0, 1'b0, 80'd0);
                                         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 begin
                                 end else begin
-                                    queue_response(1'b0, request_command,
-                                        STATUS_UNSUPPORTED, 8'd0, state_hash16,
-                                        8'd0, 8'd0, 1'b0, 80'd0);
+                                    motor_jog_axis <= request_channel[1:0];
+                                    motor_jog_dir <= request_value[0];
+                                    motor_jog_steps <= request_steps;
+                                    jog_wait_axis <= request_channel[1:0];
+                                    motor_jog_start <= 1'b1;
+                                    state <= ST_JOG_WAIT_START;
                                 end
                                 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
-                                    if (!jog_payload_valid) begin
-                                        queue_response(1'b0, MOTION_JOG,
-                                            STATUS_BAD_VALUE, 8'd0, state_hash16,
-                                            8'd0, 8'd0, 1'b0, 80'd0);
-                                    end else begin
-                                        motor_jog_axis <= request_channel[1:0];
-                                        motor_jog_dir <= request_value[0];
-                                        motor_jog_speed <= request_flags[1:0];
-                                        motor_jog_steps <= request_steps;
-                                        motor_jog_start <= 1'b1;
-                                        state <= ST_JOG;
-                                    end
-                                end else if (request_command == MOTION_MARK_CLOSED) begin
-                                    queue_response(1'b0, MOTION_MARK_CLOSED,
-                                        STATUS_UNSUPPORTED, 8'd0, state_hash16,
+                            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);
                                         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,
-                                            motor_status_payload);
-                                    end
                                 end else begin
                                 end else begin
-                                    queue_response(1'b0, request_command,
-                                        STATUS_UNSUPPORTED, 8'd0, state_hash16,
-                                        8'd0, 8'd0, 1'b0, 80'd0);
+                                    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
                             end else begin
                             end else begin
                                 queue_response(1'b0, request_command,
                                 queue_response(1'b0, request_command,
                                     STATUS_UNSUPPORTED, 8'd0, state_hash16,
                                     STATUS_UNSUPPORTED, 8'd0, state_hash16,
                                     8'd0, 8'd0, 1'b0, 80'd0);
                                     8'd0, 8'd0, 1'b0, 80'd0);
                             end
                             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
                     end
+                end
 
 
-                    ST_SNAPSHOT_VALIDATE: begin
-                        if (snapshot_output_result_valid) begin
-                            if (snapshot_output_accepted) begin
-                                motor_snapshot_start <= 1'b1;
-                                state <= ST_SNAPSHOT_MOTOR;
-                            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_MOTOR: begin
-                        if (motor_snapshot_result_valid) begin
-                            snapshot_busy_latched <= motor_snapshot_busy_mask;
-                            snapshot_invalid_latched <= motor_snapshot_invalid_mask;
-                            snapshot_accepted_latched <= motor_snapshot_accepted_mask;
+                ST_SNAPSHOT_VALIDATE: begin
+                    if (snapshot_output_result_valid) begin
+                        if (snapshot_output_accepted) begin
                             snapshot_commit_authorize <= 1'b1;
                             snapshot_commit_authorize <= 1'b1;
                             state <= ST_SNAPSHOT_COMMIT;
                             state <= ST_SNAPSHOT_COMMIT;
-                        end
-                    end
-
-                    ST_SNAPSHOT_COMMIT: begin
-                        if (snapshot_commit_pulse) begin
-                            if ((snapshot_busy_latched |
-                                 snapshot_invalid_latched) != 3'd0 ||
-                                snapshot_solenoid_ignored) begin
-                                queue_response(1'b1, CMD_SET_SNAPSHOT,
-                                    STATUS_PARTIAL,
-                                    {1'b0, snapshot_solenoid_ignored,
-                                     snapshot_invalid_latched,
-                                     snapshot_busy_latched},
-                                    state_hash16, 8'd0,
-                                    {4'd0, snapshot_accepted_latched, 1'b1},
-                                    1'b0, 80'd0);
-                            end else begin
-                                queue_response(1'b1, CMD_SET_SNAPSHOT,
-                                    STATUS_OK, 8'd0, state_hash16, 8'd0,
-                                    {4'd0, snapshot_accepted_latched, 1'b1},
-                                    1'b0, 80'd0);
-                            end
+                        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;
                             state <= ST_IDLE;
                         end
                         end
                     end
                     end
+                end
 
 
-                    ST_JOG: begin
-                        if (motor_jog_result_valid) begin
-                            queue_response(1'b1, MOTION_JOG, STATUS_OK,
-                                8'd0, state_hash16, 8'd0, 8'd0,
-                                1'b0, 80'd0);
-                            state <= ST_IDLE;
-                        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
+                end
 
 
-                    ST_DISABLE_WAIT: begin
-                        if (disabled && (step_out == 3'b000) && en_n) begin
-                            if (command_inflight && !command_response_valid) begin
-                                if (command_opcode == CMD_DISABLE) begin
-                                    queue_response(1'b1, CMD_DISABLE, STATUS_OK,
-                                        {6'd0, watchdog_timeout, disabled},
-                                        state_hash16, 8'd0, 8'd0, 1'b0, 80'd0);
-                                end else if (command_opcode == MOTION_JOG) begin
-                                    queue_response(1'b1, MOTION_JOG, STATUS_OK,
-                                        8'd0, state_hash16, 8'd0, 8'd0,
-                                        1'b0, 80'd0);
-                                end else begin
-                                    queue_response(1'b0, command_opcode,
-                                        STATUS_BUSY, 8'd0, state_hash16,
-                                        8'd0, 8'd0, 1'b0, 80'd0);
-                                end
-                            end
-                            state <= ST_IDLE;
-                        end
+                ST_JOG_WAIT_START: begin
+                    if ((jog_wait_axis == 2'd0 &&
+                         motor_axis_started_pulse[0]) ||
+                        (jog_wait_axis == 2'd1 &&
+                         motor_axis_started_pulse[1])) begin
+                        queue_response(1'b1, MOTION_JOG, STATUS_OK,
+                            8'd0, state_hash16, 8'd0, 8'd0,
+                            1'b0, 80'd0);
+                        state <= ST_IDLE;
                     end
                     end
+                end
 
 
-                    ST_WATCHDOG_ABORT: begin
-                        if (watchdog_timeout &&
-                            (state_hash16 == SAFE_STATE_HASH16) &&
-                            (step_out == 3'b000) && en_n) begin
-                            if (!command_response_valid) begin
-                                if (command_opcode == MOTION_JOG) begin
-                                    queue_response(1'b1, MOTION_JOG, STATUS_OK,
-                                        8'd0, state_hash16, 8'd0, 8'd0,
-                                        1'b0, 80'd0);
-                                end else begin
-                                    queue_response(1'b0, command_opcode,
-                                        STATUS_BUSY, 8'd0, state_hash16,
-                                        8'd0, 8'd0, 1'b0, 80'd0);
-                                end
-                            end
-                            state <= ST_IDLE;
-                        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
+                end
 
 
-                    default: state <= ST_IDLE;
-                endcase
-            end
+                default: state <= ST_IDLE;
+            endcase
         end
         end
     end
     end
 
 
-    wire unused_request_crc = ^request_crc16 ^ ^emergency_disable_crc16 ^
-        ^motor_axis_busy_mask ^ motor_jog_accepted;
+    wire unused = ^request_crc16 ^ watchdog_expiry_due;
 endmodule
 endmodule

+ 69 - 172
src/rtl/prod2u_p4_normal_v3_rx.v

@@ -15,8 +15,6 @@ module prod2u_p4_normal_v3_rx #(
     output wire [5:0]   request_length,
     output wire [5:0]   request_length,
     output wire [271:0] request_payload,
     output wire [271:0] request_payload,
     output reg  [15:0]  request_crc16,
     output reg  [15:0]  request_crc16,
-    output reg          emergency_disable_valid,
-    output reg  [15:0]  emergency_disable_crc16,
     output reg  [15:0]  crc_error_count,
     output reg  [15:0]  crc_error_count,
     output reg  [15:0]  timeout_count,
     output reg  [15:0]  timeout_count,
     output reg  [15:0]  format_error_count
     output reg  [15:0]  format_error_count
@@ -57,20 +55,14 @@ module prod2u_p4_normal_v3_rx #(
     reg [7:0] candidate_type;
     reg [7:0] candidate_type;
     reg [5:0] candidate_length;
     reg [5:0] candidate_length;
     reg [271:0] candidate_payload;
     reg [271:0] candidate_payload;
-    reg [2:0] emergency_state;
-    reg [4:0] emergency_body_index;
-    reg [15:0] emergency_crc;
-    reg [7:0] emergency_received_crc_lo;
-    wire emergency_parser_active = request_valid || (emergency_state != ST_MAGIC0);
-    wire [15:0] active_crc = emergency_parser_active ? emergency_crc : crc;
 
 
-    assign rx_ready = rst_n;
+    assign rx_ready = rst_n && !request_valid;
     assign request_type = candidate_type;
     assign request_type = candidate_type;
     assign request_length = candidate_length;
     assign request_length = candidate_length;
     assign request_payload = candidate_payload;
     assign request_payload = candidate_payload;
 
 
     binary921_crc16 u_crc (
     binary921_crc16 u_crc (
-        .crc_in(active_crc),
+        .crc_in(crc),
         .data(rx_data),
         .data(rx_data),
         .crc_out(crc_next)
         .crc_out(crc_next)
     );
     );
@@ -98,20 +90,6 @@ module prod2u_p4_normal_v3_rx #(
         end
         end
     endfunction
     endfunction
 
 
-    function [7:0] emergency_body_byte;
-        input [4:0] index;
-        begin
-            case (index)
-                5'd0: emergency_body_byte = VERSION;
-                5'd1: emergency_body_byte = PROFILE_ID;
-                5'd2: emergency_body_byte = HOST_CMD;
-                5'd11: emergency_body_byte = 8'd4;
-                5'd12: emergency_body_byte = 8'h26;
-                default: emergency_body_byte = 8'd0;
-            endcase
-        end
-    endfunction
-
     task reset_parser_from_byte;
     task reset_parser_from_byte;
         input [7:0] value;
         input [7:0] value;
         begin
         begin
@@ -126,20 +104,6 @@ module prod2u_p4_normal_v3_rx #(
         end
         end
     endtask
     endtask
 
 
-    task reset_emergency_parser_from_byte;
-        input [7:0] value;
-        begin
-            if (value == MAGIC0) begin
-                emergency_state <= ST_MAGIC1;
-            end else begin
-                emergency_state <= ST_MAGIC0;
-            end
-            emergency_body_index <= 5'd0;
-            timeout_counter <= TIMEOUT_COUNTER_ZERO;
-            emergency_crc <= 16'hffff;
-        end
-    endtask
-
     always @(posedge clk or negedge rst_n) begin
     always @(posedge clk or negedge rst_n) begin
         if (!rst_n) begin
         if (!rst_n) begin
             state <= ST_MAGIC0;
             state <= ST_MAGIC0;
@@ -150,166 +114,99 @@ module prod2u_p4_normal_v3_rx #(
             candidate_type <= 8'd0;
             candidate_type <= 8'd0;
             candidate_length <= 6'd0;
             candidate_length <= 6'd0;
             candidate_payload <= 272'd0;
             candidate_payload <= 272'd0;
-            emergency_state <= ST_MAGIC0;
-            emergency_body_index <= 5'd0;
-            emergency_crc <= 16'hffff;
-            emergency_received_crc_lo <= 8'd0;
             request_valid <= 1'b0;
             request_valid <= 1'b0;
             request_crc16 <= 16'd0;
             request_crc16 <= 16'd0;
-            emergency_disable_valid <= 1'b0;
-            emergency_disable_crc16 <= 16'd0;
             crc_error_count <= 16'd0;
             crc_error_count <= 16'd0;
             timeout_count <= 16'd0;
             timeout_count <= 16'd0;
             format_error_count <= 16'd0;
             format_error_count <= 16'd0;
         end else begin
         end else begin
-            emergency_disable_valid <= 1'b0;
             if (request_valid && request_ready) begin
             if (request_valid && request_ready) begin
                 request_valid <= 1'b0;
                 request_valid <= 1'b0;
             end
             end
 
 
             if (rx_valid && rx_ready) begin
             if (rx_valid && rx_ready) begin
                 timeout_counter <= TIMEOUT_COUNTER_ZERO;
                 timeout_counter <= TIMEOUT_COUNTER_ZERO;
-                if (emergency_parser_active) begin
-                    case (emergency_state)
-                        ST_MAGIC0: begin
-                            if (rx_data == MAGIC0) begin
-                                emergency_state <= ST_MAGIC1;
-                            end
+                case (state)
+                    ST_MAGIC0: begin
+                        if (rx_data == MAGIC0) begin
+                            state <= ST_MAGIC1;
                         end
                         end
-
-                        ST_MAGIC1: begin
-                            if (rx_data == MAGIC1) begin
-                                emergency_state <= ST_BODY;
-                                emergency_body_index <= 5'd0;
-                                emergency_crc <= 16'hffff;
-                            end else if (rx_data != MAGIC0) begin
-                                emergency_state <= ST_MAGIC0;
-                            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 (rx_data != emergency_body_byte(emergency_body_index)) begin
-                                format_error_count <= saturating_increment16(format_error_count);
-                                reset_emergency_parser_from_byte(rx_data);
-                            end else begin
-                                emergency_crc <= crc_next;
-                                if (emergency_body_index == 5'd15) begin
-                                    emergency_state <= ST_CRC_LO;
-                                    emergency_body_index <= 5'd0;
-                                end else begin
-                                    emergency_body_index <= emergency_body_index + 5'd1;
-                                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
                             end
-                        end
 
 
-                        ST_CRC_LO: begin
-                            emergency_received_crc_lo <= rx_data;
-                            emergency_state <= ST_CRC_HI;
-                        end
-
-                        ST_CRC_HI: begin
-                            if ({rx_data, emergency_received_crc_lo} != emergency_crc) begin
-                                crc_error_count <= saturating_increment16(crc_error_count);
-                                reset_emergency_parser_from_byte(rx_data);
-                            end else begin
-                                emergency_disable_crc16 <= emergency_crc;
-                                emergency_disable_valid <= 1'b1;
-                                request_valid <= 1'b0;
-                                emergency_state <= ST_MAGIC0;
-                                emergency_body_index <= 5'd0;
-                                emergency_crc <= 16'hffff;
-                            end
-                        end
-
-                        default: emergency_state <= ST_MAGIC0;
-                    endcase
-                end else begin
-                    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;
+                            if (body_index >= 6'd12 &&
+                                (body_index - 6'd12) ==
+                                (candidate_length - 6'd1)) begin
+                                state <= ST_CRC_LO;
                                 body_index <= 6'd0;
                                 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
                             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
+                                body_index <= body_index + 6'd1;
                             end
                             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_type == HOST_CMD &&
-                                    candidate_length == 6'd4 &&
-                                    candidate_payload[31:0] == 32'h00000026) begin
-                                    emergency_disable_crc16 <= crc;
-                                    emergency_disable_valid <= 1'b1;
-                                end else begin
-                                    request_crc16 <= crc;
-                                    request_valid <= 1'b1;
-                                end
-                                state <= ST_MAGIC0;
-                                body_index <= 6'd0;
-                                crc <= 16'hffff;
-                            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
+                            request_crc16 <= crc;
+                            request_valid <= 1'b1;
+                            state <= ST_MAGIC0;
+                            body_index <= 6'd0;
+                            crc <= 16'hffff;
                         end
                         end
+                    end
 
 
-                        default: state <= ST_MAGIC0;
-                    endcase
-                end
-            end else if ((emergency_parser_active && (emergency_state != ST_MAGIC0)) ||
-                         (!emergency_parser_active && (state != ST_MAGIC0))) begin
+                    default: state <= ST_MAGIC0;
+                endcase
+            end else if (state != ST_MAGIC0) begin
                 if (timeout_counter >= TIMEOUT_LIMIT) begin
                 if (timeout_counter >= TIMEOUT_LIMIT) begin
                     state <= ST_MAGIC0;
                     state <= ST_MAGIC0;
                     body_index <= 6'd0;
                     body_index <= 6'd0;
                     crc <= 16'hffff;
                     crc <= 16'hffff;
-                    emergency_state <= ST_MAGIC0;
-                    emergency_body_index <= 5'd0;
-                    emergency_crc <= 16'hffff;
                     timeout_counter <= TIMEOUT_COUNTER_ZERO;
                     timeout_counter <= TIMEOUT_COUNTER_ZERO;
                     timeout_count <= saturating_increment16(timeout_count);
                     timeout_count <= saturating_increment16(timeout_count);
                 end else begin
                 end else begin

+ 14 - 39
src/top/prod2u_p4_normal_v3_top.v

@@ -22,20 +22,16 @@ module prod2u_p4_normal_v3_top #(
     output wire        y_dir,
     output wire        y_dir,
     output wire        z_step,
     output wire        z_step,
     output wire        z_dir,
     output wire        z_dir,
+    /* verilator lint_off UNUSEDSIGNAL */
     input  wire        x_limit_raw,
     input  wire        x_limit_raw,
     input  wire        y_limit_raw
     input  wire        y_limit_raw
+    /* verilator lint_on UNUSEDSIGNAL */
 );
 );
     localparam integer WATCHDOG_SECONDS = 5;
     localparam integer WATCHDOG_SECONDS = 5;
-    localparam integer MOTOR_STANDARD_STEPS = 3200;
-    localparam integer MOTOR_LIMIT_CONFIRM_US = 1000;
-    localparam integer MOTOR_DIR_SETUP_US = 1000;
-    localparam integer MOTOR_SPEED0_HALF_US = 25000;
-    localparam integer MOTOR_SPEED1_HALF_US = 12500;
-    localparam integer MOTOR_SPEED2_HALF_US = 5000;
-    localparam integer MOTOR_SPEED3_HALF_US = 500;
+    localparam integer MOTOR_DIR_SETUP_CYCLES = 25000;
+    localparam integer MOTOR_STEP_HALF_CYCLES = 12500;
 
 
     wire sys_rst_n;
     wire sys_rst_n;
-    wire tick_1us;
     wire uart_rx_valid;
     wire uart_rx_valid;
     wire [7:0] uart_rx_data;
     wire [7:0] uart_rx_data;
     wire uart_rx_ready;
     wire uart_rx_ready;
@@ -44,12 +40,10 @@ module prod2u_p4_normal_v3_top #(
     wire uart_overflow;
     wire uart_overflow;
     wire request_valid;
     wire request_valid;
     wire request_ready;
     wire request_ready;
-    wire emergency_disable_valid;
     wire [7:0] request_type;
     wire [7:0] request_type;
     wire [5:0] request_length;
     wire [5:0] request_length;
     wire [271:0] request_payload;
     wire [271:0] request_payload;
     wire [15:0] request_crc16;
     wire [15:0] request_crc16;
-    wire [15:0] emergency_disable_crc16;
     wire [15:0] parser_crc_error_count;
     wire [15:0] parser_crc_error_count;
     wire [15:0] parser_timeout_count;
     wire [15:0] parser_timeout_count;
     wire [15:0] parser_format_error_count;
     wire [15:0] parser_format_error_count;
@@ -65,7 +59,7 @@ module prod2u_p4_normal_v3_top #(
     wire [15:0] state_hash16;
     wire [15:0] state_hash16;
     wire [2:0] motor_steps;
     wire [2:0] motor_steps;
     wire [2:0] motor_dirs;
     wire [2:0] motor_dirs;
-    wire motor_en_n_core;
+    wire core_en_n_unused;
     wire disabled;
     wire disabled;
     wire watchdog_timeout;
     wire watchdog_timeout;
     wire solenoid_on;
     wire solenoid_on;
@@ -82,13 +76,13 @@ module prod2u_p4_normal_v3_top #(
     endgenerate
     endgenerate
 
 
     assign solenoid_out = (SOLENOID_ACTIVE_HIGH != 0) ? solenoid_on : !solenoid_on;
     assign solenoid_out = (SOLENOID_ACTIVE_HIGH != 0) ? solenoid_on : !solenoid_on;
-    assign x_step = (emergency_disable_valid || disabled || watchdog_timeout) ? 1'b0 : motor_steps[0];
-    assign y_step = (emergency_disable_valid || disabled || watchdog_timeout) ? 1'b0 : motor_steps[1];
-    assign z_step = (emergency_disable_valid || disabled || watchdog_timeout) ? 1'b0 : motor_steps[2];
+    assign x_step = motor_steps[0];
+    assign y_step = motor_steps[1];
+    assign z_step = motor_steps[2];
     assign x_dir = motor_dirs[0];
     assign x_dir = motor_dirs[0];
     assign y_dir = motor_dirs[1];
     assign y_dir = motor_dirs[1];
     assign z_dir = motor_dirs[2];
     assign z_dir = motor_dirs[2];
-    assign motor_en_n = emergency_disable_valid || disabled || watchdog_timeout || motor_en_n_core;
+    assign motor_en_n = 1'b0;
 
 
     prod2u_por #(
     prod2u_por #(
         .POR_CYCLES(POR_CYCLES)
         .POR_CYCLES(POR_CYCLES)
@@ -97,14 +91,6 @@ module prod2u_p4_normal_v3_top #(
         .sys_rst_n(sys_rst_n)
         .sys_rst_n(sys_rst_n)
     );
     );
 
 
-    prod2u_p4_us_tick #(
-        .CLK_HZ(CLK_HZ)
-    ) u_us_tick (
-        .clk(sys_clk),
-        .rst_n(sys_rst_n),
-        .tick_1us(tick_1us)
-    );
-
     uart_rx_8n1 #(
     uart_rx_8n1 #(
         .CLKS_PER_BIT(HOST_UART_CLKS_PER_BIT)
         .CLKS_PER_BIT(HOST_UART_CLKS_PER_BIT)
     ) u_uart_rx (
     ) u_uart_rx (
@@ -134,8 +120,6 @@ module prod2u_p4_normal_v3_top #(
         .request_length(request_length),
         .request_length(request_length),
         .request_payload(request_payload),
         .request_payload(request_payload),
         .request_crc16(request_crc16),
         .request_crc16(request_crc16),
-        .emergency_disable_valid(emergency_disable_valid),
-        .emergency_disable_crc16(emergency_disable_crc16),
         .crc_error_count(parser_crc_error_count),
         .crc_error_count(parser_crc_error_count),
         .timeout_count(parser_timeout_count),
         .timeout_count(parser_timeout_count),
         .format_error_count(parser_format_error_count)
         .format_error_count(parser_format_error_count)
@@ -144,39 +128,29 @@ module prod2u_p4_normal_v3_top #(
     prod2u_p4_normal_v3_core #(
     prod2u_p4_normal_v3_core #(
         .CLK_HZ(CLK_HZ),
         .CLK_HZ(CLK_HZ),
         .WATCHDOG_SECONDS(WATCHDOG_SECONDS),
         .WATCHDOG_SECONDS(WATCHDOG_SECONDS),
-        .STANDARD_STEPS(MOTOR_STANDARD_STEPS),
-        .LIMIT_CONFIRM_US(MOTOR_LIMIT_CONFIRM_US),
-        .DIR_SETUP_US(MOTOR_DIR_SETUP_US),
-        .SPEED0_HALF_US(MOTOR_SPEED0_HALF_US),
-        .SPEED1_HALF_US(MOTOR_SPEED1_HALF_US),
-        .SPEED2_HALF_US(MOTOR_SPEED2_HALF_US),
-        .SPEED3_HALF_US(MOTOR_SPEED3_HALF_US)
+        .DIR_SETUP_CYCLES(MOTOR_DIR_SETUP_CYCLES),
+        .STEP_HALF_CYCLES(MOTOR_STEP_HALF_CYCLES)
     ) u_core (
     ) u_core (
         .clk(sys_clk),
         .clk(sys_clk),
         .rst_n(sys_rst_n),
         .rst_n(sys_rst_n),
-        .tick_1us(tick_1us),
         .request_valid(request_valid),
         .request_valid(request_valid),
-        .emergency_disable_valid(emergency_disable_valid),
         .request_ready(request_ready),
         .request_ready(request_ready),
         .request_type(request_type),
         .request_type(request_type),
         .request_length(request_length),
         .request_length(request_length),
         .request_payload(request_payload),
         .request_payload(request_payload),
         .request_crc16(request_crc16),
         .request_crc16(request_crc16),
-        .emergency_disable_crc16(emergency_disable_crc16),
         .frame_valid(frame_valid),
         .frame_valid(frame_valid),
         .frame_ready(frame_ready),
         .frame_ready(frame_ready),
         .frame_type(frame_type),
         .frame_type(frame_type),
         .frame_payload_len(frame_payload_len),
         .frame_payload_len(frame_payload_len),
         .frame_payload(frame_payload),
         .frame_payload(frame_payload),
-        .x_limit_raw(x_limit_raw),
-        .y_limit_raw(y_limit_raw),
         .ptc_percent(ptc_percent),
         .ptc_percent(ptc_percent),
         .fan_percent(fan_percent),
         .fan_percent(fan_percent),
         .solenoid_percent(solenoid_percent),
         .solenoid_percent(solenoid_percent),
         .state_hash16(state_hash16),
         .state_hash16(state_hash16),
         .step_out(motor_steps),
         .step_out(motor_steps),
         .dir_out(motor_dirs),
         .dir_out(motor_dirs),
-        .en_n(motor_en_n_core),
+        .en_n(core_en_n_unused),
         .disabled(disabled),
         .disabled(disabled),
         .watchdog_timeout(watchdog_timeout)
         .watchdog_timeout(watchdog_timeout)
     );
     );
@@ -222,5 +196,6 @@ module prod2u_p4_normal_v3_top #(
 
 
     wire unused_status = ^state_hash16 ^ disabled ^ watchdog_timeout ^
     wire unused_status = ^state_hash16 ^ disabled ^ watchdog_timeout ^
         ^parser_crc_error_count ^ ^parser_timeout_count ^ ^parser_format_error_count ^
         ^parser_crc_error_count ^ ^parser_timeout_count ^ ^parser_format_error_count ^
-        uart_framing_error ^ uart_break_detected ^ uart_overflow ^ tx_phy_busy;
+        uart_framing_error ^ uart_break_detected ^ uart_overflow ^ tx_phy_busy ^
+        core_en_n_unused;
 endmodule
 endmodule

+ 3 - 11
td/phy/prod2u_p4_normal_v3.tcl

@@ -7,12 +7,6 @@ read_sdc {constraints/prod2u_p4_normal_v3.sdc}
 set cdc_patterns {
 set cdc_patterns {
     */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_core/u_motors/u_x_axis/limit_sync_pipe[0]
-    */u_core/u_motors/u_x_axis/limit_sync_pipe[1]
-    */u_core/u_motors/u_x_axis/limit_sync_pipe[2]
-    */u_core/u_motors/u_y_axis/limit_sync_pipe[0]
-    */u_core/u_motors/u_y_axis/limit_sync_pipe[1]
-    */u_core/u_motors/u_y_axis/limit_sync_pipe[2]
 }
 }
 set cdc_report [open {prod2u_p4_normal_v3_cdc.rpt} w]
 set cdc_report [open {prod2u_p4_normal_v3_cdc.rpt} w]
 puts $cdc_report {schema=prod2u-p4-normal-v3-cdc-v2}
 puts $cdc_report {schema=prod2u-p4-normal-v3-cdc-v2}
@@ -30,7 +24,7 @@ foreach pattern $cdc_patterns {
         puts $cdc_report "retained_sync_register=$reg"
         puts $cdc_report "retained_sync_register=$reg"
     }
     }
 }
 }
-if {[llength $cdc_regs] != 8} {
+if {[llength $cdc_regs] != 2} {
     set reason "retained_sync_register_total:[llength $cdc_regs]"
     set reason "retained_sync_register_total:[llength $cdc_regs]"
     lappend cdc_failures $reason
     lappend cdc_failures $reason
     puts $cdc_report "structural_failure=$reason"
     puts $cdc_report "structural_failure=$reason"
@@ -38,8 +32,6 @@ if {[llength $cdc_regs] != 8} {
 
 
 set cdc_input_pairs {
 set cdc_input_pairs {
     host_uart_rx */u_uart_rx/rx_sync_pipe[0]
     host_uart_rx */u_uart_rx/rx_sync_pipe[0]
-    x_limit_raw */u_core/u_motors/u_x_axis/limit_sync_pipe[0]
-    y_limit_raw */u_core/u_motors/u_y_axis/limit_sync_pipe[0]
 }
 }
 foreach {source_port pattern} $cdc_input_pairs {
 foreach {source_port pattern} $cdc_input_pairs {
     set source_matches [get_ports -quiet $source_port]
     set source_matches [get_ports -quiet $source_port]
@@ -80,11 +72,11 @@ set fsm_failures {}
 foreach {axis pattern} $phase_groups {
 foreach {axis pattern} $phase_groups {
     set matches {}
     set matches {}
     foreach candidate [get_regs -quiet $pattern] {
     foreach candidate [get_regs -quiet $pattern] {
-        if {[regexp {/motion_phase\[[0-2]\]$} $candidate]} {
+        if {[regexp {/motion_phase\[[0-1]\]$} $candidate]} {
             lappend matches $candidate
             lappend matches $candidate
         }
         }
     }
     }
-    if {[llength $matches] != 3} {
+    if {[llength $matches] != 2} {
         puts $fsm_report "motion_phase=${axis}:[llength $matches]:unknown"
         puts $fsm_report "motion_phase=${axis}:[llength $matches]:unknown"
         set reason "motion_phase_register_count:$axis:[llength $matches]"
         set reason "motion_phase_register_count:$axis:[llength $matches]"
         lappend fsm_failures $reason
         lappend fsm_failures $reason

+ 3 - 11
td/syn/prod2u_p4_normal_v3.tcl

@@ -25,12 +25,6 @@ optimize_rtl
 set cdc_patterns {
 set cdc_patterns {
     */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_core/u_motors/u_x_axis/limit_sync_pipe[0]
-    */u_core/u_motors/u_x_axis/limit_sync_pipe[1]
-    */u_core/u_motors/u_x_axis/limit_sync_pipe[2]
-    */u_core/u_motors/u_y_axis/limit_sync_pipe[0]
-    */u_core/u_motors/u_y_axis/limit_sync_pipe[1]
-    */u_core/u_motors/u_y_axis/limit_sync_pipe[2]
 }
 }
 set cdc_report [open {prod2u_p4_normal_v3_cdc.rpt} w]
 set cdc_report [open {prod2u_p4_normal_v3_cdc.rpt} w]
 puts $cdc_report {schema=prod2u-p4-normal-v3-cdc-v2}
 puts $cdc_report {schema=prod2u-p4-normal-v3-cdc-v2}
@@ -48,7 +42,7 @@ foreach pattern $cdc_patterns {
         puts $cdc_report "retained_sync_register=$reg"
         puts $cdc_report "retained_sync_register=$reg"
     }
     }
 }
 }
-if {[llength $cdc_regs] != 8} {
+if {[llength $cdc_regs] != 2} {
     set reason "retained_sync_register_total:[llength $cdc_regs]"
     set reason "retained_sync_register_total:[llength $cdc_regs]"
     lappend cdc_failures $reason
     lappend cdc_failures $reason
     puts $cdc_report "structural_failure=$reason"
     puts $cdc_report "structural_failure=$reason"
@@ -58,8 +52,6 @@ if {[llength $cdc_regs] > 0} {
 }
 }
 set cdc_input_pairs {
 set cdc_input_pairs {
     host_uart_rx */u_uart_rx/rx_sync_pipe[0]
     host_uart_rx */u_uart_rx/rx_sync_pipe[0]
-    x_limit_raw */u_core/u_motors/u_x_axis/limit_sync_pipe[0]
-    y_limit_raw */u_core/u_motors/u_y_axis/limit_sync_pipe[0]
 }
 }
 foreach {source_port pattern} $cdc_input_pairs {
 foreach {source_port pattern} $cdc_input_pairs {
     set source_matches [get_ports -quiet $source_port]
     set source_matches [get_ports -quiet $source_port]
@@ -106,11 +98,11 @@ set fsm_failures {}
 foreach {axis pattern} $phase_groups {
 foreach {axis pattern} $phase_groups {
     set matches {}
     set matches {}
     foreach candidate [get_regs -quiet $pattern] {
     foreach candidate [get_regs -quiet $pattern] {
-        if {[regexp {/motion_phase\[[0-2]\]$} $candidate]} {
+        if {[regexp {/motion_phase\[[0-1]\]$} $candidate]} {
             lappend matches $candidate
             lappend matches $candidate
         }
         }
     }
     }
-    if {[llength $matches] != 3} {
+    if {[llength $matches] != 2} {
         puts $fsm_report "motion_phase=${axis}:[llength $matches]:unknown"
         puts $fsm_report "motion_phase=${axis}:[llength $matches]:unknown"
         set reason "motion_phase_register_count:$axis:[llength $matches]"
         set reason "motion_phase_register_count:$axis:[llength $matches]"
         lappend fsm_failures $reason
         lappend fsm_failures $reason

+ 3 - 1
tests/README.md

@@ -4,8 +4,10 @@ The active verification tree covers only Prod2U P4 Normal v3.
 
 
 - `tests/sim/`: directed Icarus/Verilator RTL simulations.
 - `tests/sim/`: directed Icarus/Verilator RTL simulations.
 - `tests/cocotb/`: Python-driven core and top-level cosimulation.
 - `tests/cocotb/`: Python-driven core and top-level cosimulation.
-- `tests/formal/`: motion, watchdog, protocol, output and Trace properties.
+- `tests/formal/`: JOG timing/reload, protocol, output, and non-motor watchdog properties.
 - `tests/unit/`: host protocol, model, package, resource and receipt contracts.
 - `tests/unit/`: host protocol, model, package, resource and receipt contracts.
 - `tests/fixtures/`: deliberately bad inputs used to prove detectors fail closed.
 - `tests/fixtures/`: deliberately bad inputs used to prove detectors fail closed.
 
 
+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.
+
 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.
 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.

+ 4 - 3
tests/cocotb/prod2u_p4_normal_v3_ack_only_top.v

@@ -18,15 +18,16 @@ module prod2u_p4_normal_v3_ack_only_top;
     wire z_dir;
     wire z_dir;
 
 
     wire sys_rst_n_debug = u_dut.sys_rst_n;
     wire sys_rst_n_debug = u_dut.sys_rst_n;
-    wire emergency_disable_debug = u_dut.emergency_disable_valid;
     wire disabled_debug = u_dut.disabled;
     wire disabled_debug = u_dut.disabled;
     wire watchdog_timeout_debug = u_dut.watchdog_timeout;
     wire watchdog_timeout_debug = u_dut.watchdog_timeout;
-    wire [2:0] axis_active_debug = u_dut.u_core.motor_axis_active_mask;
-    wire [2:0] axis_busy_debug = u_dut.u_core.motor_axis_busy_mask;
     wire [191:0] ptc_percent_debug = u_dut.ptc_percent;
     wire [191:0] ptc_percent_debug = u_dut.ptc_percent;
     wire [31:0] fan_percent_debug = u_dut.fan_percent;
     wire [31:0] fan_percent_debug = u_dut.fan_percent;
     wire [7:0] solenoid_percent_debug = u_dut.solenoid_percent;
     wire [7:0] solenoid_percent_debug = u_dut.solenoid_percent;
     wire [15:0] state_hash16_debug = u_dut.state_hash16;
     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;
 
 
     prod2u_p4_normal_v3_top #(
     prod2u_p4_normal_v3_top #(
         .CLK_HZ(1000000),
         .CLK_HZ(1000000),

+ 128 - 182
tests/cocotb/test_prod2u_p4_normal_v3_ack_only_top_e2e.py

@@ -1,4 +1,4 @@
-"""ACK-only UART, independent-axis, status, and DISABLE top-level checks."""
+"""UART end-to-end checks for the unguarded independent JOG image."""
 
 
 from __future__ import annotations
 from __future__ import annotations
 
 
@@ -8,7 +8,7 @@ from pathlib import Path
 import cocotb
 import cocotb
 from cocotb.clock import Clock
 from cocotb.clock import Clock
 from cocotb.queue import Queue
 from cocotb.queue import Queue
-from cocotb.triggers import ReadOnly, RisingEdge, with_timeout
+from cocotb.triggers import ClockCycles, ReadOnly, RisingEdge, with_timeout
 
 
 
 
 ROOT = Path(__file__).resolve().parents[2]
 ROOT = Path(__file__).resolve().parents[2]
@@ -19,7 +19,7 @@ import prod2u_p4_protocol as protocol  # noqa: E402
 
 
 UART_CLKS_PER_BIT = 4
 UART_CLKS_PER_BIT = 4
 FRAME_TIMEOUT_US = 5000
 FRAME_TIMEOUT_US = 5000
-QUIET_CYCLES = 512
+QUIET_CYCLES = 128
 
 
 GOLDEN_DISABLE = bytes.fromhex("A55A02040500000000000000000426000000C4AE")
 GOLDEN_DISABLE = bytes.fromhex("A55A02040500000000000000000426000000C4AE")
 GOLDEN_GET_STATUS = bytes.fromhex("A55A02040500000000000000000424000000AC43")
 GOLDEN_GET_STATUS = bytes.fromhex("A55A02040500000000000000000424000000AC43")
@@ -38,21 +38,21 @@ GOLDEN_X_JOG_65535 = bytes.fromhex(
 GOLDEN_X_JOG_801_REVERSE = bytes.fromhex(
 GOLDEN_X_JOG_801_REVERSE = bytes.fromhex(
     "A55A02041100000000000000000835000103210300004A43"
     "A55A02041100000000000000000835000103210300004A43"
 )
 )
+GOLDEN_Y_JOG_800 = bytes.fromhex(
+    "A55A02041100000000000000000835010003200300003FC8"
+)
 
 
 
 
 async def send_uart_frame(dut, frame: bytes) -> None:
 async def send_uart_frame(dut, frame: bytes) -> None:
     await RisingEdge(dut.sys_clk)
     await RisingEdge(dut.sys_clk)
     for byte in frame:
     for byte in frame:
         dut.host_uart_rx.value = 0
         dut.host_uart_rx.value = 0
-        for _ in range(UART_CLKS_PER_BIT):
-            await RisingEdge(dut.sys_clk)
+        await ClockCycles(dut.sys_clk, UART_CLKS_PER_BIT)
         for bit in range(8):
         for bit in range(8):
             dut.host_uart_rx.value = (byte >> bit) & 1
             dut.host_uart_rx.value = (byte >> bit) & 1
-            for _ in range(UART_CLKS_PER_BIT):
-                await RisingEdge(dut.sys_clk)
+            await ClockCycles(dut.sys_clk, UART_CLKS_PER_BIT)
         dut.host_uart_rx.value = 1
         dut.host_uart_rx.value = 1
-        for _ in range(UART_CLKS_PER_BIT):
-            await RisingEdge(dut.sys_clk)
+        await ClockCycles(dut.sys_clk, UART_CLKS_PER_BIT)
 
 
 
 
 async def uart_byte_monitor(dut, output: Queue) -> None:
 async def uart_byte_monitor(dut, output: Queue) -> None:
@@ -65,21 +65,40 @@ async def uart_byte_monitor(dut, output: Queue) -> None:
             continue
             continue
         current = int(dut.host_uart_tx.value)
         current = int(dut.host_uart_tx.value)
         if previous and not current:
         if previous and not current:
-            for _ in range(UART_CLKS_PER_BIT + (UART_CLKS_PER_BIT // 2)):
-                await RisingEdge(dut.sys_clk)
+            await ClockCycles(
+                dut.sys_clk,
+                UART_CLKS_PER_BIT + (UART_CLKS_PER_BIT // 2),
+            )
             value = 0
             value = 0
             for bit in range(8):
             for bit in range(8):
                 await ReadOnly()
                 await ReadOnly()
                 assert dut.host_uart_tx.value.is_resolvable
                 assert dut.host_uart_tx.value.is_resolvable
                 value |= int(dut.host_uart_tx.value) << bit
                 value |= int(dut.host_uart_tx.value) << bit
-                for _ in range(UART_CLKS_PER_BIT):
-                    await RisingEdge(dut.sys_clk)
+                await ClockCycles(dut.sys_clk, UART_CLKS_PER_BIT)
             output.put_nowait(value)
             output.put_nowait(value)
             previous = 1
             previous = 1
         else:
         else:
             previous = current
             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) -> int:
 async def next_uart_byte(queue: Queue) -> int:
     return await with_timeout(queue.get(), FRAME_TIMEOUT_US, "us")
     return await with_timeout(queue.get(), FRAME_TIMEOUT_US, "us")
 
 
@@ -102,8 +121,7 @@ async def send_and_read_ack(dut, queue: Queue, request: bytes) -> protocol.HostA
 
 
 
 
 async def assert_uart_quiet(dut, queue: Queue, label: str) -> None:
 async def assert_uart_quiet(dut, queue: Queue, label: str) -> None:
-    for _ in range(QUIET_CYCLES):
-        await RisingEdge(dut.sys_clk)
+    await ClockCycles(dut.sys_clk, QUIET_CYCLES)
     assert queue.qsize() == 0, f"unexpected follow-up bytes after {label}"
     assert queue.qsize() == 0, f"unexpected follow-up bytes after {label}"
 
 
 
 
@@ -122,57 +140,19 @@ def assert_request_goldens() -> None:
     assert protocol.build_motor_jog(
     assert protocol.build_motor_jog(
         axis=0, raw_dir=1, speed_code=3, steps=801
         axis=0, raw_dir=1, speed_code=3, steps=801
     ) == GOLDEN_X_JOG_801_REVERSE
     ) == GOLDEN_X_JOG_801_REVERSE
-    assert protocol.encode_frame(
-        frame_type=protocol.FrameType.HOST_CMD,
-        seq=0,
-        timestamp_tick=0,
-        payload=bytes((0x29, 0, 0, 0)),
-    ) == GOLDEN_TEMPERATURE_REQUEST
-
-
-def committed_state(dut) -> tuple[int, ...]:
-    return (
-        int(dut.ptc_percent_debug.value),
-        int(dut.fan_percent_debug.value),
-        int(dut.solenoid_percent_debug.value),
-        int(dut.disabled_debug.value),
-        int(dut.watchdog_timeout_debug.value),
-        int(dut.x_step.value),
-        int(dut.y_step.value),
-        int(dut.z_step.value),
-        int(dut.motor_en_n.value),
-    )
-
-
-async def wait_high(signal, clock, cycles: int, label: str) -> None:
-    for _ in range(cycles):
-        await RisingEdge(clock)
-        await ReadOnly()
-        if int(signal.value):
-            return
-    raise AssertionError(f"timed out waiting for {label}")
-
-
-async def wait_dual_step(dut, cycles: int) -> None:
-    for _ in range(cycles):
-        await RisingEdge(dut.sys_clk)
-        await ReadOnly()
-        if int(dut.x_step.value) and int(dut.y_step.value):
-            return
-    raise AssertionError("X/Y standard motion never overlapped")
+    assert protocol.build_motor_jog(
+        axis=1, raw_dir=0, speed_code=3, steps=800
+    ) == GOLDEN_Y_JOG_800
 
 
 
 
-async def assert_emergency_hard_gate(dut) -> None:
-    await wait_high(
-        dut.emergency_disable_debug,
-        dut.sys_clk,
-        2000,
-        "emergency DISABLE decode",
-    )
-    assert int(dut.x_step.value) == 0
-    assert int(dut.y_step.value) == 0
-    assert int(dut.z_step.value) == 0
-    assert int(dut.motor_en_n.value) == 1
+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()
 @cocotb.test()
@@ -180,138 +160,104 @@ async def ack_only_uart_contract(dut) -> None:
     assert_request_goldens()
     assert_request_goldens()
     cocotb.start_soon(Clock(dut.sys_clk, 10, unit="ns").start())
     cocotb.start_soon(Clock(dut.sys_clk, 10, unit="ns").start())
     received: Queue = Queue()
     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(uart_byte_monitor(dut, received))
+    cocotb.start_soon(step_monitor(dut, observed))
 
 
-    await wait_high(dut.sys_rst_n_debug, dut.sys_clk, 32, "POR release")
-    for _ in range(256):
+    for _ in range(32):
         await RisingEdge(dut.sys_clk)
         await RisingEdge(dut.sys_clk)
-    assert received.qsize() == 0, "unsolicited BOOT/Trace bytes were transmitted"
+        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
 
 
-    get_status = GOLDEN_GET_STATUS
-    status_ack = await send_and_read_ack(dut, received, get_status)
+    status_ack = await send_and_read_ack(dut, received, GOLDEN_GET_STATUS)
     assert status_ack.ok is True
     assert status_ack.ok is True
-    assert status_ack.command == protocol.CommandId.GET_STATUS
     assert status_ack.status == protocol.StatusCode.OK
     assert status_ack.status == protocol.StatusCode.OK
-    assert status_ack.response_type == 0
-    await assert_uart_quiet(dut, received, "GET_STATUS ACK")
 
 
-    before_unknown = committed_state(dut)
-    temperature_ack = await send_and_read_ack(
-        dut, received, GOLDEN_TEMPERATURE_REQUEST
-    )
-    assert temperature_ack.ok is False
-    assert int(temperature_ack.command) == 0x29
-    assert temperature_ack.status == protocol.StatusCode.UNSUPPORTED_IN_PROFILE
-    assert committed_state(dut) == before_unknown
-    await assert_uart_quiet(dut, received, "0x29 ACK")
-
-    mark_ack = await send_and_read_ack(dut, received, GOLDEN_MARK_CLOSED)
-    assert mark_ack.ok is False
-    assert mark_ack.command == protocol.MotionOpcode.MARK_CLOSED
-    assert mark_ack.status == protocol.StatusCode.UNSUPPORTED_IN_PROFILE
-    assert committed_state(dut) == before_unknown
-    await assert_uart_quiet(dut, received, "0x36 ACK")
-
-    motor_status_request = GOLDEN_GET_MOTOR_STATUS
-    motor_status_ack = await send_and_read_ack(dut, received, motor_status_request)
-    assert motor_status_ack.ok is True
-    assert motor_status_ack.command == protocol.MotionOpcode.GET_MOTOR_STATUS
-    assert motor_status_ack.response_type == protocol.FrameType.MOTION_STATUS
-    motor_status_frame = await read_uart_frame(received)
-    assert motor_status_frame.frame_type == protocol.FrameType.MOTION_STATUS
-    initial_motion = protocol.decode_motion_status(motor_status_frame)
-    assert initial_motion.busy_mask == 0
-    assert int(dut.disabled_debug.value) == 1
-    await assert_uart_quiet(dut, received, "initial MOTION_STATUS")
+    for request, command in (
+        (GOLDEN_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
 
 
-    # Version 1 accepts and clamps oversized JOG requests even when LS is high.
     dut.x_limit_raw.value = 1
     dut.x_limit_raw.value = 1
-    oversized_jog_ack = await send_and_read_ack(
-        dut, received, GOLDEN_X_JOG_65535
+    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),
     )
     )
-    assert oversized_jog_ack.ok is True
-    assert oversized_jog_ack.command == protocol.MotionOpcode.JOG
-    assert oversized_jog_ack.status == protocol.StatusCode.OK
-    assert oversized_jog_ack.response_type == 0
-    await assert_uart_quiet(dut, received, "oversized JOG ACK")
-    await wait_high(dut.x_step, dut.sys_clk, 3000, "oversized X JOG STEP")
-    assert int(dut.axis_active_debug.value) & 0x01
-    assert int(dut.axis_busy_debug.value) & 0x01
-
-    # A same-axis replacement remains accepted while the prior JOG is active.
-    await RisingEdge(dut.sys_clk)
-    dut.x_limit_raw.value = 0
+    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(
     replacement_ack = await send_and_read_ack(
         dut, received, GOLDEN_X_JOG_801_REVERSE
         dut, received, GOLDEN_X_JOG_801_REVERSE
     )
     )
     assert replacement_ack.ok is True
     assert replacement_ack.ok is True
-    assert replacement_ack.command == protocol.MotionOpcode.JOG
-    assert replacement_ack.status == protocol.StatusCode.OK
-    assert replacement_ack.response_type == 0
-    await assert_uart_quiet(dut, received, "same-axis replacement JOG ACK")
-    await wait_high(dut.x_dir, dut.sys_clk, 3000, "replacement X DIR")
-    await wait_high(dut.x_step, dut.sys_clk, 3000, "replacement X JOG STEP")
-    assert int(dut.axis_active_debug.value) & 0x01
-    assert int(dut.axis_busy_debug.value) & 0x01
-
-    replacement_status_ack = await send_and_read_ack(
-        dut, received, motor_status_request
-    )
-    assert replacement_status_ack.ok is True
-    replacement_status_frame = await read_uart_frame(received)
-    replacement_motion = protocol.decode_motion_status(replacement_status_frame)
-    assert replacement_motion.busy_mask & 0x01
-    assert replacement_motion.current_xyz[0] == 0xFF
-    assert replacement_motion.target_xyz[0] == 0xFF
-    await assert_uart_quiet(dut, received, "replacement MOTION_STATUS")
-
-    disable_request = GOLDEN_DISABLE
-    emergency_check = cocotb.start_soon(assert_emergency_hard_gate(dut))
-    force_jog_disable_ack = await send_and_read_ack(
-        dut, received, disable_request
-    )
-    await emergency_check
-    assert force_jog_disable_ack.ok is True
-    assert force_jog_disable_ack.command == protocol.CommandId.DISABLE
-    assert int(dut.axis_active_debug.value) == 0
-    assert int(dut.axis_busy_debug.value) == 0
-    await assert_uart_quiet(dut, received, "force-JOG DISABLE ACK")
-
-    snapshot_request = protocol.build_output_snapshot(
-        ptc_percent=[0] * 24,
-        fan_percent=[30] * 4,
-        solenoid=0,
-        xyz=(100, 100, 0),
-    )
-    snapshot_ack = await send_and_read_ack(dut, received, snapshot_request)
-    assert snapshot_ack.ok is True
-    assert snapshot_ack.command == protocol.CommandId.SET_OUTPUT_SNAPSHOT
-    assert snapshot_ack.status == protocol.StatusCode.OK
-    assert snapshot_ack.result_flags == 0x0F
-    await wait_high(dut.axis_busy_debug, dut.sys_clk, 2000, "dual-axis busy")
-    assert int(dut.axis_busy_debug.value) & 0x03 == 0x03
-    await wait_dual_step(dut, 3000)
-    assert int(dut.x_dir.value) == 0
-    assert int(dut.y_dir.value) == 0
+    assert int(observed["x_rises"]) > before_replacement
+    assert int(dut.x_dir.value) == 1
+    assert int(dut.x_remaining_debug.value) == 801
 
 
-    active_status_ack = await send_and_read_ack(dut, received, motor_status_request)
-    assert active_status_ack.ok is True
-    active_status_frame = await read_uart_frame(received)
-    active_motion = protocol.decode_motion_status(active_status_frame)
-    assert active_motion.busy_mask & 0x03 == 0x03
-    assert active_motion.current_xyz[:2] == (0xFE, 0xFE)
-    assert active_motion.target_xyz[:2] == (100, 100)
-
-    emergency_check = cocotb.start_soon(assert_emergency_hard_gate(dut))
-    disable_ack = await send_and_read_ack(dut, received, disable_request)
-    await emergency_check
+    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 disable_ack.ok is True
-    assert disable_ack.command == protocol.CommandId.DISABLE
-    assert disable_ack.status == protocol.StatusCode.OK
     assert int(dut.disabled_debug.value) == 1
     assert int(dut.disabled_debug.value) == 1
-    assert int(dut.axis_busy_debug.value) == 0
-    assert int(dut.x_step.value) == 0
-    assert int(dut.y_step.value) == 0
-    assert int(dut.z_step.value) == 0
-    assert int(dut.motor_en_n.value) == 1
-    assert received.qsize() == 0
+    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")

+ 11 - 8
tests/formal/README.md

@@ -1,15 +1,18 @@
 # Formal Verification Layer
 # Formal Verification Layer
 
 
-Formal targets cover independent safety properties for Prod2U P4 Normal v3:
+Formal targets cover independent digital properties for Prod2U P4 Normal v3:
 
 
-- complete STEP high/low phases unless DISABLE or watchdog performs a hard stop;
-- DIR changes only with STEP low, followed by a fresh setup interval;
-- force-motion JOG replacement uses the latest command at a complete low-tail boundary;
-- reported busy starts with the first emitted STEP and clears after the final low tail;
-- Version 1 motion is externally invariant to either limit input;
+- only opcode `0x35` can start X/Y motion;
+- every valid JOG preserves the full `1..65535` step field and uses fixed 1000 step/s;
+- ACK is released only after the first STEP rise;
+- same-axis replacement immediately forces STEP low, discards old distance, and restarts the full DIR setup interval; the old pulse may be truncated;
+- reported busy, fault, and position-valid fields remain zero while current/target remain unknown;
+- motion is externally invariant to either limit input, DISABLE, and watchdog expiry;
+- the reserved-axis proof is named for what it checks; it is not a motor hard-stop proof;
 - X/Y executor non-interference, peer overlap and shared-enable behavior;
 - X/Y executor non-interference, peer overlap and shared-enable behavior;
-- same-cycle DISABLE/watchdog pin safety and expiry-over-refresh priority;
-- RX framing/payload integrity, continuous held-request intake and emergency DISABLE flush;
+- motor enable remains active; only reset, power loss, or reconfiguration stops motion;
+- DISABLE/watchdog still force non-motor outputs safe and preserve expiry-over-refresh priority;
+- RX framing/payload integrity and continuous held-request intake without an emergency DISABLE bypass;
 - output-state invariants.
 - output-state invariants.
 
 
 These properties prove digital STEP/DIR/EN and status behavior. They do not
 These properties prove digital STEP/DIR/EN and status behavior. They do not

+ 2 - 3
tests/formal/prod2u_p4_axis_cdc_structure.sby

@@ -4,9 +4,9 @@ cover
 
 
 [options]
 [options]
 prove: mode prove
 prove: mode prove
-prove: depth 16
+prove: depth 24
 cover: mode cover
 cover: mode cover
-cover: depth 16
+cover: depth 24
 
 
 [engines]
 [engines]
 prove: abc pdr
 prove: abc pdr
@@ -14,7 +14,6 @@ cover: smtbmc yices
 
 
 [script]
 [script]
 read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_axis_cdc_structure_formal.v
 read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_axis_cdc_structure_formal.v
-select -assert-count 1 a:async_reg=true
 prep -top prod2u_p4_axis_cdc_structure_formal
 prep -top prod2u_p4_axis_cdc_structure_formal
 
 
 [files]
 [files]

+ 22 - 36
tests/formal/prod2u_p4_axis_cdc_structure_formal.v

@@ -1,50 +1,36 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
+`default_nettype none
 
 
 module prod2u_p4_axis_cdc_structure_formal;
 module prod2u_p4_axis_cdc_structure_formal;
     (* gclk *) reg clk;
     (* gclk *) reg clk;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
-    (* anyseq *) reg limit_raw;
+    (* 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;
 
 
-    wire step_out;
-    wire busy;
-    wire drive_active;
-
-    prod2u_p4_axis_executor #(
-        .STANDARD_STEPS(4),
-        .LIMIT_CONFIRM_US(4),
-        .DIR_SETUP_US(2),
-        .SPEED0_HALF_US(2),
-        .SPEED1_HALF_US(2),
-        .SPEED2_HALF_US(2),
-        .SPEED3_HALF_US(2)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .tick_1us(1'b1),
-        .force_stop(1'b0),
-        .limit_raw(limit_raw),
-        .jog_start(1'b0),
-        .jog_dir(1'b0),
-        .jog_speed_code(2'd0),
-        .jog_steps(16'd1),
-        .standard_start(1'b0),
-        .standard_target_open(1'b0),
-        .step_out(step_out),
-        .dir_out(),
-        .busy(busy),
-        .drive_active(drive_active),
-        .position_valid(),
-        .current_aperture(),
-        .target_aperture()
+    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
     always @(posedge clk) begin
         rst_n <= 1'b1;
         rst_n <= 1'b1;
         if (rst_n) begin
         if (rst_n) begin
-            assert(!step_out);
-            assert(!busy);
-            assert(!drive_active);
+            assert(step_a == step_b);
+            assert(dir_a == dir_b);
+            assert(started_a == started_b);
         end
         end
-        cover(rst_n && limit_raw && !step_out && !busy);
+        cover(rst_n && legacy_limit && started_a);
     end
     end
 endmodule
 endmodule
+
+`default_nettype wire

+ 2 - 2
tests/formal/prod2u_p4_axis_force_jog_limit_ignore.sby

@@ -4,9 +4,9 @@ cover
 
 
 [options]
 [options]
 prove: mode prove
 prove: mode prove
-prove: depth 48
+prove: depth 32
 cover: mode cover
 cover: mode cover
-cover: depth 48
+cover: depth 32
 
 
 [engines]
 [engines]
 prove: abc pdr
 prove: abc pdr

+ 20 - 64
tests/formal/prod2u_p4_axis_force_jog_limit_ignore_formal.v

@@ -4,79 +4,35 @@
 module prod2u_p4_axis_force_jog_limit_ignore_formal;
 module prod2u_p4_axis_force_jog_limit_ignore_formal;
     (* gclk *) reg clk;
     (* gclk *) reg clk;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
-
-    (* anyseq *) reg force_stop;
-    (* anyseq *) reg limit_raw_a;
-    (* anyseq *) reg limit_raw_b;
-    (* anyseq *) reg jog_start;
-    (* anyseq *) reg jog_dir;
-    (* anyseq *) reg [1:0] jog_speed_code;
-    (* anyseq *) reg [15:0] jog_steps;
-    (* anyseq *) reg standard_start;
-    (* anyseq *) reg standard_target_open;
-
-    wire step_a;
-    wire dir_a;
-    wire busy_a;
-    wire drive_a;
-    wire valid_a;
-    wire [7:0] current_a;
-    wire [7:0] target_a;
-    wire step_b;
-    wire dir_b;
-    wire busy_b;
-    wire drive_b;
-    wire valid_b;
-    wire [7:0] current_b;
-    wire [7:0] target_b;
-
-    prod2u_p4_axis_executor #(
-        .STANDARD_STEPS(4), .DIR_SETUP_US(2),
-        .SPEED0_HALF_US(2), .SPEED1_HALF_US(2),
-        .SPEED2_HALF_US(2), .SPEED3_HALF_US(2)
-    ) dut_a (
-        .clk(clk), .rst_n(rst_n), .tick_1us(1'b1),
-        .force_stop(force_stop), .limit_raw(limit_raw_a),
-        .jog_start(jog_start), .jog_dir(jog_dir),
-        .jog_speed_code(jog_speed_code), .jog_steps(jog_steps),
-        .standard_start(standard_start),
-        .standard_target_open(standard_target_open),
-        .step_out(step_a), .dir_out(dir_a), .busy(busy_a),
-        .drive_active(drive_a), .position_valid(valid_a),
-        .current_aperture(current_a), .target_aperture(target_a)
+    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 #(
-        .STANDARD_STEPS(4), .DIR_SETUP_US(2),
-        .SPEED0_HALF_US(2), .SPEED1_HALF_US(2),
-        .SPEED2_HALF_US(2), .SPEED3_HALF_US(2)
-    ) dut_b (
-        .clk(clk), .rst_n(rst_n), .tick_1us(1'b1),
-        .force_stop(force_stop), .limit_raw(limit_raw_b),
-        .jog_start(jog_start), .jog_dir(jog_dir),
-        .jog_speed_code(jog_speed_code), .jog_steps(jog_steps),
-        .standard_start(standard_start),
-        .standard_target_open(standard_target_open),
-        .step_out(step_b), .dir_out(dir_b), .busy(busy_b),
-        .drive_active(drive_b), .position_valid(valid_b),
-        .current_aperture(current_b), .target_aperture(target_b)
+    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
     always @(posedge clk) begin
         rst_n <= 1'b1;
         rst_n <= 1'b1;
-        assume(!(jog_start && standard_start));
-
+        past_valid <= 1'b1;
         if (rst_n) begin
         if (rst_n) begin
             assert(step_a == step_b);
             assert(step_a == step_b);
             assert(dir_a == dir_b);
             assert(dir_a == dir_b);
-            assert(busy_a == busy_b);
-            assert(drive_a == drive_b);
-            assert(valid_a == valid_b);
-            assert(current_a == current_b);
-            assert(target_a == target_b);
+            assert(started_a == started_b);
         end
         end
-
-        cover(rst_n && (limit_raw_a != limit_raw_b) && busy_a && step_a);
+        cover(rst_n && (legacy_limit_a != legacy_limit_b) && started_a);
     end
     end
 endmodule
 endmodule
 
 

+ 2 - 2
tests/formal/prod2u_p4_axis_force_jog_replace.sby

@@ -4,9 +4,9 @@ cover
 
 
 [options]
 [options]
 bmc: mode bmc
 bmc: mode bmc
-bmc: depth 128
+bmc: depth 32
 cover: mode cover
 cover: mode cover
-cover: depth 128
+cover: depth 32
 
 
 [engines]
 [engines]
 bmc: smtbmc yices
 bmc: smtbmc yices

+ 22 - 152
tests/formal/prod2u_p4_axis_force_jog_replace_formal.v

@@ -2,172 +2,42 @@
 `default_nettype none
 `default_nettype none
 
 
 module prod2u_p4_axis_force_jog_replace_formal;
 module prod2u_p4_axis_force_jog_replace_formal;
-    localparam [3:0] PH_START = 4'd0;
-    localparam [3:0] PH_WAIT_FIRST_RISE = 4'd1;
-    localparam [3:0] PH_SEND_HIGH_REPLACE = 4'd2;
-    localparam [3:0] PH_WAIT_FALL = 4'd3;
-    localparam [3:0] PH_SEND_LOW_REPLACE = 4'd4;
-    localparam [3:0] PH_WAIT_BOUNDARY = 4'd5;
-    localparam [3:0] PH_WAIT_NEW_RISE = 4'd6;
-    localparam [3:0] PH_RUN_REPLACEMENT = 4'd7;
-    localparam [3:0] PH_DONE = 4'd8;
-
     (* gclk *) reg clk;
     (* gclk *) reg clk;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
-    reg [3:0] phase = PH_START;
-    reg jog_start = 1'b0;
-    reg jog_dir = 1'b0;
-    reg [15:0] jog_steps = 16'd4;
-    reg previous_step = 1'b0;
-    reg previous_busy = 1'b0;
-    reg [3:0] setup_low_cycles = 4'd0;
-    reg [2:0] replacement_rises = 3'd0;
-    reg saw_high_replacement = 1'b0;
-    reg saw_low_replacement = 1'b0;
-    reg saw_boundary = 1'b0;
-    reg done = 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 step_out;
     wire dir_out;
     wire dir_out;
-    wire busy;
-    wire drive_active;
-    wire position_valid;
-    wire [7:0] current_aperture;
-    wire [7:0] target_aperture;
-    wire step_rise = step_out && !previous_step;
-    wire step_fall = !step_out && previous_step;
-    wire busy_fall = !busy && previous_busy;
+    wire started_pulse;
 
 
     prod2u_p4_axis_executor #(
     prod2u_p4_axis_executor #(
-        .STANDARD_STEPS(4),
-        .DIR_SETUP_US(2),
-        .SPEED0_HALF_US(4),
-        .SPEED1_HALF_US(4),
-        .SPEED2_HALF_US(4),
-        .SPEED3_HALF_US(4)
+        .DIR_SETUP_CYCLES(3),
+        .STEP_HALF_CYCLES(2)
     ) dut (
     ) dut (
-        .clk(clk), .rst_n(rst_n), .tick_1us(1'b1),
-        .force_stop(1'b0), .limit_raw(1'b0),
-        .jog_start(jog_start), .jog_dir(jog_dir),
-        .jog_speed_code(2'd3), .jog_steps(jog_steps),
-        .standard_start(1'b0), .standard_target_open(1'b0),
-        .step_out(step_out), .dir_out(dir_out), .busy(busy),
-        .drive_active(drive_active), .position_valid(position_valid),
-        .current_aperture(current_aperture),
-        .target_aperture(target_aperture)
+        .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
     always @(posedge clk) begin
         rst_n <= 1'b1;
         rst_n <= 1'b1;
-        previous_step <= step_out;
-        previous_busy <= busy;
-        jog_start <= 1'b0;
-
-        if (!rst_n) begin
-            phase <= PH_START;
-            setup_low_cycles <= 4'd0;
-            replacement_rises <= 3'd0;
-            saw_high_replacement <= 1'b0;
-            saw_low_replacement <= 1'b0;
-            saw_boundary <= 1'b0;
-            done <= 1'b0;
-        end else begin
-            case (phase)
-                PH_START: begin
-                    jog_start <= 1'b1;
-                    jog_dir <= 1'b0;
-                    jog_steps <= 16'd4;
-                    phase <= PH_WAIT_FIRST_RISE;
-                end
-
-                PH_WAIT_FIRST_RISE: if (step_rise) begin
-                    assert(busy);
-                    assert(!dir_out);
-                    phase <= PH_SEND_HIGH_REPLACE;
-                end
-
-                PH_SEND_HIGH_REPLACE: begin
-                    assert(step_out);
-                    assert(busy);
-                    jog_start <= 1'b1;
-                    jog_dir <= 1'b0;
-                    jog_steps <= 16'd2;
-                    saw_high_replacement <= 1'b1;
-                    phase <= PH_WAIT_FALL;
-                end
-
-                PH_WAIT_FALL: if (step_fall) begin
-                    assert(busy);
-                    assert(!dir_out);
-                    phase <= PH_SEND_LOW_REPLACE;
-                end
+        past_valid <= 1'b1;
 
 
-                PH_SEND_LOW_REPLACE: begin
-                    assert(!step_out);
-                    assert(busy);
-                    jog_start <= 1'b1;
-                    jog_dir <= 1'b1;
-                    jog_steps <= 16'd3;
-                    saw_low_replacement <= 1'b1;
-                    phase <= PH_WAIT_BOUNDARY;
-                end
-
-                PH_WAIT_BOUNDARY: begin
-                    assert(!step_out);
-                    if (busy_fall) begin
-                        assert(dir_out);
-                        assert(drive_active);
-                        saw_boundary <= 1'b1;
-                        // The boundary cycle itself is the first guaranteed
-                        // STEP-low setup interval.
-                        setup_low_cycles <= 4'd1;
-                        phase <= PH_WAIT_NEW_RISE;
-                    end
-                end
-
-                PH_WAIT_NEW_RISE: begin
-                    assert(dir_out);
-                    assert(drive_active);
-                    if (step_rise) begin
-                        assert(busy);
-                        assert(setup_low_cycles >= 4'd2);
-                        replacement_rises <= 3'd1;
-                        phase <= PH_RUN_REPLACEMENT;
-                    end else begin
-                        assert(!busy);
-                        assert(!step_out);
-                        setup_low_cycles <= setup_low_cycles + 4'd1;
-                    end
-                end
-
-                PH_RUN_REPLACEMENT: begin
-                    assert(dir_out);
-                    if (step_rise) begin
-                        replacement_rises <= replacement_rises + 3'd1;
-                    end
-                    if (busy_fall) begin
-                        assert(replacement_rises == 3'd3);
-                        assert(!step_out);
-                        assert(!drive_active);
-                        assert(!position_valid);
-                        assert(current_aperture == 8'hff);
-                        assert(target_aperture == 8'hff);
-                        done <= 1'b1;
-                        phase <= PH_DONE;
-                    end
-                end
-
-                default: begin
-                    assert(!busy);
-                    assert(!step_out);
-                    assert(!drive_active);
-                    assert(replacement_rises == 3'd3);
-                end
-            endcase
+        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
         end
 
 
-        cover(done && saw_high_replacement && saw_low_replacement &&
-            saw_boundary && (replacement_rises == 3'd3));
+        cover(past_valid && $past(step_out) && $past(command_start) &&
+            !step_out && (dir_out == $past(command_dir)));
+        cover(rst_n && started_pulse && step_out);
     end
     end
 endmodule
 endmodule
 
 

+ 2 - 3
tests/formal/prod2u_p4_axis_safety.sby

@@ -4,9 +4,9 @@ cover
 
 
 [options]
 [options]
 prove: mode prove
 prove: mode prove
-prove: depth 64
+prove: depth 32
 cover: mode cover
 cover: mode cover
-cover: depth 64
+cover: depth 32
 
 
 [engines]
 [engines]
 prove: abc pdr
 prove: abc pdr
@@ -14,7 +14,6 @@ cover: smtbmc yices
 
 
 [script]
 [script]
 read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_axis_safety_formal.v
 read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_axis_safety_formal.v
-select -assert-count 1 a:async_reg=true
 prep -top prod2u_p4_axis_safety_formal
 prep -top prod2u_p4_axis_safety_formal
 
 
 [files]
 [files]

+ 113 - 109
tests/formal/prod2u_p4_axis_safety_formal.v

@@ -2,132 +2,136 @@
 `default_nettype none
 `default_nettype none
 
 
 module prod2u_p4_axis_safety_formal;
 module prod2u_p4_axis_safety_formal;
-    (* gclk *) reg clk;
-    reg rst_n = 1'b0;
-    reg [2:0] history_valid = 3'b000;
+    localparam integer DUT_DIR_SETUP_CYCLES = 3;
+    localparam integer DUT_STEP_HALF_CYCLES = 2;
 
 
-    (* anyseq *) reg force_stop;
-    (* anyseq *) reg limit_raw;
-    (* anyseq *) reg jog_start;
-    (* anyseq *) reg jog_dir;
-    (* anyseq *) reg [1:0] jog_speed_code;
-    (* anyseq *) reg [15:0] jog_steps;
-    (* anyseq *) reg standard_start;
-    (* anyseq *) reg standard_target_open;
+    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 step_out;
     wire dir_out;
     wire dir_out;
-    wire busy;
-    wire drive_active;
+    wire started_pulse;
+
+    // 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 #(
     prod2u_p4_axis_executor #(
-        .STANDARD_STEPS(4),
-        .LIMIT_CONFIRM_US(4),
-        .DIR_SETUP_US(2),
-        .SPEED0_HALF_US(2),
-        .SPEED1_HALF_US(2),
-        .SPEED2_HALF_US(2),
-        .SPEED3_HALF_US(2)
+        .DIR_SETUP_CYCLES(DUT_DIR_SETUP_CYCLES),
+        .STEP_HALF_CYCLES(DUT_STEP_HALF_CYCLES)
     ) dut (
     ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .tick_1us(1'b1),
-        .force_stop(force_stop),
-        .limit_raw(limit_raw),
-        .jog_start(jog_start),
-        .jog_dir(jog_dir),
-        .jog_speed_code(jog_speed_code),
-        .jog_steps(jog_steps),
-        .standard_start(standard_start),
-        .standard_target_open(standard_target_open),
-        .step_out(step_out),
-        .dir_out(dir_out),
-        .busy(busy),
-        .drive_active(drive_active),
-        .position_valid(),
-        .current_aperture(),
-        .target_aperture()
+        .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 @(*) begin
-        if (rst_n && force_stop) begin
-            assert(!step_out);
-            assert(!busy);
-            assert(!drive_active);
-        end
-    end
-
     always @(posedge clk) begin
     always @(posedge clk) begin
         rst_n <= 1'b1;
         rst_n <= 1'b1;
-        history_valid <= {history_valid[1:0], rst_n};
-
-        // The command source emits one command kind per cycle. Version one
-        // deliberately permits valid JOG requests in every motion phase.
-        assume(!(jog_start && standard_start));
-
-        if (history_valid[0]) begin
-            assert(!step_out || busy);
-            assert(!step_out || drive_active);
-
-            // Reported busy is evidence of an emitted STEP, not merely setup
-            // or an enabled driver.
-            if (busy && !$past(busy)) begin
-                assert(step_out);
-                assert(!$past(step_out));
+        previous_step <= step_out;
+
+        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
             end
-
-            // A normal completion clears busy only after the final low phase.
-            if (!busy && $past(busy) && !force_stop && !$past(force_stop)) begin
-                assert(!step_out);
-                assert(!$past(step_out));
-            end
-
-            // DIR may change only while STEP is low. Replacement JOG clears
-            // busy at this boundary and then starts a fresh setup interval.
-            if (dir_out != $past(dir_out)) begin
-                assert(!step_out);
-                assert(!$past(step_out));
-                assert(!busy);
-            end
-
-            // Every non-truncated falling edge is the end of a complete high
-            // phase. Hard stop is the sole permitted truncation path.
-            if (!step_out && $past(step_out) &&
-                !force_stop && !$past(force_stop)) begin
-                assert($past(busy));
-                assert(busy);
+            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;
+                if (command_steps == 16'd0) begin
+                    spec_active <= 1'b0;
+                    spec_setup_left <= 2'd0;
+                end else begin
+                    spec_active <= 1'b1;
+                    spec_setup_left <= SPEC_DIR_SETUP_CYCLES;
+                end
+            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
         end
         end
 
 
-        if (history_valid[1]) begin
-            // With two one-microsecond setup ticks, every rise has two prior
-            // low samples and a stable direction.
-            if (step_out && !$past(step_out)) begin
-                assert(!$past(step_out, 2));
-                assert(dir_out == $past(dir_out));
-                assert(dir_out == $past(dir_out, 2));
-            end
-
-            // With a two-tick half-period, a normal high phase cannot be one
-            // clock long.
-            if (!step_out && $past(step_out) &&
-                !force_stop && !$past(force_stop) && !$past(force_stop, 2)) begin
-                assert($past(step_out, 2));
-            end
-
-            // Likewise busy cannot clear until at least the complete low half
-            // has elapsed after the final falling edge.
-            if (!busy && $past(busy) &&
-                !force_stop && !$past(force_stop) && !$past(force_stop, 2)) begin
-                assert(!$past(step_out));
-                assert(!$past(step_out, 2));
-            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);
         end
         end
 
 
-        cover(rst_n && drive_active && !busy && !step_out);
-        cover(rst_n && busy && step_out);
-        cover(history_valid[0] && $past(busy) && !busy && !force_stop);
-        cover(history_valid[0] && $past(step_out) && force_stop && !step_out);
+        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
     end
 endmodule
 endmodule
 
 

+ 2 - 2
tests/formal/prod2u_p4_core_disable_motor_safety.sby

@@ -4,9 +4,9 @@ cover
 
 
 [options]
 [options]
 bmc: mode bmc
 bmc: mode bmc
-bmc: depth 96
+bmc: depth 192
 cover: mode cover
 cover: mode cover
-cover: depth 96
+cover: depth 192
 
 
 [engines]
 [engines]
 bmc: smtbmc yices
 bmc: smtbmc yices

+ 192 - 55
tests/formal/prod2u_p4_core_disable_motor_safety_formal.v

@@ -1,121 +1,258 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
+`default_nettype none
 
 
 module prod2u_p4_core_disable_motor_safety_formal;
 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 [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;
     (* gclk *) reg clk;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
-    reg [2:0] phase = 3'd0;
+    reg [3:0] phase = PH_JOG_SEND;
+    reg previous_x_step = 1'b0;
+    reg reference_jog_start = 1'b0;
     reg [271:0] request_payload;
     reg [271:0] request_payload;
-    wire request_valid = phase == 3'd0;
+
+    wire request_valid = (phase == PH_JOG_SEND) ||
+        (phase == PH_SNAPSHOT_SEND) || (phase == PH_DISABLE_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 request_ready;
     wire [191:0] ptc_percent;
     wire [191:0] ptc_percent;
     wire [31:0] fan_percent;
     wire [31:0] fan_percent;
     wire [7:0] solenoid_percent;
     wire [7:0] solenoid_percent;
     wire [15:0] state_hash16;
     wire [15:0] state_hash16;
     wire [2:0] step_out;
     wire [2:0] step_out;
+    wire [2:0] dir_out;
     wire en_n;
     wire en_n;
     wire disabled;
     wire disabled;
     wire watchdog_timeout;
     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;
+    reg [1:0] jog_ack_delay = 2'd0;
+    localparam [1:0] EXPECTED_JOG_ACK_DELAY = 2'd2;
 
 
     always @(*) begin
     always @(*) begin
         request_payload = 272'd0;
         request_payload = 272'd0;
-        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'd16;
+        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
     end
 
 
     prod2u_p4_normal_v3_core #(
     prod2u_p4_normal_v3_core #(
         .CLK_HZ(1),
         .CLK_HZ(1),
-        .WATCHDOG_SECONDS(32),
-        .STANDARD_STEPS(4),
-        .DIR_SETUP_US(1),
-        .SPEED0_HALF_US(4),
-        .SPEED1_HALF_US(3),
-        .SPEED2_HALF_US(2),
-        .SPEED3_HALF_US(1)
+        .WATCHDOG_SECONDS(64),
+        .DIR_SETUP_CYCLES(2),
+        .STEP_HALF_CYCLES(2)
     ) dut (
     ) dut (
         .clk(clk),
         .clk(clk),
         .rst_n(rst_n),
         .rst_n(rst_n),
-        .tick_1us(1'b1),
         .request_valid(request_valid),
         .request_valid(request_valid),
         .request_ready(request_ready),
         .request_ready(request_ready),
-        .request_type(FT_MOTION_CMD),
-        .request_length(6'd8),
+        .request_type(request_type),
+        .request_length(request_length),
         .request_payload(request_payload),
         .request_payload(request_payload),
         .request_crc16(16'h3501),
         .request_crc16(16'h3501),
-        .emergency_disable_valid(phase == 3'd2),
-        .emergency_disable_crc16(16'hd15a),
-        .frame_valid(),
+        .frame_valid(frame_valid),
         .frame_ready(1'b1),
         .frame_ready(1'b1),
-        .frame_type(),
-        .frame_payload_len(),
-        .frame_payload(),
-        .x_limit_raw(1'b0),
-        .y_limit_raw(1'b0),
+        .frame_type(frame_type),
+        .frame_payload_len(frame_payload_len),
+        .frame_payload(frame_payload),
         .ptc_percent(ptc_percent),
         .ptc_percent(ptc_percent),
         .fan_percent(fan_percent),
         .fan_percent(fan_percent),
         .solenoid_percent(solenoid_percent),
         .solenoid_percent(solenoid_percent),
         .state_hash16(state_hash16),
         .state_hash16(state_hash16),
         .step_out(step_out),
         .step_out(step_out),
-        .dir_out(),
+        .dir_out(dir_out),
         .en_n(en_n),
         .en_n(en_n),
         .disabled(disabled),
         .disabled(disabled),
         .watchdog_timeout(watchdog_timeout)
         .watchdog_timeout(watchdog_timeout)
     );
     );
 
 
-    always @(*) begin
-        if (rst_n && (phase == 3'd2)) begin
-            assert(step_out == 3'b000);
-            assert(en_n);
-        end
-    end
+    prod2u_p4_motor_hub #(
+        .DIR_SETUP_CYCLES(2),
+        .STEP_HALF_CYCLES(2)
+    ) reference_motors (
+        .clk(clk),
+        .rst_n(rst_n),
+        .jog_start(reference_jog_start),
+        .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
     always @(posedge clk) begin
         rst_n <= 1'b1;
         rst_n <= 1'b1;
+        reference_jog_start <= 1'b0;
+        previous_x_step <= step_out[0];
+
         if (!rst_n) begin
         if (!rst_n) begin
-            phase <= 3'd0;
+            phase <= PH_JOG_SEND;
+            previous_x_step <= 1'b0;
+            reference_jog_start <= 1'b0;
+            first_step_seen <= 1'b0;
+            jog_ack_seen <= 1'b0;
+            jog_ack_delay <= 2'd0;
         end else begin
         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;
+                jog_ack_delay <= EXPECTED_JOG_ACK_DELAY;
+            end else if (jog_ack_delay != 0) begin
+                jog_ack_delay <= jog_ack_delay - 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(jog_ack_delay == 2'd1);
+                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
+            if (!jog_ack_seen && (jog_ack_delay == 2'd1)) begin
+                assert(frame_valid);
+            end
+
             case (phase)
             case (phase)
-                3'd0: if (request_valid && request_ready) phase <= 3'd1;
-                3'd1: if (!en_n && !request_ready) begin
+                PH_JOG_SEND: begin
+                    assert(disabled);
+                    assert(!watchdog_timeout);
+                    if (request_valid && request_ready) begin
+                        reference_jog_start <= 1'b1;
+                        phase <= PH_WAIT_FIRST_STEP;
+                    end
+                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(!disabled);
                     assert(!watchdog_timeout);
                     assert(!watchdog_timeout);
-                    phase <= 3'd2;
+                    if (request_valid && request_ready) begin
+                        phase <= PH_WAIT_SAFE;
+                    end
                 end
                 end
-                3'd2: begin
-                    assert(!request_ready);
-                    assert(step_out == 3'b000);
-                    assert(en_n);
-                    phase <= 3'd3;
+
+                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
                 end
-                3'd3: if (disabled) begin
+
+                PH_WAIT_POST_DISABLE_STEP: begin
+                    assert(disabled);
                     assert(!watchdog_timeout);
                     assert(!watchdog_timeout);
                     assert(state_hash16 == 16'he177);
                     assert(state_hash16 == 16'he177);
                     assert(ptc_percent == 192'd0);
                     assert(ptc_percent == 192'd0);
                     assert(fan_percent == {4{8'd30}});
                     assert(fan_percent == {4{8'd30}});
                     assert(solenoid_percent == 8'd0);
                     assert(solenoid_percent == 8'd0);
-                    assert(step_out == 3'b000);
-                    assert(en_n);
-                    phase <= 3'd4;
-                end
-                3'd4: begin
-                    assert(disabled);
-                    assert(!watchdog_timeout);
-                    assert(step_out == 3'b000);
-                    assert(en_n);
-                    phase <= 3'd5;
+                    if (step_out[0] && !previous_x_step) begin
+                        phase <= PH_DONE;
+                    end
                 end
                 end
+
                 default: begin
                 default: begin
+                    assert(phase == PH_DONE);
                     assert(disabled);
                     assert(disabled);
                     assert(!watchdog_timeout);
                     assert(!watchdog_timeout);
-                    assert(step_out == 3'b000);
-                    assert(en_n);
+                    assert(state_hash16 == 16'he177);
+                    assert(ptc_percent == 192'd0);
+                    assert(fan_percent == {4{8'd30}});
+                    assert(solenoid_percent == 8'd0);
                 end
                 end
             endcase
             endcase
-            cover(phase == 3'd5);
+
+            cover(phase == PH_DONE);
         end
         end
     end
     end
 endmodule
 endmodule
+
+`default_nettype wire

+ 2 - 2
tests/formal/prod2u_p4_core_watchdog_race.sby

@@ -4,9 +4,9 @@ cover
 
 
 [options]
 [options]
 bmc: mode bmc
 bmc: mode bmc
-bmc: depth 96
+bmc: depth 192
 cover: mode cover
 cover: mode cover
-cover: depth 96
+cover: depth 192
 
 
 [engines]
 [engines]
 bmc: smtbmc yices
 bmc: smtbmc yices

+ 255 - 73
tests/formal/prod2u_p4_core_watchdog_race_formal.v

@@ -1,149 +1,331 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
+`default_nettype none
 
 
 module prod2u_p4_core_watchdog_race_formal;
 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 [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;
     (* gclk *) reg clk;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
-    reg [3:0] phase = 4'd0;
-    reg [3:0] lease_age = 4'd0;
+    reg [3:0] phase = PH_UNARMED_STATUS_SEND;
+    reg previous_x_step = 1'b0;
+    reg saw_jog_step = 1'b0;
+    reg reference_jog_start = 1'b0;
+    reg shadow_tracking = 1'b0;
     reg [271:0] request_payload;
     reg [271:0] request_payload;
-    wire request_valid = (phase == 4'd0) ||
-        ((phase == 4'd2) && (lease_age == 4'd5)) || (phase == 4'd3);
+    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 request_ready;
     wire [191:0] ptc_percent;
     wire [191:0] ptc_percent;
     wire [31:0] fan_percent;
     wire [31:0] fan_percent;
     wire [7:0] solenoid_percent;
     wire [7:0] solenoid_percent;
     wire [15:0] state_hash16;
     wire [15:0] state_hash16;
     wire [2:0] step_out;
     wire [2:0] step_out;
+    wire [2:0] dir_out;
     wire en_n;
     wire en_n;
     wire disabled;
     wire disabled;
     wire watchdog_timeout;
     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_JOG_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
     always @(*) begin
         request_payload = 272'd0;
         request_payload = 272'd0;
-        if (phase == 4'd0) 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'd16;
-        end else begin
-            request_payload[7:0] = 8'h37;
-        end
+        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
     end
 
 
     prod2u_p4_normal_v3_core #(
     prod2u_p4_normal_v3_core #(
         .CLK_HZ(1),
         .CLK_HZ(1),
-        .WATCHDOG_SECONDS(8),
-        .STANDARD_STEPS(4),
-        .DIR_SETUP_US(1),
-        .SPEED0_HALF_US(4),
-        .SPEED1_HALF_US(3),
-        .SPEED2_HALF_US(2),
-        .SPEED3_HALF_US(1)
+        .WATCHDOG_SECONDS(64),
+        .DIR_SETUP_CYCLES(2),
+        .STEP_HALF_CYCLES(2)
     ) dut (
     ) dut (
         .clk(clk),
         .clk(clk),
         .rst_n(rst_n),
         .rst_n(rst_n),
-        .tick_1us(1'b1),
         .request_valid(request_valid),
         .request_valid(request_valid),
         .request_ready(request_ready),
         .request_ready(request_ready),
-        .request_type(FT_MOTION_CMD),
-        .request_length(6'd8),
+        .request_type(request_type),
+        .request_length(request_length),
         .request_payload(request_payload),
         .request_payload(request_payload),
-        .request_crc16({12'd0, phase}),
-        .emergency_disable_valid(phase == 4'd5),
-        .emergency_disable_crc16(16'hd15a),
+        .request_crc16(16'h3701),
         .frame_valid(),
         .frame_valid(),
         .frame_ready(1'b1),
         .frame_ready(1'b1),
         .frame_type(),
         .frame_type(),
         .frame_payload_len(),
         .frame_payload_len(),
         .frame_payload(),
         .frame_payload(),
-        .x_limit_raw(1'b0),
-        .y_limit_raw(1'b0),
         .ptc_percent(ptc_percent),
         .ptc_percent(ptc_percent),
         .fan_percent(fan_percent),
         .fan_percent(fan_percent),
         .solenoid_percent(solenoid_percent),
         .solenoid_percent(solenoid_percent),
         .state_hash16(state_hash16),
         .state_hash16(state_hash16),
         .step_out(step_out),
         .step_out(step_out),
-        .dir_out(),
+        .dir_out(dir_out),
         .en_n(en_n),
         .en_n(en_n),
         .disabled(disabled),
         .disabled(disabled),
         .watchdog_timeout(watchdog_timeout)
         .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(reference_jog_start),
+        .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
     always @(posedge clk) begin
         rst_n <= 1'b1;
         rst_n <= 1'b1;
+        reference_jog_start <= 1'b0;
+        previous_x_step <= step_out[0];
+        if (step_out[0]) begin
+            saw_jog_step <= 1'b1;
+        end
+
         if (!rst_n) begin
         if (!rst_n) begin
-            phase <= 4'd0;
-            lease_age <= 4'd0;
+            phase <= PH_UNARMED_STATUS_SEND;
+            previous_x_step <= 1'b0;
+            saw_jog_step <= 1'b0;
+            reference_jog_start <= 1'b0;
+            shadow_tracking <= 1'b0;
         end else begin
         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)
             case (phase)
-                4'd0: if (request_valid && request_ready) phase <= 4'd1;
-                4'd1: if (!en_n && !disabled) begin
+                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(!disabled);
                     assert(!watchdog_timeout);
                     assert(!watchdog_timeout);
-                    lease_age <= 4'd0;
-                    phase <= 4'd2;
+                    if (request_valid && request_ready) begin
+                        reference_jog_start <= 1'b1;
+                        phase <= PH_WAIT_JOG;
+                    end
                 end
                 end
-                4'd2: begin
+
+                PH_WAIT_JOG: begin
+                    assert(!disabled);
                     assert(!watchdog_timeout);
                     assert(!watchdog_timeout);
-                    if (lease_age == 4'd5) begin
-                        assert(request_valid);
-                        assert(!request_ready);
-                        assert(step_out == 3'b000);
-                        assert(en_n);
-                        phase <= 4'd3;
-                    end else begin
-                        lease_age <= lease_age + 4'd1;
+                    if (saw_jog_step && request_ready) begin
+                        phase <= PH_EARLY_STATUS_SEND;
                     end
                     end
                 end
                 end
-                4'd3: begin
-                    assert(request_valid);
-                    assert(watchdog_timeout);
+
+                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(disabled);
+                    assert(watchdog_timeout);
+                    assert(!shadow_armed);
                     assert(state_hash16 == 16'he177);
                     assert(state_hash16 == 16'he177);
                     assert(ptc_percent == 192'd0);
                     assert(ptc_percent == 192'd0);
                     assert(fan_percent == {4{8'd30}});
                     assert(fan_percent == {4{8'd30}});
                     assert(solenoid_percent == 8'd0);
                     assert(solenoid_percent == 8'd0);
-                    assert(step_out == 3'b000);
-                    assert(en_n);
-                    phase <= 4'd4;
+                    phase <= PH_WAIT_RACE_RESPONSE;
                 end
                 end
-                4'd4: begin
-                    assert(watchdog_timeout);
+
+                PH_WAIT_RACE_RESPONSE: begin
                     assert(disabled);
                     assert(disabled);
-                    assert(step_out == 3'b000);
-                    assert(en_n);
-                    phase <= 4'd5;
+                    assert(watchdog_timeout);
+                    assert(!shadow_armed);
+                    if (request_ready) begin
+                        phase <= PH_TIMEOUT_STATUS_SEND;
+                    end
                 end
                 end
-                4'd5: begin
-                    assert(step_out == 3'b000);
-                    assert(en_n);
-                    phase <= 4'd6;
+
+                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
                 end
-                4'd6: begin
+
+                PH_WAIT_TIMEOUT_STATUS: begin
                     assert(disabled);
                     assert(disabled);
-                    assert(!watchdog_timeout);
-                    assert(step_out == 3'b000);
-                    assert(en_n);
-                    phase <= 4'd7;
+                    assert(watchdog_timeout);
+                    assert(!shadow_armed);
+                    if (request_ready) begin
+                        phase <= PH_WAIT_POST_TIMEOUT_STEP;
+                    end
                 end
                 end
-                4'd7: begin
+
+                PH_WAIT_POST_TIMEOUT_STEP: begin
                     assert(disabled);
                     assert(disabled);
-                    assert(!watchdog_timeout);
-                    assert(step_out == 3'b000);
-                    assert(en_n);
-                    phase <= 4'd8;
+                    assert(watchdog_timeout);
+                    assert(!shadow_armed);
+                    if (step_out[0] && !previous_x_step) begin
+                        phase <= PH_DONE;
+                    end
                 end
                 end
+
                 default: begin
                 default: begin
+                    assert(phase == PH_DONE);
                     assert(disabled);
                     assert(disabled);
-                    assert(!watchdog_timeout);
-                    assert(step_out == 3'b000);
-                    assert(en_n);
+                    assert(watchdog_timeout);
+                    assert(!shadow_armed);
                 end
                 end
             endcase
             endcase
-            cover(phase == 4'd8);
+
+            cover(phase == PH_DONE);
         end
         end
     end
     end
 endmodule
 endmodule
+
+`default_nettype wire

+ 5 - 10
tests/formal/prod2u_p4_jog_no_gates.sby

@@ -6,13 +6,13 @@ cover_hub
 
 
 [options]
 [options]
 bmc_core: mode bmc
 bmc_core: mode bmc
-bmc_core: depth 96
+bmc_core: depth 32
 cover_core: mode cover
 cover_core: mode cover
-cover_core: depth 96
+cover_core: depth 32
 bmc_hub: mode bmc
 bmc_hub: mode bmc
-bmc_hub: depth 48
+bmc_hub: depth 32
 cover_hub: mode cover
 cover_hub: mode cover
-cover_hub: depth 48
+cover_hub: depth 32
 
 
 [engines]
 [engines]
 bmc_core: smtbmc yices
 bmc_core: smtbmc yices
@@ -21,18 +21,13 @@ bmc_hub: smtbmc yices
 cover_hub: smtbmc yices
 cover_hub: smtbmc yices
 
 
 [script]
 [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_jog_no_gates_formal.v
+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
 bmc_core: prep -top prod2u_p4_core_jog_no_busy_formal
 cover_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
 bmc_hub: prep -top prod2u_p4_hub_jog_no_gate_formal
 cover_hub: prep -top prod2u_p4_hub_jog_no_gate_formal
 cover_hub: prep -top prod2u_p4_hub_jog_no_gate_formal
 
 
 [files]
 [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_axis_executor.v
 ../../src/rtl/prod2u_p4_motor_hub.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_jog_no_gates_formal.v
 prod2u_p4_jog_no_gates_formal.v

+ 45 - 248
tests/formal/prod2u_p4_jog_no_gates_formal.v

@@ -2,273 +2,70 @@
 `default_nettype none
 `default_nettype none
 
 
 module prod2u_p4_core_jog_no_busy_formal;
 module prod2u_p4_core_jog_no_busy_formal;
-    localparam [7:0] FT_MOTION_CMD = 8'h11;
-    localparam [7:0] FT_HOST_ACK = 8'h06;
-    localparam [7:0] MOTION_JOG = 8'h35;
-    localparam [7:0] STATUS_OK = 8'h00;
-    localparam [7:0] STATUS_BUSY = 8'h09;
-
     (* gclk *) reg clk;
     (* gclk *) reg clk;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
-    reg request_valid = 1'b0;
-    reg [3:0] phase = 4'd0;
-    reg second_ack_seen = 1'b0;
-    reg [3:0] motion_wait = 4'd0;
-
-    reg [271:0] request_payload;
-    wire request_ready;
-    wire frame_valid;
-    wire [7:0] frame_type;
-    wire [143:0] frame_payload;
-    wire watchdog_timeout;
-    wire en_n;
-
-    always @(*) begin
-        request_payload = 272'd0;
-        request_payload[7:0] = MOTION_JOG;
-        request_payload[15:8] = 8'd0;
-        request_payload[23:16] = 8'd1;
-        request_payload[31:24] = 8'd3;
-        request_payload[47:32] = 16'd32;
-    end
+    (* 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_normal_v3_core #(
-        .CLK_HZ(1),
-        .WATCHDOG_SECONDS(12),
-        .STANDARD_STEPS(4),
-        .DIR_SETUP_US(1),
-        .SPEED0_HALF_US(1),
-        .SPEED1_HALF_US(1),
-        .SPEED2_HALF_US(1),
-        .SPEED3_HALF_US(1)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .tick_1us(1'b1),
-        .request_valid(request_valid),
-        .request_ready(request_ready),
-        .request_type(FT_MOTION_CMD),
-        .request_length(6'd8),
-        .request_payload(request_payload),
-        .request_crc16(16'h3500),
-        .emergency_disable_valid(1'b0),
-        .emergency_disable_crc16(16'd0),
-        .frame_valid(frame_valid),
-        .frame_ready(1'b1),
-        .frame_type(frame_type),
-        .frame_payload_len(),
-        .frame_payload(frame_payload),
-        .x_limit_raw(1'b0),
-        .y_limit_raw(1'b1),
-        .ptc_percent(),
-        .fan_percent(),
-        .solenoid_percent(),
-        .state_hash16(),
-        .step_out(),
-        .dir_out(),
-        .en_n(en_n),
-        .disabled(),
-        .watchdog_timeout(watchdog_timeout)
+    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
     always @(posedge clk) begin
         rst_n <= 1'b1;
         rst_n <= 1'b1;
-        request_valid <= 1'b0;
-
-        if (!rst_n) begin
-            phase <= 4'd0;
-            second_ack_seen <= 1'b0;
-            motion_wait <= 4'd0;
-        end else begin
-            // This harness only issues valid JOG requests, so BUSY is never a
-            // permitted result regardless of the preceding watchdog state.
-            if (frame_valid && (frame_type == FT_HOST_ACK) &&
-                (frame_payload[15:8] == MOTION_JOG)) begin
-                assert(frame_payload[23:16] != STATUS_BUSY);
-                assert(frame_payload[23:16] == STATUS_OK);
-                assert(frame_payload[0]);
-                if (phase >= 4'd5) second_ack_seen <= 1'b1;
-            end
-
-            case (phase)
-                4'd0: begin
-                    if (request_ready) begin
-                        request_valid <= 1'b1;
-                        phase <= 4'd1;
-                    end
-                end
-                4'd1: begin
-                    if (request_valid && request_ready) phase <= 4'd2;
-                end
-                4'd2: begin
-                    if (frame_valid && (frame_type == FT_HOST_ACK) &&
-                        (frame_payload[15:8] == MOTION_JOG)) begin
-                        phase <= 4'd3;
-                    end
-                end
-                4'd3: begin
-                    if (watchdog_timeout && request_ready) begin
-                        request_valid <= 1'b1;
-                        phase <= 4'd4;
-                    end
-                end
-                4'd4: begin
-                    if (request_valid && request_ready) begin
-                        motion_wait <= 4'd0;
-                        phase <= 4'd5;
-                    end
-                end
-                4'd5: begin
-                    // Forwarding is observed through the public drive request:
-                    // an accepted JOG must leave the hard-stopped idle output.
-                    if (!en_n) begin
-                        phase <= 4'd6;
-                    end else begin
-                        assert(motion_wait < 4'd8);
-                        motion_wait <= motion_wait + 4'd1;
-                    end
-                end
-                4'd6: begin
-                    if (second_ack_seen) phase <= 4'd7;
-                end
-                default: phase <= phase;
-            endcase
-
-            cover(phase == 4'd7);
+        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
         end
+        cover(rst_n && (legacy_limit || legacy_disabled || legacy_watchdog) &&
+            (|started));
     end
     end
 endmodule
 endmodule
 
 
 module prod2u_p4_hub_jog_no_gate_formal;
 module prod2u_p4_hub_jog_no_gate_formal;
     (* gclk *) reg clk;
     (* gclk *) reg clk;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
-    reg jog_valid = 1'b0;
-    reg jog_dir = 1'b0;
-    reg snapshot_valid = 1'b0;
-    reg disabled = 1'b0;
-    reg [3:0] phase = 4'd0;
-    reg [3:0] replacement_wait = 4'd0;
-    reg disable_hard_stop_seen = 1'b0;
-
-    wire jog_result_valid;
-    wire jog_accepted;
-    wire [2:0] axis_active_mask;
-    wire [2:0] axis_busy_mask;
-    wire [2:0] step_out;
-    wire [2:0] dir_out;
-    wire en_n;
-
-    prod2u_p4_motor_hub #(
-        .STANDARD_STEPS(4),
-        .LIMIT_CONFIRM_US(4),
-        .DIR_SETUP_US(1),
-        .SPEED0_HALF_US(1),
-        .SPEED1_HALF_US(1),
-        .SPEED2_HALF_US(1),
-        .SPEED3_HALF_US(1)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .tick_1us(1'b1),
-        .force_stop(1'b0),
-        .disabled(disabled),
-        .watchdog_timeout(1'b0),
-        .x_limit_raw(1'b1),
-        .y_limit_raw(1'b0),
-        .snapshot_valid(snapshot_valid),
-        .snapshot_targets(24'd0),
-        .snapshot_busy_at_accept(3'b111),
-        .snapshot_result_valid(),
-        .snapshot_busy_mask(),
-        .snapshot_invalid_mask(),
-        .snapshot_accepted_mask(),
-        .jog_valid(jog_valid),
-        .jog_axis(2'd0),
-        .jog_dir(jog_dir),
-        .jog_speed_code(2'd3),
-        .jog_steps(16'd32),
-        .jog_result_valid(jog_result_valid),
-        .jog_accepted(jog_accepted),
-        .axis_active_mask(axis_active_mask),
-        .axis_busy_mask(axis_busy_mask),
-        .step_out(step_out),
-        .dir_out(dir_out),
-        .en_n(en_n),
-        .status_payload()
+    (* 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
     always @(posedge clk) begin
         rst_n <= 1'b1;
         rst_n <= 1'b1;
-        jog_valid <= 1'b0;
-        snapshot_valid <= 1'b0;
-
-        if (!rst_n) begin
-            phase <= 4'd0;
-            disabled <= 1'b0;
-            jog_dir <= 1'b0;
-            replacement_wait <= 4'd0;
-            disable_hard_stop_seen <= 1'b0;
-        end else begin
-            if (disabled) begin
-                assert(step_out == 3'b000);
-                assert(en_n);
-                assert(axis_active_mask == 3'b000);
-                assert(axis_busy_mask == 3'b000);
-                disable_hard_stop_seen <= 1'b1;
-            end
-
-            case (phase)
-                4'd0: begin
-                    jog_valid <= 1'b1;
-                    phase <= 4'd1;
-                end
-                4'd1: phase <= 4'd2;
-                4'd2: begin
-                    if (jog_result_valid) begin
-                        assert(jog_accepted);
-                        phase <= 4'd3;
-                    end
-                end
-                4'd3: begin
-                    if (axis_active_mask[0] && step_out[0]) begin
-                        jog_dir <= 1'b1;
-                        jog_valid <= 1'b1;
-                        snapshot_valid <= 1'b1;
-                        phase <= 4'd4;
-                    end
-                end
-                4'd4: begin
-                    // An active axis and simultaneous snapshot traffic are not
-                    // JOG admission gates.
-                    assert(axis_active_mask[0]);
-                    phase <= 4'd5;
-                end
-                4'd5: begin
-                    if (jog_result_valid) begin
-                        assert(jog_accepted);
-                        replacement_wait <= 4'd0;
-                        phase <= 4'd6;
-                    end
-                end
-                4'd6: begin
-                    // The opposite DIR becoming visible proves the accepted
-                    // replacement reached the axis executor, not just the ACK.
-                    if (dir_out[0]) begin
-                        disabled <= 1'b1;
-                        phase <= 4'd7;
-                    end else begin
-                        assert(replacement_wait < 4'd8);
-                        replacement_wait <= replacement_wait + 4'd1;
-                    end
-                end
-                4'd7: begin
-                    if (disable_hard_stop_seen) phase <= 4'd8;
-                end
-                default: phase <= phase;
-            endcase
-
-            cover((phase == 4'd8) && disable_hard_stop_seen);
+        if (rst_n) begin
+            assert(started_a == started_b);
+            assert(step_a == step_b);
+            assert(dir_a == dir_b);
         end
         end
+        cover(rst_n && (legacy_gate_a != legacy_gate_b) && (|started_a));
     end
     end
 endmodule
 endmodule
 
 

+ 14 - 14
tests/formal/prod2u_p4_motor_hub_axis_isolation.sby

@@ -3,30 +3,30 @@ prove_isolation
 cover_isolation
 cover_isolation
 bmc_overlap
 bmc_overlap
 cover_overlap
 cover_overlap
-prove_hard_stop
-cover_hard_stop
+prove_reserved_axis
+cover_reserved_axis
 
 
 [options]
 [options]
 prove_isolation: mode prove
 prove_isolation: mode prove
-prove_isolation: depth 64
+prove_isolation: depth 48
 cover_isolation: mode cover
 cover_isolation: mode cover
-cover_isolation: depth 64
+cover_isolation: depth 48
 bmc_overlap: mode bmc
 bmc_overlap: mode bmc
-bmc_overlap: depth 96
+bmc_overlap: depth 48
 cover_overlap: mode cover
 cover_overlap: mode cover
-cover_overlap: depth 96
-prove_hard_stop: mode prove
-prove_hard_stop: depth 64
-cover_hard_stop: mode cover
-cover_hard_stop: depth 64
+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]
 [engines]
 prove_isolation: abc pdr
 prove_isolation: abc pdr
 cover_isolation: smtbmc yices
 cover_isolation: smtbmc yices
 bmc_overlap: smtbmc yices
 bmc_overlap: smtbmc yices
 cover_overlap: smtbmc yices
 cover_overlap: smtbmc yices
-prove_hard_stop: abc pdr
-cover_hard_stop: smtbmc yices
+prove_reserved_axis: abc pdr
+cover_reserved_axis: smtbmc yices
 
 
 [script]
 [script]
 read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_motor_hub.v prod2u_p4_motor_hub_axis_isolation_formal.v
 read_verilog -formal prod2u_p4_axis_executor.v prod2u_p4_motor_hub.v prod2u_p4_motor_hub_axis_isolation_formal.v
@@ -34,8 +34,8 @@ prove_isolation: prep -top prod2u_p4_motor_hub_axis_isolation_formal
 cover_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
 bmc_overlap: prep -top prod2u_p4_motor_hub_peer_overlap_formal
 cover_overlap: prep -top prod2u_p4_motor_hub_peer_overlap_formal
 cover_overlap: prep -top prod2u_p4_motor_hub_peer_overlap_formal
-prove_hard_stop: prep -top prod2u_p4_motor_hub_hard_stop_formal
-cover_hard_stop: prep -top prod2u_p4_motor_hub_hard_stop_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]
 [files]
 ../../src/rtl/prod2u_p4_axis_executor.v
 ../../src/rtl/prod2u_p4_axis_executor.v

+ 69 - 250
tests/formal/prod2u_p4_motor_hub_axis_isolation_formal.v

@@ -1,298 +1,117 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
 `default_nettype none
 `default_nettype none
 
 
-module prod2u_p4_motor_hub_formal_fixture (
-    input  wire        clk,
-    input  wire        rst_n,
-    input  wire        force_stop,
-    input  wire        disabled,
-    input  wire        watchdog_timeout,
-    input  wire        x_limit_raw,
-    input  wire        y_limit_raw,
-    input  wire        snapshot_valid,
-    input  wire [23:0] snapshot_targets,
-    input  wire [2:0]  snapshot_busy_at_accept,
-    input  wire        jog_valid,
-    input  wire [1:0]  jog_axis,
-    input  wire        jog_dir,
-    input  wire [1:0]  jog_speed_code,
-    input  wire [15:0] jog_steps,
-    output wire        snapshot_result_valid,
-    output wire [2:0]  snapshot_busy_mask,
-    output wire [2:0]  snapshot_invalid_mask,
-    output wire [2:0]  snapshot_accepted_mask,
-    output wire        jog_result_valid,
-    output wire        jog_accepted,
-    output wire [2:0]  axis_active_mask,
-    output wire [2:0]  axis_busy_mask,
-    output wire [2:0]  step_out,
-    output wire [2:0]  dir_out,
-    output wire        en_n,
-    output wire [79:0] status_payload
-);
-    prod2u_p4_motor_hub #(
-        .STANDARD_STEPS(4),
-        .LIMIT_CONFIRM_US(4),
-        .DIR_SETUP_US(2),
-        .SPEED0_HALF_US(2),
-        .SPEED1_HALF_US(2),
-        .SPEED2_HALF_US(2),
-        .SPEED3_HALF_US(2)
-    ) dut (
-        .clk(clk), .rst_n(rst_n), .tick_1us(1'b1),
-        .force_stop(force_stop), .disabled(disabled),
-        .watchdog_timeout(watchdog_timeout),
-        .x_limit_raw(x_limit_raw), .y_limit_raw(y_limit_raw),
-        .snapshot_valid(snapshot_valid),
-        .snapshot_targets(snapshot_targets),
-        .snapshot_busy_at_accept(snapshot_busy_at_accept),
-        .snapshot_result_valid(snapshot_result_valid),
-        .snapshot_busy_mask(snapshot_busy_mask),
-        .snapshot_invalid_mask(snapshot_invalid_mask),
-        .snapshot_accepted_mask(snapshot_accepted_mask),
-        .jog_valid(jog_valid), .jog_axis(jog_axis),
-        .jog_dir(jog_dir), .jog_speed_code(jog_speed_code),
-        .jog_steps(jog_steps), .jog_result_valid(jog_result_valid),
-        .jog_accepted(jog_accepted),
-        .axis_active_mask(axis_active_mask),
-        .axis_busy_mask(axis_busy_mask),
-        .step_out(step_out), .dir_out(dir_out), .en_n(en_n),
-        .status_payload(status_payload)
-    );
-endmodule
-
 module prod2u_p4_motor_hub_axis_isolation_formal;
 module prod2u_p4_motor_hub_axis_isolation_formal;
     (* gclk *) reg clk;
     (* gclk *) reg clk;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
-
-    (* anyseq *) reg x_jog_valid;
-    (* anyseq *) reg y_jog_valid;
+    (* anyseq *) reg jog_start;
+    (* anyseq *) reg [1:0] jog_axis;
     (* anyseq *) reg jog_dir;
     (* anyseq *) reg jog_dir;
-    (* anyseq *) reg [1:0] jog_speed;
     (* anyseq *) reg [15:0] jog_steps;
     (* anyseq *) reg [15:0] jog_steps;
-    (* anyseq *) reg x_limit_raw;
-    (* anyseq *) reg y_limit_raw;
 
 
-    wire [2:0] base_active;
-    wire [2:0] base_busy;
-    wire [2:0] base_step;
-    wire [2:0] base_dir;
-    wire [79:0] base_status;
-    wire [2:0] x_active;
-    wire [2:0] x_busy;
-    wire [2:0] x_step;
-    wire [2:0] x_dir;
-    wire [79:0] x_status;
-    wire [2:0] y_active;
-    wire [2:0] y_busy;
-    wire [2:0] y_step;
-    wire [2:0] y_dir;
-    wire [79:0] y_status;
+    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_formal_fixture base (
-        .clk(clk), .rst_n(rst_n), .force_stop(1'b0),
-        .disabled(1'b0), .watchdog_timeout(1'b0),
-        .x_limit_raw(x_limit_raw), .y_limit_raw(y_limit_raw),
-        .snapshot_valid(1'b0), .snapshot_targets(24'd0),
-        .snapshot_busy_at_accept(3'd0),
-        .jog_valid(1'b0), .jog_axis(2'd0), .jog_dir(jog_dir),
-        .jog_speed_code(jog_speed), .jog_steps(jog_steps),
-        .axis_active_mask(base_active), .axis_busy_mask(base_busy),
-        .step_out(base_step), .dir_out(base_dir),
-        .status_payload(base_status)
+    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_formal_fixture x_stimulus (
-        .clk(clk), .rst_n(rst_n), .force_stop(1'b0),
-        .disabled(1'b0), .watchdog_timeout(1'b0),
-        .x_limit_raw(x_limit_raw), .y_limit_raw(y_limit_raw),
-        .snapshot_valid(1'b0), .snapshot_targets(24'd0),
-        .snapshot_busy_at_accept(3'd0),
-        .jog_valid(x_jog_valid), .jog_axis(2'd0), .jog_dir(jog_dir),
-        .jog_speed_code(jog_speed), .jog_steps(jog_steps),
-        .axis_active_mask(x_active), .axis_busy_mask(x_busy),
-        .step_out(x_step), .dir_out(x_dir), .status_payload(x_status)
+    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_formal_fixture y_stimulus (
-        .clk(clk), .rst_n(rst_n), .force_stop(1'b0),
-        .disabled(1'b0), .watchdog_timeout(1'b0),
-        .x_limit_raw(x_limit_raw), .y_limit_raw(y_limit_raw),
-        .snapshot_valid(1'b0), .snapshot_targets(24'd0),
-        .snapshot_busy_at_accept(3'd0),
-        .jog_valid(y_jog_valid), .jog_axis(2'd1), .jog_dir(jog_dir),
-        .jog_speed_code(jog_speed), .jog_steps(jog_steps),
-        .axis_active_mask(y_active), .axis_busy_mask(y_busy),
-        .step_out(y_step), .dir_out(y_dir), .status_payload(y_status)
+    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
     always @(posedge clk) begin
         rst_n <= 1'b1;
         rst_n <= 1'b1;
-
         if (rst_n) begin
         if (rst_n) begin
-            // X-only traffic cannot alter any Y executor output or status.
-            assert(x_active[1] == base_active[1]);
-            assert(x_busy[1] == base_busy[1]);
-            assert(x_step[1] == base_step[1]);
-            assert(x_dir[1] == base_dir[1]);
-            assert(x_status[9] == base_status[9]);
-            assert(x_status[17] == base_status[17]);
-            assert(x_status[39:32] == base_status[39:32]);
-            assert(x_status[63:56] == base_status[63:56]);
-
-            // Y-only traffic has the symmetric non-interference guarantee.
-            assert(y_active[0] == base_active[0]);
-            assert(y_busy[0] == base_busy[0]);
-            assert(y_step[0] == base_step[0]);
-            assert(y_dir[0] == base_dir[0]);
-            assert(y_status[8] == base_status[8]);
-            assert(y_status[16] == base_status[16]);
-            assert(y_status[31:24] == base_status[31:24]);
-            assert(y_status[55:48] == base_status[55:48]);
+            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
         end
-
-        cover(rst_n && x_step[0] && !x_step[1]);
-        cover(rst_n && y_step[1] && !y_step[0]);
+        cover(rst_n && step_actual[0] && step_actual[1]);
     end
     end
 endmodule
 endmodule
 
 
 module prod2u_p4_motor_hub_peer_overlap_formal;
 module prod2u_p4_motor_hub_peer_overlap_formal;
     (* gclk *) reg clk;
     (* gclk *) reg clk;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
-    reg [2:0] phase = 3'd0;
-    reg jog_valid = 1'b0;
-    reg [1:0] jog_axis = 2'd0;
-    reg x_step_seen = 1'b0;
-    reg y_step_seen = 1'b0;
-    reg overlap_seen = 1'b0;
-    reg done = 1'b0;
-
-    wire jog_result_valid;
-    wire jog_accepted;
-    wire [2:0] axis_active;
-    wire [2:0] axis_busy;
+    (* 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] step_out;
+    wire [2:0] dir_out;
 
 
-    prod2u_p4_motor_hub_formal_fixture dut (
-        .clk(clk), .rst_n(rst_n), .force_stop(1'b0),
-        .disabled(1'b0), .watchdog_timeout(1'b0),
-        .x_limit_raw(1'b0), .y_limit_raw(1'b1),
-        .snapshot_valid(1'b0), .snapshot_targets(24'd0),
-        .snapshot_busy_at_accept(3'd0),
-        .jog_valid(jog_valid), .jog_axis(jog_axis), .jog_dir(1'b0),
-        .jog_speed_code(2'd3), .jog_steps(16'd4),
-        .jog_result_valid(jog_result_valid), .jog_accepted(jog_accepted),
-        .axis_active_mask(axis_active), .axis_busy_mask(axis_busy),
-        .step_out(step_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
     always @(posedge clk) begin
         rst_n <= 1'b1;
         rst_n <= 1'b1;
-        jog_valid <= 1'b0;
-
-        if (!rst_n) begin
-            phase <= 3'd0;
-            x_step_seen <= 1'b0;
-            y_step_seen <= 1'b0;
-            overlap_seen <= 1'b0;
-            done <= 1'b0;
-        end else begin
-            if (step_out[0]) x_step_seen <= 1'b1;
-            if (step_out[1]) y_step_seen <= 1'b1;
-            if (&axis_busy[1:0]) overlap_seen <= 1'b1;
-
-            assert(!step_out[0] || axis_busy[0]);
-            assert(!step_out[1] || axis_busy[1]);
-
-            case (phase)
-                3'd0: begin
-                    jog_axis <= 2'd0;
-                    jog_valid <= 1'b1;
-                    phase <= 3'd1;
-                end
-                3'd1: if (jog_result_valid) begin
-                    assert(jog_accepted);
-                    jog_axis <= 2'd1;
-                    jog_valid <= 1'b1;
-                    phase <= 3'd2;
-                end
-                3'd2: if (jog_result_valid) begin
-                    assert(jog_accepted);
-                    phase <= 3'd3;
-                end
-                3'd3: if (!axis_active[0] && !axis_active[1] &&
-                    x_step_seen && y_step_seen) begin
-                    assert(overlap_seen);
-                    done <= 1'b1;
-                    phase <= 3'd4;
-                end
-                default: begin
-                    assert(!axis_active[0]);
-                    assert(!axis_active[1]);
-                end
-            endcase
+        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
         end
-
-        cover(done && overlap_seen && x_step_seen && y_step_seen);
+        cover(rst_n && step_out[0] && step_out[1]);
     end
     end
 endmodule
 endmodule
 
 
-module prod2u_p4_motor_hub_hard_stop_formal;
+module prod2u_p4_motor_hub_reserved_axis_formal;
     (* gclk *) reg clk;
     (* gclk *) reg clk;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
-    reg past_valid = 1'b0;
-
-    (* anyseq *) reg force_stop;
-    (* anyseq *) reg disabled;
-    (* anyseq *) reg watchdog_timeout;
-    (* anyseq *) reg jog_valid;
+    (* anyseq *) reg jog_start;
     (* anyseq *) reg [1:0] jog_axis;
     (* anyseq *) reg [1:0] jog_axis;
     (* anyseq *) reg jog_dir;
     (* anyseq *) reg jog_dir;
     (* anyseq *) reg [15:0] jog_steps;
     (* anyseq *) reg [15:0] jog_steps;
-
-    wire [2:0] axis_active;
-    wire [2:0] axis_busy;
-    wire [2:0] step_out;
-    wire en_n;
-    wire [79:0] status_payload;
-    wire hard_stop = force_stop || disabled || watchdog_timeout;
-
-    prod2u_p4_motor_hub_formal_fixture dut (
-        .clk(clk), .rst_n(rst_n), .force_stop(force_stop),
-        .disabled(disabled), .watchdog_timeout(watchdog_timeout),
-        .x_limit_raw(1'b0), .y_limit_raw(1'b0),
-        .snapshot_valid(1'b0), .snapshot_targets(24'd0),
-        .snapshot_busy_at_accept(3'd0),
-        .jog_valid(jog_valid), .jog_axis(jog_axis), .jog_dir(jog_dir),
-        .jog_speed_code(2'd3), .jog_steps(jog_steps),
-        .axis_active_mask(axis_active), .axis_busy_mask(axis_busy),
-        .step_out(step_out), .en_n(en_n), .status_payload(status_payload)
+    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 @(*) begin
-        if (rst_n && hard_stop) begin
-            assert(step_out == 3'b000);
-            assert(en_n);
-            assert(axis_active == 3'b000);
-            assert(axis_busy == 3'b000);
-        end
-    end
 
 
     always @(posedge clk) begin
     always @(posedge clk) begin
         rst_n <= 1'b1;
         rst_n <= 1'b1;
-        past_valid <= rst_n;
-
+        if (jog_start) assume(jog_axis[1]);
         if (rst_n) begin
         if (rst_n) begin
-            assert(status_payload[2] == disabled);
-            assert(status_payload[3] == watchdog_timeout);
-            assert(status_payload[0] == (|axis_busy));
-            if (!hard_stop) assert(en_n == !(|axis_active));
+            assert(started_actual == started_reference);
+            assert(step_actual == step_reference);
+            assert(dir_actual == dir_reference);
         end
         end
-
-        cover(past_valid && $past(|step_out) && watchdog_timeout &&
-            (step_out == 3'b000) && en_n);
-        cover(past_valid && $past(|step_out) && disabled &&
-            (step_out == 3'b000) && en_n);
+        cover(rst_n && jog_start && jog_axis[1]);
     end
     end
 endmodule
 endmodule
 
 

+ 60 - 61
tests/formal/prod2u_p4_normal_v3_rx_formal.v

@@ -15,66 +15,49 @@ module prod2u_p4_normal_v3_rx_formal;
     wire [5:0] request_length;
     wire [5:0] request_length;
     wire [271:0] request_payload;
     wire [271:0] request_payload;
     wire [15:0] request_crc16;
     wire [15:0] request_crc16;
-    wire emergency_disable_valid;
-    wire [15:0] emergency_disable_crc16;
     wire [15:0] crc_error_count;
     wire [15:0] crc_error_count;
     wire [15:0] timeout_count;
     wire [15:0] timeout_count;
     wire [15:0] format_error_count;
     wire [15:0] format_error_count;
     (* anyconst *) reg [7:0] payload_low_bit;
     (* anyconst *) reg [7:0] payload_low_bit;
     (* anyconst *) reg [3:0] payload_high_bit;
     (* anyconst *) reg [3:0] payload_high_bit;
     reg past_valid = 1'b0;
     reg past_valid = 1'b0;
-    reg [6:0] driver_phase = 7'd0;
+    reg [5:0] driver_phase = 6'd0;
     reg held_request_seen = 1'b0;
     reg held_request_seen = 1'b0;
-    reg emergency_flush_seen = 1'b0;
+    reg handshake_seen = 1'b0;
+    reg recovery_seen = 1'b0;
 
 
-    // CRC-valid MOTION_CMD followed by HOST_CMD DISABLE while the request is held.
+    // CRC-valid MOTION_CMD, held for two clocks before it is retired.
     function [7:0] driver_byte;
     function [7:0] driver_byte;
-        input [6:0] index;
+        input [5:0] index;
         begin
         begin
             case (index)
             case (index)
-                7'd0: driver_byte = 8'ha5;
-                7'd1: driver_byte = 8'h5a;
-                7'd2: driver_byte = 8'h02;
-                7'd3: driver_byte = 8'h04;
-                7'd4: driver_byte = 8'h11;
-                7'd13: driver_byte = 8'h08;
-                7'd14: driver_byte = 8'h37;
-                7'd15: driver_byte = 8'h01;
-                7'd17: driver_byte = 8'h03;
-                7'd18: driver_byte = 8'ha0;
-                7'd22: driver_byte = 8'hf1;
-                7'd23: driver_byte = 8'hc3;
-                7'd25: driver_byte = 8'ha5;
-                7'd26: driver_byte = 8'h5a;
-                7'd27: driver_byte = 8'h02;
-                7'd28: driver_byte = 8'h04;
-                7'd29: driver_byte = 8'h05;
-                7'd38: driver_byte = 8'h04;
-                7'd39: driver_byte = 8'h26;
-                7'd43: driver_byte = 8'hc4;
-                7'd44: driver_byte = 8'hae;
+                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;
                 default: driver_byte = 8'h00;
             endcase
             endcase
         end
         end
     endfunction
     endfunction
 
 
 `ifdef PROD2U_P4_FORMAL_COVER_DRIVER
 `ifdef PROD2U_P4_FORMAL_COVER_DRIVER
-    assign rx_valid = rst_n && ((driver_phase < 7'd24) ||
-        (driver_phase >= 7'd25 && driver_phase < 7'd45));
+    assign rx_valid = rst_n && (driver_phase < 6'd24);
     assign rx_data = driver_byte(driver_phase);
     assign rx_data = driver_byte(driver_phase);
-    assign request_ready = 1'b0;
+    assign request_ready = driver_phase >= 6'd26;
 `else
 `else
     assign rx_valid = rx_valid_anyseq;
     assign rx_valid = rx_valid_anyseq;
     assign rx_data = rx_data_anyseq;
     assign rx_data = rx_data_anyseq;
     assign request_ready = request_ready_anyseq;
     assign request_ready = request_ready_anyseq;
 `endif
 `endif
 
 
-`ifdef PROD2U_P4_FORMAL_MUTATE_RX_READY_BACKPRESSURE
-    wire checked_rx_ready = request_valid ? 1'b0 : rx_ready;
-`else
-    wire checked_rx_ready = rx_ready;
-`endif
-
     prod2u_p4_normal_v3_rx #(
     prod2u_p4_normal_v3_rx #(
         .CLK_HZ(1000),
         .CLK_HZ(1000),
         .INTER_BYTE_TIMEOUT_MS(2)
         .INTER_BYTE_TIMEOUT_MS(2)
@@ -90,8 +73,6 @@ module prod2u_p4_normal_v3_rx_formal;
         .request_length(request_length),
         .request_length(request_length),
         .request_payload(request_payload),
         .request_payload(request_payload),
         .request_crc16(request_crc16),
         .request_crc16(request_crc16),
-        .emergency_disable_valid(emergency_disable_valid),
-        .emergency_disable_crc16(emergency_disable_crc16),
         .crc_error_count(crc_error_count),
         .crc_error_count(crc_error_count),
         .timeout_count(timeout_count),
         .timeout_count(timeout_count),
         .format_error_count(format_error_count)
         .format_error_count(format_error_count)
@@ -100,34 +81,37 @@ module prod2u_p4_normal_v3_rx_formal;
     always @(posedge clk) begin
     always @(posedge clk) begin
         past_valid <= 1'b1;
         past_valid <= 1'b1;
         rst_n <= 1'b1;
         rst_n <= 1'b1;
-        if (rx_valid) assume(rx_ready);
+
         if (!rst_n) begin
         if (!rst_n) begin
-            driver_phase <= 7'd0;
+            driver_phase <= 6'd0;
             held_request_seen <= 1'b0;
             held_request_seen <= 1'b0;
-            emergency_flush_seen <= 1'b0;
+            handshake_seen <= 1'b0;
+            recovery_seen <= 1'b0;
         end else begin
         end else begin
 `ifdef PROD2U_P4_FORMAL_COVER_DRIVER
 `ifdef PROD2U_P4_FORMAL_COVER_DRIVER
-            if (driver_phase < 7'd24) begin
-                driver_phase <= driver_phase + 7'd1;
-            end else if (driver_phase == 7'd24 && request_valid) begin
-                driver_phase <= 7'd25;
-            end else if (driver_phase >= 7'd25 && driver_phase < 7'd45) begin
-                driver_phase <= driver_phase + 7'd1;
+            if (driver_phase < 6'd28) begin
+                driver_phase <= driver_phase + 6'd1;
             end
             end
 `endif
 `endif
-            if (request_valid && !request_ready) held_request_seen <= 1'b1;
-            if (held_request_seen && emergency_disable_valid && !request_valid) begin
-                emergency_flush_seen <= 1'b1;
+            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
         end
         end
-        if (rst_n) assert(checked_rx_ready);
-        if (emergency_disable_valid) begin
-            assert(!request_valid);
+
+        if (rst_n) begin
+            assert(rx_ready == !request_valid);
         end
         end
-        if (past_valid && $past(request_valid && !request_ready)) begin
-            assert(checked_rx_ready);
-            if (!emergency_disable_valid) begin
+
+        if (past_valid && $past(rst_n)) begin
+            if ($past(request_valid && !request_ready)) begin
                 assert(request_valid);
                 assert(request_valid);
+                assert(!rx_ready);
                 assert(request_type == $past(request_type));
                 assert(request_type == $past(request_type));
                 assert(request_length == $past(request_length));
                 assert(request_length == $past(request_length));
                 assert(request_crc16 == $past(request_crc16));
                 assert(request_crc16 == $past(request_crc16));
@@ -135,14 +119,29 @@ module prod2u_p4_normal_v3_rx_formal;
                     $past(request_payload[payload_low_bit]));
                     $past(request_payload[payload_low_bit]));
                 assert(request_payload[9'd256 + payload_high_bit] ==
                 assert(request_payload[9'd256 + payload_high_bit] ==
                     $past(request_payload[9'd256 + payload_high_bit]));
                     $past(request_payload[9'd256 + payload_high_bit]));
-            end else begin
+                assert(crc_error_count == $past(crc_error_count));
+                assert(timeout_count == $past(timeout_count));
+                assert(format_error_count == $past(format_error_count));
+            end
+
+            if ($past(request_valid && request_ready)) begin
                 assert(!request_valid);
                 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]));
+                assert(crc_error_count == $past(crc_error_count));
+                assert(timeout_count == $past(timeout_count));
+                assert(format_error_count == $past(format_error_count));
             end
             end
         end
         end
 
 
-        cover(emergency_flush_seen);
+        cover(held_request_seen);
+        cover(handshake_seen);
+        cover(recovery_seen);
     end
     end
-
-    wire unused_counts = ^crc_error_count ^ ^timeout_count ^ ^format_error_count ^
-        emergency_disable_valid ^ ^emergency_disable_crc16;
 endmodule
 endmodule

+ 21 - 18
tests/formal/prod2u_p4_normal_v3_rx_payload_formal.v

@@ -6,6 +6,7 @@ module prod2u_p4_normal_v3_rx_payload_formal;
     reg [6:0] frame_index = 7'd0;
     reg [6:0] frame_index = 7'd0;
     reg request_seen = 1'b0;
     reg request_seen = 1'b0;
     reg [15:0] harness_crc = 16'hffff;
     reg [15:0] harness_crc = 16'hffff;
+    reg [271:0] expected_payload = 272'd0;
     (* anyconst *) reg [1:0] command_kind;
     (* anyconst *) reg [1:0] command_kind;
     (* anyseq *) reg [7:0] payload_byte;
     (* anyseq *) reg [7:0] payload_byte;
 
 
@@ -24,8 +25,6 @@ module prod2u_p4_normal_v3_rx_payload_formal;
     wire [5:0] request_length;
     wire [5:0] request_length;
     wire [271:0] request_payload;
     wire [271:0] request_payload;
     wire [15:0] request_crc16;
     wire [15:0] request_crc16;
-    wire emergency_disable_valid;
-    wire [15:0] emergency_disable_crc16;
     wire [15:0] crc_error_count;
     wire [15:0] crc_error_count;
     wire [15:0] timeout_count;
     wire [15:0] timeout_count;
     wire [15:0] format_error_count;
     wire [15:0] format_error_count;
@@ -52,8 +51,6 @@ module prod2u_p4_normal_v3_rx_payload_formal;
         .request_length(request_length),
         .request_length(request_length),
         .request_payload(request_payload),
         .request_payload(request_payload),
         .request_crc16(request_crc16),
         .request_crc16(request_crc16),
-        .emergency_disable_valid(emergency_disable_valid),
-        .emergency_disable_crc16(emergency_disable_crc16),
         .crc_error_count(crc_error_count),
         .crc_error_count(crc_error_count),
         .timeout_count(timeout_count),
         .timeout_count(timeout_count),
         .format_error_count(format_error_count)
         .format_error_count(format_error_count)
@@ -75,7 +72,11 @@ module prod2u_p4_normal_v3_rx_payload_formal;
         end else if (frame_index == 7'd13) begin
         end else if (frame_index == 7'd13) begin
             drive_data = {2'd0, selected_length};
             drive_data = {2'd0, selected_length};
         end else if (frame_index < crc_low_index) begin
         end else if (frame_index < crc_low_index) begin
-            drive_data = payload_byte;
+            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
         end else if (frame_index == crc_low_index) begin
             drive_data = harness_crc[7:0];
             drive_data = harness_crc[7:0];
         end else begin
         end else begin
@@ -86,10 +87,12 @@ module prod2u_p4_normal_v3_rx_payload_formal;
     always @(posedge clk) begin
     always @(posedge clk) begin
         assume(command_kind < 2'd3);
         assume(command_kind < 2'd3);
         rst_n <= 1'b1;
         rst_n <= 1'b1;
+
         if (!rst_n) begin
         if (!rst_n) begin
             frame_index <= 7'd0;
             frame_index <= 7'd0;
             request_seen <= 1'b0;
             request_seen <= 1'b0;
             harness_crc <= 16'hffff;
             harness_crc <= 16'hffff;
+            expected_payload <= 272'd0;
         end else begin
         end else begin
             if (drive_valid) begin
             if (drive_valid) begin
                 assert(rx_ready);
                 assert(rx_ready);
@@ -97,31 +100,31 @@ module prod2u_p4_normal_v3_rx_payload_formal;
                 if (frame_index >= 7'd2 && frame_index < crc_low_index) begin
                 if (frame_index >= 7'd2 && frame_index < crc_low_index) begin
                     harness_crc <= harness_crc_next;
                     harness_crc <= harness_crc_next;
                 end
                 end
+                if (frame_index >= 7'd14 && frame_index < crc_low_index) begin
+                    expected_payload[(frame_index - 7'd14) * 8 +: 8] <=
+                        drive_data;
+                end
             end
             end
+
             if (request_valid) begin
             if (request_valid) begin
                 request_seen <= 1'b1;
                 request_seen <= 1'b1;
                 assert(request_type == selected_type);
                 assert(request_type == selected_type);
                 assert(request_length == selected_length);
                 assert(request_length == selected_length);
                 assert(request_crc16 == harness_crc);
                 assert(request_crc16 == harness_crc);
-                if (selected_length == 6'd4) begin
-                    assert(request_payload[271:32] == 240'd0);
+                assert(request_payload == expected_payload);
+                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
-                if (selected_length == 6'd8) begin
-                    assert(request_payload[271:64] == 208'd0);
-                end
-            end
-            if (emergency_disable_valid) begin
-                request_seen <= 1'b1;
-                assert(selected_type == 8'h05);
-                assert(selected_length == 6'd4);
-                assert(emergency_disable_crc16 == harness_crc);
             end
             end
+
             if (frame_index >= (crc_high_index + 7'd2)) begin
             if (frame_index >= (crc_high_index + 7'd2)) begin
                 assert(request_seen);
                 assert(request_seen);
             end
             end
         end
         end
     end
     end
 
 
-    wire unused_counts = ^crc_error_count ^ ^timeout_count ^ ^format_error_count ^
-        emergency_disable_valid;
+    wire unused_request = request_seen;
 endmodule
 endmodule

+ 231 - 259
tests/sim/prod2u_p4_axis_force_jog_v1_tb.v

@@ -1,343 +1,315 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
 
 
 module prod2u_p4_axis_force_jog_v1_tb;
 module prod2u_p4_axis_force_jog_v1_tb;
-    localparam integer DIR_SETUP_TICKS = 4;
-    localparam integer HALF_PERIOD_TICKS = 4;
+    localparam integer DIR_SETUP_CYCLES = 3;
+    localparam integer STEP_HALF_CYCLES = 2;
 
 
-    reg clk;
-    reg rst_n;
-    reg force_stop;
-    reg limit_raw;
-    reg jog_start;
-    reg jog_dir;
-    reg [1:0] jog_speed_code;
-    reg [15:0] jog_steps;
-    reg standard_start;
-    reg standard_target_open;
+    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 step_out;
     wire dir_out;
     wire dir_out;
-    wire busy;
-    wire drive_active;
-    wire position_valid;
-    wire [7:0] current_aperture;
-    wire [7:0] target_aperture;
-    wire [15:0] remaining_steps = dut.remaining_steps_reg;
+    wire started_pulse;
 
 
-    integer failures;
-    integer rise_total;
-    integer fall_total;
-    integer short_high_pulses;
-    integer high_age;
-    reg previous_step;
+    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 #(
     prod2u_p4_axis_executor #(
-        .STANDARD_STEPS(6),
-        .LIMIT_CONFIRM_US(5),
-        .DIR_SETUP_US(DIR_SETUP_TICKS),
-        .SPEED0_HALF_US(HALF_PERIOD_TICKS),
-        .SPEED1_HALF_US(HALF_PERIOD_TICKS),
-        .SPEED2_HALF_US(HALF_PERIOD_TICKS),
-        .SPEED3_HALF_US(HALF_PERIOD_TICKS)
+        .DIR_SETUP_CYCLES(DIR_SETUP_CYCLES),
+        .STEP_HALF_CYCLES(STEP_HALF_CYCLES)
     ) dut (
     ) dut (
         .clk(clk),
         .clk(clk),
         .rst_n(rst_n),
         .rst_n(rst_n),
-        .tick_1us(1'b1),
-        .force_stop(force_stop),
-        .limit_raw(limit_raw),
-        .jog_start(jog_start),
-        .jog_dir(jog_dir),
-        .jog_speed_code(jog_speed_code),
-        .jog_steps(jog_steps),
-        .standard_start(standard_start),
-        .standard_target_open(standard_target_open),
+        .command_start(command_start),
+        .command_dir(command_dir),
+        .command_steps(command_steps),
         .step_out(step_out),
         .step_out(step_out),
         .dir_out(dir_out),
         .dir_out(dir_out),
-        .busy(busy),
-        .drive_active(drive_active),
-        .position_valid(position_valid),
-        .current_aperture(current_aperture),
-        .target_aperture(target_aperture)
+        .started_pulse(started_pulse)
     );
     );
 
 
-    initial begin
-        clk = 1'b0;
-        forever #5 clk = ~clk;
-    end
+    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
     always @(posedge clk) begin
         #1;
         #1;
-        if (!previous_step && step_out) begin
-            rise_total = rise_total + 1;
-            high_age = 1;
-            if (!busy) begin
-                failures = failures + 1;
-                $display("RED: STEP rise did not assert reported busy");
+        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
             end
-        end else if (step_out) begin
-            high_age = high_age + 1;
-        end
-        if (previous_step && !step_out) begin
-            fall_total = fall_total + 1;
-            if (!force_stop && drive_active &&
-                (high_age < HALF_PERIOD_TICKS)) begin
-                short_high_pulses = short_high_pulses + 1;
-                $display("RED: replacement truncated STEP high width=%0d", high_age);
+
+            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
-            high_age = 0;
         end
         end
+
         previous_step = step_out;
         previous_step = step_out;
     end
     end
 
 
     task reset_axis;
     task reset_axis;
         begin
         begin
             rst_n = 1'b0;
             rst_n = 1'b0;
-            force_stop = 1'b0;
-            limit_raw = 1'b0;
-            jog_start = 1'b0;
-            jog_dir = 1'b0;
-            jog_speed_code = 2'd3;
-            jog_steps = 16'd1;
-            standard_start = 1'b0;
-            standard_target_open = 1'b0;
-            rise_total = 0;
-            fall_total = 0;
-            short_high_pulses = 0;
-            high_age = 0;
+            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;
             previous_step = 1'b0;
-            repeat (4) @(negedge clk);
+            check_widths = 1'b1;
+            repeat (3) @(negedge clk);
             rst_n = 1'b1;
             rst_n = 1'b1;
-            repeat (2) @(posedge clk);
+            repeat (2) @(negedge clk);
+            if (step_out || started_pulse) begin
+                fail("reset did not leave STEP and started_pulse low");
+            end
         end
         end
     endtask
     endtask
 
 
-    task pulse_jog;
+    task issue_command;
         input direction;
         input direction;
         input [15:0] steps;
         input [15:0] steps;
         begin
         begin
             @(negedge clk);
             @(negedge clk);
-            jog_dir = direction;
-            jog_steps = steps;
-            jog_start = 1'b1;
-            @(negedge clk);
-            jog_start = 1'b0;
-        end
-    endtask
-
-    task pulse_standard;
-        input target_open;
-        begin
-            @(negedge clk);
-            standard_target_open = target_open;
-            standard_start = 1'b1;
+            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);
             @(negedge clk);
-            standard_start = 1'b0;
+            command_start = 1'b0;
         end
         end
     endtask
     endtask
 
 
-    task wait_for_phase;
-        input [2:0] expected_phase;
+    task wait_for_rises;
+        input integer expected;
         input integer maximum_cycles;
         input integer maximum_cycles;
-        integer guard;
         begin
         begin
             guard = 0;
             guard = 0;
-            while ((dut.motion_phase != expected_phase) &&
-                   (guard < maximum_cycles)) begin
+            while ((rise_count < expected) && (guard < maximum_cycles)) begin
                 @(negedge clk);
                 @(negedge clk);
                 guard = guard + 1;
                 guard = guard + 1;
             end
             end
-            if (guard >= maximum_cycles) begin
-                failures = failures + 1;
-                $display("RED: phase %0d not reached, current=%0d",
-                    expected_phase, dut.motion_phase);
+            if (rise_count != expected) begin
+                fail("command did not produce the requested STEP rises");
             end
             end
         end
         end
     endtask
     endtask
 
 
-    task wait_for_idle;
-        input integer maximum_cycles;
-        integer guard;
+    task run_exact_count;
+        input direction;
+        input [15:0] steps;
+        integer first_rise_cycle;
         begin
         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;
             guard = 0;
-            while (drive_active && (guard < maximum_cycles)) begin
-                @(posedge clk);
-                #1;
+            while ((fall_count < steps) && (guard < STEP_HALF_CYCLES + 8)) begin
+                @(negedge clk);
                 guard = guard + 1;
                 guard = guard + 1;
             end
             end
-            if (drive_active || busy || step_out ||
-                (guard >= maximum_cycles)) begin
-                failures = failures + 1;
-                $display("RED: axis did not retire drive=%0d busy=%0d step=%0d phase=%0d",
-                    drive_active, busy, step_out, dut.motion_phase);
-            end
-        end
-    endtask
-
-    task expect_setup_not_busy;
-        input integer case_id;
-        begin
-            #1;
-            if (!drive_active || busy || step_out) begin
-                failures = failures + 1;
-                $display("RED case %0d: setup visibility drive=%0d busy=%0d step=%0d",
-                    case_id, drive_active, busy, step_out);
+            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
         end
         end
     endtask
     endtask
 
 
-    integer before_rises;
-    integer setup_ticks;
-    reg old_dir;
-
     initial begin
     initial begin
-        failures = 0;
-        reset_axis();
-
-        // A JOG received during DIR setup replaces immediately. No STEP from
-        // the superseded standard command may escape, and setup is not busy.
-        pulse_standard(1'b1);
-        expect_setup_not_busy(1);
-        repeat (2) @(posedge clk);
-        pulse_jog(1'b1, 16'd3);
-        expect_setup_not_busy(1);
-        if (dir_out !== 1'b1 || remaining_steps !== 16'd3) begin
-            failures = failures + 1;
-            $display("RED case 1: setup replacement dir=%0d remaining=%0d",
-                dir_out, remaining_steps);
-        end
-        wait_for_idle(200);
-        if (rise_total != 3 || fall_total != 3 || short_high_pulses != 0) begin
-            failures = failures + 1;
-            $display("RED case 1: setup replacement rises=%0d falls=%0d short=%0d",
-                rise_total, fall_total, short_high_pulses);
-        end
+        // 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);
 
 
-        // Replacement during STEP_HIGH must finish that pulse and its low
-        // phase before changing DIR. The replacement then waits full setup.
+        // A setup-phase replacement restarts setup and suppresses the old move.
         reset_axis();
         reset_axis();
-        pulse_standard(1'b1);
-        wait_for_phase(3'd2, 64);
-        old_dir = dir_out;
-        before_rises = rise_total;
-        pulse_jog(1'b1, 16'd3);
-        if (!step_out || dir_out !== old_dir || !busy) begin
-            failures = failures + 1;
-            $display("RED case 2: high-phase replacement changed early step=%0d dir=%0d busy=%0d",
-                step_out, dir_out, busy);
-        end
-        wait_for_phase(3'd1, 64);
-        if (step_out || busy || !drive_active || dir_out !== 1'b1 ||
-            remaining_steps !== 16'd3) begin
-            failures = failures + 1;
-            $display("RED case 2: replacement boundary step=%0d busy=%0d drive=%0d dir=%0d remaining=%0d",
-                step_out, busy, drive_active, dir_out, remaining_steps);
-        end
-        setup_ticks = 0;
-        while (!step_out && drive_active && setup_ticks < 32) begin
-            @(posedge clk);
-            #1;
-            setup_ticks = setup_ticks + 1;
-        end
-        if (!step_out || setup_ticks < DIR_SETUP_TICKS || !busy) begin
-            failures = failures + 1;
-            $display("RED case 2: replacement setup ticks=%0d step=%0d busy=%0d",
-                setup_ticks, step_out, busy);
-        end
-        wait_for_idle(200);
-        if (rise_total != (before_rises + 3) || fall_total != rise_total ||
-            short_high_pulses != 0 || position_valid ||
-            current_aperture !== 8'hff || target_aperture !== 8'hff) begin
-            failures = failures + 1;
-            $display("RED case 2: high replacement rises=%0d expected=%0d falls=%0d short=%0d status=%0h/%0h/%0d",
-                rise_total, before_rises + 3, fall_total, short_high_pulses,
-                current_aperture, target_aperture, position_valid);
+        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
         end
 
 
-        // A low-phase replacement waits for the full low tail, then reloads.
+        // A high-phase replacement has absolute priority: STEP goes low on the
+        // acceptance edge, then the replacement waits a fresh setup interval.
         reset_axis();
         reset_axis();
-        pulse_jog(1'b0, 16'd5);
-        wait_for_phase(3'd3, 64);
-        old_dir = dir_out;
-        pulse_jog(1'b1, 16'd2);
-        if (dir_out !== old_dir || !busy || !drive_active || step_out) begin
-            failures = failures + 1;
-            $display("RED case 3: low-phase replacement changed before tail");
+        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
         end
-        wait_for_phase(3'd1, 64);
-        if (dir_out !== 1'b1 || busy || !drive_active ||
-            remaining_steps !== 16'd2) begin
-            failures = failures + 1;
-            $display("RED case 3: low replacement boundary dir=%0d busy=%0d remaining=%0d",
-                dir_out, busy, remaining_steps);
-        end
-        wait_for_idle(200);
-        if (rise_total != 3 || fall_total != 3 || short_high_pulses != 0) begin
-            failures = failures + 1;
-            $display("RED case 3: low replacement rises=%0d falls=%0d short=%0d",
-                rise_total, fall_total, short_high_pulses);
+        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
         end
 
 
-        // Multiple JOGs received before the safe boundary are acknowledged by
-        // the caller but only the last request is executed after the old STEP.
+        // A low-phase replacement also starts a fresh setup and discards tail.
         reset_axis();
         reset_axis();
-        pulse_standard(1'b0);
-        wait_for_phase(3'd2, 64);
-        pulse_jog(1'b0, 16'd7);
-        pulse_jog(1'b1, 16'd2);
-        wait_for_phase(3'd1, 64);
-        if (dir_out !== 1'b1 || remaining_steps !== 16'd2 || busy) begin
-            failures = failures + 1;
-            $display("RED case 4: latest-wins dir=%0d remaining=%0d busy=%0d",
-                dir_out, remaining_steps, busy);
-        end
-        wait_for_idle(200);
-        if (rise_total != 3 || fall_total != 3 || short_high_pulses != 0) begin
-            failures = failures + 1;
-            $display("RED case 4: latest-wins rises=%0d falls=%0d short=%0d",
-                rise_total, fall_total, short_high_pulses);
+        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
         end
 
 
-        // LS is deliberately irrelevant in the force-motion image.
+        // 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();
         reset_axis();
-        limit_raw = 1'b1;
-        pulse_jog(1'b1, 16'd5);
-        repeat (20) begin
-            @(negedge clk);
-            limit_raw = ~limit_raw;
-        end
-        wait_for_idle(200);
-        if (rise_total != 5 || fall_total != 5) begin
-            failures = failures + 1;
-            $display("RED case 5: LS changed force JOG rises=%0d falls=%0d",
-                rise_total, fall_total);
+        @(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
         end
+        @(negedge clk);
+        prod_command_start = 1'b0;
 
 
-        // Hard stop is the only path allowed to truncate a STEP. Pins and
-        // reported busy must gate low without waiting for the next clock.
-        reset_axis();
-        pulse_jog(1'b1, 16'd8);
-        wait_for_phase(3'd2, 64);
-        #1 force_stop = 1'b1;
+        @(posedge prod_step_out);
+        prod_first_rise_time = $time;
         #1;
         #1;
-        if (step_out || drive_active || busy) begin
-            failures = failures + 1;
-            $display("RED case 6: hard stop did not gate pins/busy immediately step=%0d drive=%0d busy=%0d",
-                step_out, drive_active, busy);
+        if (!prod_started_pulse) begin
+            fail("production first STEP rise lacked started_pulse");
         end
         end
-        @(posedge clk);
+        @(negedge prod_step_out);
+        prod_first_fall_time = $time;
+        @(posedge prod_step_out);
+        prod_second_rise_time = $time;
         #1;
         #1;
-        force_stop = 1'b0;
-        repeat (12) @(posedge clk);
-        if (step_out || drive_active || busy || position_valid ||
-            current_aperture !== 8'hff || target_aperture !== 8'hff) begin
-            failures = failures + 1;
-            $display("RED case 6: hard-stop state survived step=%0d drive=%0d busy=%0d",
-                step_out, drive_active, busy);
+        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
         end
 
 
         if (failures != 0) begin
         if (failures != 0) begin
-            $display("AXIS_FORCE_JOG_V1_RED failures=%0d", failures);
-            $fatal(1);
+            $fatal(1, "prod2u_p4_axis_force_jog_v1_tb failures=%0d", failures);
         end
         end
 
 
         $display("PASS: prod2u_p4_axis_force_jog_v1_tb");
         $display("PASS: prod2u_p4_axis_force_jog_v1_tb");

+ 37 - 103
tests/sim/prod2u_p4_axis_jog_16bit_tb.v

@@ -1,121 +1,55 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
 
 
 module prod2u_p4_axis_jog_16bit_tb;
 module prod2u_p4_axis_jog_16bit_tb;
-    reg clk;
-    reg rst_n;
-    reg limit_raw;
-    reg jog_start;
-    reg jog_dir;
-    reg [15:0] jog_steps;
+    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 step_out;
-    wire busy;
-    wire drive_active;
-    wire [15:0] remaining_steps = dut.remaining_steps_reg;
-
-    integer guard;
-    integer rises;
-    reg previous_step;
+    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 #(
     prod2u_p4_axis_executor #(
-        .STANDARD_STEPS(4),
-        .DIR_SETUP_US(1),
-        .SPEED0_HALF_US(1),
-        .SPEED1_HALF_US(1),
-        .SPEED2_HALF_US(1),
-        .SPEED3_HALF_US(1)
+        .DIR_SETUP_CYCLES(1),
+        .STEP_HALF_CYCLES(1)
     ) dut (
     ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .tick_1us(1'b1),
-        .force_stop(1'b0),
-        .limit_raw(limit_raw),
-        .jog_start(jog_start),
-        .jog_dir(jog_dir),
-        .jog_speed_code(2'd3),
-        .jog_steps(jog_steps),
-        .standard_start(1'b0),
-        .standard_target_open(1'b0),
-        .step_out(step_out),
-        .dir_out(),
-        .busy(busy),
-        .drive_active(drive_active),
-        .position_valid(),
-        .current_aperture(),
-        .target_aperture()
+        .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
     initial begin
-        clk = 1'b0;
-        forever #5 clk = ~clk;
-    end
+        repeat (3) @(negedge clk);
+        rst_n = 1'b1;
+        @(negedge clk);
+        command_dir = 1'b1;
+        command_start = 1'b1;
+        @(negedge clk);
+        command_start = 1'b0;
 
 
-    task run_clamped_jog;
-        input [15:0] requested;
-        input [15:0] expected;
-        begin
-            @(negedge clk);
-            jog_dir = ~jog_dir;
-            jog_steps = requested;
-            jog_start = 1'b1;
-            @(posedge clk);
-            #1;
-            if (busy || !drive_active || step_out ||
-                remaining_steps !== expected) begin
-                $display("force JOG load mismatch requested=%0d expected=%0d busy=%0d drive=%0d step=%0d remaining=%0d",
-                    requested, expected, busy, drive_active, step_out,
-                    remaining_steps);
-                $fatal;
-            end
+        while ((rises < 65535) && (guard < 140000)) begin
             @(negedge clk);
             @(negedge clk);
-            jog_start = 1'b0;
-
-            guard = 0;
-            rises = 0;
-            previous_step = step_out;
-            while (drive_active && guard < (expected * 4 + 64)) begin
-                @(posedge clk);
-                #1;
-                if (!previous_step && step_out) begin
-                    rises = rises + 1;
-                    if (!busy) begin
-                        $display("force JOG rise without reported busy requested=%0d rise=%0d",
-                            requested, rises);
-                        $fatal;
-                    end
-                end
-                if ((rises == 0) && busy) begin
-                    $display("force JOG reported busy before first STEP requested=%0d",
-                        requested);
-                    $fatal;
-                end
-                if ((guard % 7) == 0) limit_raw = ~limit_raw;
-                previous_step = step_out;
-                guard = guard + 1;
-            end
-            if (busy || drive_active || step_out || rises != expected) begin
-                $display("force JOG count mismatch requested=%0d expected=%0d rises=%0d busy=%0d remaining=%0d",
-                    requested, expected, rises, busy, remaining_steps);
-                $fatal;
-            end
+            guard = guard + 1;
         end
         end
-    endtask
-
-    initial begin
-        rst_n = 1'b0;
-        limit_raw = 1'b1;
-        jog_start = 1'b0;
-        jog_dir = 1'b0;
-        jog_steps = 16'd1;
         repeat (4) @(negedge clk);
         repeat (4) @(negedge clk);
-        rst_n = 1'b1;
-
-        run_clamped_jog(16'd1, 16'd1);
-        run_clamped_jog(16'd799, 16'd799);
-        run_clamped_jog(16'd800, 16'd800);
-        run_clamped_jog(16'd801, 16'd800);
-        run_clamped_jog(16'd8191, 16'd800);
-        run_clamped_jog(16'd65535, 16'd800);
 
 
+        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");
         $display("PASS: prod2u_p4_axis_jog_16bit_tb");
         $finish;
         $finish;
     end
     end

+ 0 - 214
tests/sim/prod2u_p4_axis_minimal_standard_tb.v

@@ -1,214 +0,0 @@
-`timescale 1ns/1ps
-
-module prod2u_p4_axis_minimal_standard_tb;
-    localparam integer STANDARD_STEPS = 3200;
-
-    reg clk;
-    reg rst_n;
-    reg force_stop;
-    reg standard_start;
-    reg standard_target_open;
-    reg limit_raw;
-
-    wire step_out;
-    wire dir_out;
-    wire busy;
-    wire drive_active;
-    wire position_valid;
-    wire [7:0] current_aperture;
-    wire [7:0] target_aperture;
-
-    integer failures;
-    integer guard;
-    integer rises;
-    reg previous_step;
-
-    prod2u_p4_axis_executor #(
-        .STANDARD_STEPS(STANDARD_STEPS),
-        .LIMIT_CONFIRM_US(1000),
-        .DIR_SETUP_US(4),
-        .SPEED0_HALF_US(1),
-        .SPEED1_HALF_US(1),
-        .SPEED2_HALF_US(1),
-        .SPEED3_HALF_US(1)
-    ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .tick_1us(1'b1),
-        .force_stop(force_stop),
-        .limit_raw(limit_raw),
-        .jog_start(1'b0),
-        .jog_dir(1'b0),
-        .jog_speed_code(2'd3),
-        .jog_steps(16'd1),
-        .standard_start(standard_start),
-        .standard_target_open(standard_target_open),
-        .step_out(step_out),
-        .dir_out(dir_out),
-        .busy(busy),
-        .drive_active(drive_active),
-        .position_valid(position_valid),
-        .current_aperture(current_aperture),
-        .target_aperture(target_aperture)
-    );
-
-    initial begin
-        clk = 1'b0;
-        forever #5 clk = ~clk;
-    end
-
-    task reset_axis_with_limit_high;
-        begin
-            rst_n = 1'b0;
-            force_stop = 1'b0;
-            standard_start = 1'b0;
-            standard_target_open = 1'b0;
-            limit_raw = 1'b1;
-            repeat (4) @(negedge clk);
-            rst_n = 1'b1;
-            repeat (2) @(posedge clk);
-        end
-    endtask
-
-    task run_standard;
-        input target_open;
-        input expected_dir;
-        input [7:0] expected_aperture;
-        input integer case_id;
-        input toggle_limit_mid_motion;
-        begin
-            @(negedge clk);
-            standard_target_open = target_open;
-            standard_start = 1'b1;
-            @(posedge clk);
-            #1;
-            if (!drive_active || busy || step_out) begin
-                failures = failures + 1;
-                $display("RED case %0d: standard setup drive=%0d busy=%0d step=%0d",
-                    case_id, drive_active, busy, step_out);
-            end
-            if (drive_active && dir_out !== expected_dir) begin
-                failures = failures + 1;
-                $display("RED case %0d: DIR=%0d expected=%0d", case_id,
-                    dir_out, expected_dir);
-            end
-            @(negedge clk);
-            standard_start = 1'b0;
-
-            rises = 0;
-            guard = 0;
-            previous_step = step_out;
-            while (drive_active && guard < 12000) begin
-                @(posedge clk);
-                #1;
-                if (toggle_limit_mid_motion && (guard == 100)) begin
-                    limit_raw = 1'b1;
-                end
-                if (toggle_limit_mid_motion && (guard == 300)) begin
-                    limit_raw = 1'b0;
-                end
-                if (!previous_step && step_out) rises = rises + 1;
-                previous_step = step_out;
-                guard = guard + 1;
-            end
-            if (busy || drive_active || step_out ||
-                guard >= 12000) begin
-                failures = failures + 1;
-                $display("RED case %0d: standard command did not settle", case_id);
-            end
-            if (rises != STANDARD_STEPS) begin
-                failures = failures + 1;
-                $display("RED case %0d: standard rises=%0d expected=%0d",
-                    case_id, rises, STANDARD_STEPS);
-            end
-            if (!position_valid || current_aperture !== expected_aperture ||
-                target_aperture !== expected_aperture) begin
-                failures = failures + 1;
-                $display("RED case %0d: completion status valid=%0d current=%0h target=%0h",
-                    case_id, position_valid, current_aperture, target_aperture);
-            end
-        end
-    endtask
-
-    initial begin
-        failures = 0;
-        rst_n = 1'b0;
-        force_stop = 1'b0;
-        standard_start = 1'b0;
-        standard_target_open = 1'b0;
-        limit_raw = 1'b0;
-
-        // Standard motion is a fixed mechanical command. A high close-limit
-        // input must not shorten or reject either direction.
-        reset_axis_with_limit_high();
-        run_standard(1'b1, 1'b0, 8'd100, 1, 1'b0);
-
-        // Repeating the same target is another complete 3200-step command.
-        run_standard(1'b1, 1'b0, 8'd100, 2, 1'b0);
-
-        reset_axis_with_limit_high();
-        run_standard(1'b0, 1'b1, 8'd0, 3, 1'b0);
-
-        // Repeating CLOSE is also a fresh fixed-length command.
-        run_standard(1'b0, 1'b1, 8'd0, 4, 1'b0);
-
-        // A permanently low limit and arbitrary changes during either
-        // standard direction must not affect the exact 3200-step count.
-        reset_axis_with_limit_high();
-        limit_raw = 1'b0;
-        run_standard(1'b1, 1'b0, 8'd100, 5, 1'b0);
-        run_standard(1'b0, 1'b1, 8'd0, 6, 1'b0);
-        run_standard(1'b1, 1'b0, 8'd100, 7, 1'b1);
-        run_standard(1'b0, 1'b1, 8'd0, 8, 1'b1);
-
-        // A hard stop is the exceptional path that may truncate STEP. It must
-        // immediately gate the pins and invalidate a previously completed
-        // command position on the next active clock edge.
-        reset_axis_with_limit_high();
-        run_standard(1'b1, 1'b0, 8'd100, 9, 1'b0);
-        if (!position_valid) begin
-            failures = failures + 1;
-            $display("RED case 5: hard-stop setup has no valid position");
-        end
-        @(negedge clk);
-        standard_target_open = 1'b0;
-        standard_start = 1'b1;
-        @(negedge clk);
-        standard_start = 1'b0;
-        guard = 0;
-        while (!step_out && drive_active && guard < 5000) begin
-            @(posedge clk);
-            #1;
-            guard = guard + 1;
-        end
-        if (!step_out) begin
-            failures = failures + 1;
-            $display("RED case 5: hard-stop setup emitted no STEP");
-        end else begin
-            #1 force_stop = 1'b1;
-            #1;
-            if (step_out || drive_active) begin
-                failures = failures + 1;
-                $display("RED case 5: hard stop did not gate STEP/drive immediately");
-            end
-            @(posedge clk);
-            #1;
-            if (busy || drive_active || step_out || position_valid ||
-                current_aperture !== 8'hff ||
-                target_aperture !== 8'hff) begin
-                failures = failures + 1;
-                $display("RED case 5: hard stop retained busy=%0d drive=%0d valid=%0d current=%0h target=%0h",
-                    busy, drive_active, position_valid, current_aperture,
-                    target_aperture);
-            end
-        end
-
-        if (failures != 0) begin
-            $display("AXIS_MINIMAL_STANDARD_RED failures=%0d", failures);
-            $fatal(1);
-        end
-
-        $display("PASS: prod2u_p4_axis_minimal_standard_tb");
-        $finish;
-    end
-endmodule

+ 35 - 52
tests/sim/prod2u_p4_cdc_sync_depth_tb.v

@@ -3,70 +3,53 @@
 module prod2u_p4_cdc_sync_depth_tb;
 module prod2u_p4_cdc_sync_depth_tb;
     reg clk = 1'b0;
     reg clk = 1'b0;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
-    reg limit_raw = 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 #5 clk = ~clk;
+    always @(posedge step_out) rises = rises + 1;
 
 
     prod2u_p4_axis_executor #(
     prod2u_p4_axis_executor #(
-        .STANDARD_STEPS(4),
-        .LIMIT_CONFIRM_US(8),
-        .DIR_SETUP_US(2),
-        .SPEED0_HALF_US(2),
-        .SPEED1_HALF_US(2),
-        .SPEED2_HALF_US(2),
-        .SPEED3_HALF_US(2)
+        .DIR_SETUP_CYCLES(2),
+        .STEP_HALF_CYCLES(2)
     ) dut (
     ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .tick_1us(1'b1),
-        .force_stop(1'b0),
-        .limit_raw(limit_raw),
-        .jog_start(1'b0),
-        .jog_dir(1'b0),
-        .jog_speed_code(2'd0),
-        .jog_steps(16'd1),
-        .standard_start(1'b0),
-        .standard_target_open(1'b0),
-        .step_out(),
-        .dir_out(),
-        .busy(),
-        .drive_active(),
-        .position_valid(),
-        .current_aperture(),
-        .target_aperture()
+        .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)
     );
     );
 
 
-    task expect_pipe;
-        input [2:0] expected;
-        input [8*48-1:0] label_text;
-        begin
-            @(posedge clk);
-            #1;
-            if (dut.limit_sync_pipe !== expected) begin
-                $display("CDC_FAIL %0s pipe=%03b expected=%03b",
-                    label_text, dut.limit_sync_pipe, expected);
-                $fatal(1);
-            end
-        end
-    endtask
-
     initial begin
     initial begin
         repeat (3) @(negedge clk);
         repeat (3) @(negedge clk);
         rst_n = 1'b1;
         rst_n = 1'b1;
-        expect_pipe(3'b000, "reset low");
-
         @(negedge clk);
         @(negedge clk);
-        limit_raw = 1'b1;
-        expect_pipe(3'b001, "rise stage 1");
-        expect_pipe(3'b011, "rise stage 2");
-        expect_pipe(3'b111, "rise stage 3");
-
+        command_start = 1'b1;
         @(negedge clk);
         @(negedge clk);
-        limit_raw = 1'b0;
-        expect_pipe(3'b110, "fall stage 1");
-        expect_pipe(3'b100, "fall stage 2");
-        expect_pipe(3'b000, "fall stage 3");
-
+        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");
         $display("PASS: prod2u_p4_cdc_sync_depth_tb");
         $finish;
         $finish;
     end
     end

+ 443 - 0
tests/sim/prod2u_p4_completion_ack_contract_tb.v

@@ -0,0 +1,443 @@
+`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;
+    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),
+        .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;
+            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
+            wait_ready("JOG 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_JOG;
+            request_payload[15:8] = {6'd0, axis};
+            request_payload[23:16] = {7'd0, direction};
+            request_payload[31:24] = 8'd3;
+            request_payload[47:32] = steps;
+            request_crc16 = crc;
+            request_valid = 1'b1;
+            @(posedge clk);
+            #1;
+            @(negedge clk);
+            request_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

+ 134 - 251
tests/sim/prod2u_p4_core_watchdog_refresh_tb.v

@@ -1,13 +1,15 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
 
 
 module prod2u_p4_core_watchdog_refresh_tb;
 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_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_JOG = 8'h35;
     localparam [7:0] MOTION_GET_STATUS = 8'h37;
     localparam [7:0] MOTION_GET_STATUS = 8'h37;
     localparam [7:0] STATUS_OK = 8'h00;
     localparam [7:0] STATUS_OK = 8'h00;
-    localparam integer CLK_HZ = 64;
-    localparam integer WATCHDOG_SECONDS = 5;
-    localparam integer WATCHDOG_CYCLES = CLK_HZ * WATCHDOG_SECONDS;
 
 
     reg clk = 1'b0;
     reg clk = 1'b0;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
@@ -17,54 +19,48 @@ module prod2u_p4_core_watchdog_refresh_tb;
     reg [5:0] request_length = 6'd0;
     reg [5:0] request_length = 6'd0;
     reg [271:0] request_payload = 272'd0;
     reg [271:0] request_payload = 272'd0;
     reg [15:0] request_crc16 = 16'd0;
     reg [15:0] request_crc16 = 16'd0;
-    wire disabled;
-    wire watchdog_timeout;
+    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] step_out;
     wire en_n;
     wire en_n;
+    wire disabled;
+    wire watchdog_timeout;
 
 
-    integer cycle_count = 0;
-    integer action_arm_count = 0;
-    integer refresh_count = 0;
-    integer last_lease_cycle = -1;
-    integer last_refresh_age = -1;
     integer guard;
     integer guard;
-    integer query_index;
-    integer timeout_age;
+    integer index;
+    integer x_rises = 0;
+    integer x_before;
+    reg [271:0] payload;
 
 
     always #5 clk = ~clk;
     always #5 clk = ~clk;
+    always @(posedge step_out[0]) x_rises = x_rises + 1;
 
 
     prod2u_p4_normal_v3_core #(
     prod2u_p4_normal_v3_core #(
-        .CLK_HZ(CLK_HZ),
-        .WATCHDOG_SECONDS(WATCHDOG_SECONDS),
-        .STANDARD_STEPS(8),
-        .LIMIT_CONFIRM_US(4),
-        .DIR_SETUP_US(1),
-        .SPEED0_HALF_US(2),
-        .SPEED1_HALF_US(2),
-        .SPEED2_HALF_US(2),
-        .SPEED3_HALF_US(1)
+        .CLK_HZ(32),
+        .WATCHDOG_SECONDS(1),
+        .DIR_SETUP_CYCLES(1),
+        .STEP_HALF_CYCLES(1)
     ) dut (
     ) dut (
         .clk(clk),
         .clk(clk),
         .rst_n(rst_n),
         .rst_n(rst_n),
-        .tick_1us(1'b1),
         .request_valid(request_valid),
         .request_valid(request_valid),
         .request_ready(request_ready),
         .request_ready(request_ready),
         .request_type(request_type),
         .request_type(request_type),
         .request_length(request_length),
         .request_length(request_length),
         .request_payload(request_payload),
         .request_payload(request_payload),
         .request_crc16(request_crc16),
         .request_crc16(request_crc16),
-        .emergency_disable_valid(1'b0),
-        .emergency_disable_crc16(16'd0),
-        .frame_valid(),
+        .frame_valid(frame_valid),
         .frame_ready(1'b1),
         .frame_ready(1'b1),
-        .frame_type(),
+        .frame_type(frame_type),
         .frame_payload_len(),
         .frame_payload_len(),
-        .frame_payload(),
-        .x_limit_raw(1'b0),
-        .y_limit_raw(1'b0),
-        .ptc_percent(),
-        .fan_percent(),
-        .solenoid_percent(),
+        .frame_payload(frame_payload),
+        .ptc_percent(ptc_percent),
+        .fan_percent(fan_percent),
+        .solenoid_percent(solenoid_percent),
         .state_hash16(),
         .state_hash16(),
         .step_out(step_out),
         .step_out(step_out),
         .dir_out(),
         .dir_out(),
@@ -73,19 +69,6 @@ module prod2u_p4_core_watchdog_refresh_tb;
         .watchdog_timeout(watchdog_timeout)
         .watchdog_timeout(watchdog_timeout)
     );
     );
 
 
-    always @(posedge clk) begin
-        cycle_count = cycle_count + 1;
-        if (rst_n && dut.watchdog_action_arm) begin
-            action_arm_count = action_arm_count + 1;
-            last_lease_cycle = cycle_count;
-        end
-        if (rst_n && dut.watchdog_status_refresh) begin
-            refresh_count = refresh_count + 1;
-            last_refresh_age = cycle_count - last_lease_cycle;
-            last_lease_cycle = cycle_count;
-        end
-    end
-
     task fail;
     task fail;
         input [8*120-1:0] message;
         input [8*120-1:0] message;
         begin
         begin
@@ -94,271 +77,171 @@ module prod2u_p4_core_watchdog_refresh_tb;
         end
         end
     endtask
     endtask
 
 
-    task wait_request_ready;
-        input [8*64-1:0] label_text;
-        begin
-            guard = 0;
-            while (!request_ready && guard < 512) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (!request_ready) begin
-                $display("READY_TIMEOUT label=%0s state=%0d inflight=%0d deferred_disable=%0d expiry_due=%0d",
-                    label_text, dut.state, dut.command_inflight,
-                    dut.deferred_disable_pending, dut.watchdog_expiry_due);
-                fail(label_text);
-            end
-        end
-    endtask
-
-    task wait_response_ok;
-        input [7:0] expected_command;
-        input [8*64-1:0] label_text;
+    task wait_ready;
         begin
         begin
             guard = 0;
             guard = 0;
-            while (!dut.command_response_valid && guard < 128) begin
+            while (!request_ready && guard < 1024) begin
                 @(negedge clk);
                 @(negedge clk);
                 guard = guard + 1;
                 guard = guard + 1;
             end
             end
-            if (!dut.command_response_valid) begin
-                fail(label_text);
-            end
-            if (dut.command_ack_payload[7:0] !== 8'h01 ||
-                dut.command_ack_payload[15:8] !== expected_command ||
-                dut.command_ack_payload[23:16] !== STATUS_OK) begin
-                $display("BAD_ACK label=%0s ack=%016h", label_text,
-                    dut.command_ack_payload);
-                fail(label_text);
-            end
+            if (!request_ready) fail("request_ready timeout");
         end
         end
     endtask
     endtask
 
 
-    task issue_status_when_ready;
-        input [15:0] crc;
-        input [8*64-1:0] label_text;
+    task send_request;
+        input [7:0] kind;
+        input [5:0] length;
+        input [271:0] bytes;
         begin
         begin
-            wait_request_ready(label_text);
+            wait_ready();
             @(negedge clk);
             @(negedge clk);
-            if (!request_ready) fail(label_text);
-            request_type = FT_MOTION_CMD;
-            request_length = 6'd8;
-            request_payload = 272'd0;
-            request_payload[7:0] = MOTION_GET_STATUS;
-            request_crc16 = crc;
+            request_type = kind;
+            request_length = length;
+            request_payload = bytes;
+            request_crc16 = request_crc16 + 16'd1;
             request_valid = 1'b1;
             request_valid = 1'b1;
             @(posedge clk);
             @(posedge clk);
             #1;
             #1;
             @(negedge clk);
             @(negedge clk);
             request_valid = 1'b0;
             request_valid = 1'b0;
-            wait_response_ok(MOTION_GET_STATUS, label_text);
         end
         end
     endtask
     endtask
 
 
-    task issue_jog_arm;
+    task expect_ack;
+        input [7:0] command;
         begin
         begin
-            wait_request_ready("jog arm ready");
-            @(negedge clk);
-            if (!request_ready) fail("jog lost ready");
-            request_type = FT_MOTION_CMD;
-            request_length = 6'd8;
-            request_payload = 272'd0;
-            request_payload[7:0] = MOTION_JOG;
-            request_payload[15:8] = 8'd0;
-            request_payload[23:16] = 8'd1;
-            request_payload[31:24] = 8'd3;
-            request_payload[47:32] = 16'd800;
-            request_crc16 = 16'ha101;
-            request_valid = 1'b1;
-            @(negedge clk);
-            request_valid = 1'b0;
-            wait_response_ok(MOTION_JOG, "jog arm response");
             guard = 0;
             guard = 0;
-            while (action_arm_count == 0 && guard < 32) begin
-                @(negedge clk);
+            while (!(frame_valid && frame_type == FT_HOST_ACK) && guard < 1024) begin
+                @(posedge clk);
+                #1;
                 guard = guard + 1;
                 guard = guard + 1;
             end
             end
-            if (action_arm_count != 1 || last_lease_cycle < 0 ||
-                disabled || !dut.watchdog_armed || watchdog_timeout) begin
-                $display("ARM_FAIL arms=%0d lease_cycle=%0d disabled=%0d armed=%0d timeout=%0d",
-                    action_arm_count, last_lease_cycle, disabled,
-                    dut.watchdog_armed, watchdog_timeout);
-                fail("accepted JOG did not arm watchdog exactly once");
-            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
         end
     endtask
     endtask
 
 
-    task issue_active_replacement_rearm;
+    task issue_status;
         begin
         begin
-            repeat (CLK_HZ / 2) @(negedge clk);
-            wait_request_ready("active replacement ready");
-            if (!dut.motor_axis_active_mask[0] || watchdog_timeout || disabled) begin
-                fail("replacement setup axis was not active before second JOG");
-            end
-            request_type = FT_MOTION_CMD;
-            request_length = 6'd8;
-            request_payload = 272'd0;
-            request_payload[7:0] = MOTION_JOG;
-            request_payload[15:8] = 8'd0;
-            request_payload[23:16] = 8'd0;
-            request_payload[31:24] = 8'd3;
-            request_payload[47:32] = 16'd800;
-            request_crc16 = 16'ha102;
-            request_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            request_valid = 1'b0;
-            wait_response_ok(MOTION_JOG, "active replacement response");
-            guard = 0;
-            while (action_arm_count < 2 && guard < 32) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (action_arm_count != 2 || !dut.motor_axis_active_mask[0] ||
-                disabled || !dut.watchdog_armed || watchdog_timeout) begin
-                $display("REARM_FAIL arms=%0d active=%03b disabled=%0d armed=%0d timeout=%0d",
-                    action_arm_count, dut.motor_axis_active_mask, disabled,
-                    dut.watchdog_armed, watchdog_timeout);
-                fail("accepted active-axis replacement did not rearm watchdog");
-            end
+            payload = 272'd0;
+            payload[7:0] = MOTION_GET_STATUS;
+            send_request(FT_MOTION_CMD, 6'd8, payload);
+            expect_ack(MOTION_GET_STATUS);
         end
         end
     endtask
     endtask
 
 
-    task issue_refresh_at_one_second;
-        input [15:0] crc;
-        input integer expected_refresh_count;
+    task issue_jog;
+        input [15:0] steps;
         begin
         begin
-            guard = 0;
-            while ((cycle_count - last_lease_cycle) < (CLK_HZ - 1) &&
-                   guard < (CLK_HZ + 16)) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if ((cycle_count - last_lease_cycle) != (CLK_HZ - 1)) begin
-                $display("REFRESH_SCHEDULE_FAIL age=%0d ready=%0d",
-                    cycle_count - last_lease_cycle, request_ready);
-                fail("could not schedule one-second status refresh");
-            end
-            if (!request_ready) fail("core not ready at one-second refresh boundary");
+            payload = 272'd0;
+            payload[7:0] = MOTION_JOG;
+            payload[15:8] = 8'd0;
+            payload[23:16] = 8'd1;
+            payload[31:24] = 8'd3;
+            payload[47:32] = steps;
+            send_request(FT_MOTION_CMD, 6'd8, payload);
+            expect_ack(MOTION_JOG);
+        end
+    endtask
 
 
-            request_type = FT_MOTION_CMD;
-            request_length = 6'd8;
-            request_payload = 272'd0;
-            request_payload[7:0] = MOTION_GET_STATUS;
-            request_crc16 = crc;
-            request_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            if (refresh_count != expected_refresh_count ||
-                last_refresh_age != CLK_HZ || disabled ||
-                !dut.watchdog_armed || watchdog_timeout) begin
-                $display("REFRESH_FAIL count=%0d/%0d age=%0d disabled=%0d armed=%0d timeout=%0d",
-                    refresh_count, expected_refresh_count, last_refresh_age,
-                    disabled, dut.watchdog_armed, watchdog_timeout);
-                fail("legal GET_MOTOR_STATUS did not refresh at one second");
-            end
-            @(negedge clk);
-            request_valid = 1'b0;
-            wait_response_ok(MOTION_GET_STATUS, "periodic status response");
+    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
         end
     endtask
     endtask
 
 
     initial begin
     initial begin
         repeat (4) @(negedge clk);
         repeat (4) @(negedge clk);
         rst_n = 1'b1;
         rst_n = 1'b1;
+        repeat (2) @(negedge clk);
 
 
-        wait_request_ready("initial disabled status ready");
-        if (!disabled || dut.watchdog_armed || watchdog_timeout) begin
-            fail("reset did not establish disabled unarmed state");
-        end
-        issue_status_when_ready(16'hd001, "initial disabled status");
-        wait_request_ready("initial disabled status drain");
-        if (refresh_count != 0 || action_arm_count != 0 ||
-            !disabled || dut.watchdog_armed || watchdog_timeout) begin
+        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");
             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
         end
+        if ((x_rises - x_before) != 20 || !disabled ||
+            dut.watchdog_armed || watchdog_timeout)
+            fail("JOG armed watchdog or did not execute while disabled");
 
 
-        issue_jog_arm();
-        wait_request_ready("jog arm drain");
-        issue_active_replacement_rearm();
-        wait_request_ready("active replacement drain");
+        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");
 
 
-        for (query_index = 1; query_index <= 6; query_index = query_index + 1) begin
-            issue_refresh_at_one_second(16'he000 + query_index, query_index);
-            wait_request_ready("periodic status drain");
-        end
-        if ((last_lease_cycle < 0) ||
-            (refresh_count * CLK_HZ <= WATCHDOG_CYCLES) ||
-            watchdog_timeout || disabled || !dut.watchdog_armed) begin
-            fail("rolling refresh did not keep lease alive beyond five seconds");
-        end
+        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;
         guard = 0;
-        while ((cycle_count - last_lease_cycle) < (WATCHDOG_CYCLES - 1) &&
-               guard < WATCHDOG_CYCLES) begin
+        while (!dut.watchdog_expiry_due && guard < 128) begin
             @(negedge clk);
             @(negedge clk);
-            if ((cycle_count - last_lease_cycle) < (WATCHDOG_CYCLES - 1) &&
-                (watchdog_timeout || disabled || !dut.watchdog_armed ||
-                 dut.watchdog_expiry_due)) begin
-                fail("watchdog expired before exact five-second boundary");
-            end
             guard = guard + 1;
             guard = guard + 1;
         end
         end
-        if ((cycle_count - last_lease_cycle) != (WATCHDOG_CYCLES - 1) ||
-            !dut.watchdog_expiry_due || watchdog_timeout || disabled ||
-            !dut.watchdog_armed || step_out !== 3'b000 || !en_n) begin
-            $display("EXPIRY_DUE_FAIL age=%0d due=%0d timeout=%0d disabled=%0d armed=%0d step=%03b en_n=%0d",
-                cycle_count - last_lease_cycle, dut.watchdog_expiry_due,
-                watchdog_timeout, disabled, dut.watchdog_armed, step_out, en_n);
-            fail("expiry_due was not exact or did not hard-safe pins");
-        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_type = FT_MOTION_CMD;
         request_length = 6'd8;
         request_length = 6'd8;
-        request_payload = 272'd0;
-        request_payload[7:0] = MOTION_GET_STATUS;
-        request_crc16 = 16'hefff;
+        request_payload = payload;
         request_valid = 1'b1;
         request_valid = 1'b1;
         #1;
         #1;
-        if (request_ready || dut.watchdog_status_refresh ||
-            !dut.watchdog_expiry_due) begin
-            fail("status refresh won over expiry boundary");
-        end
-
+        if (!request_ready || !dut.watchdog_status_refresh)
+            fail("simultaneous expiry/status request was not accepted");
         @(posedge clk);
         @(posedge clk);
         #1;
         #1;
-        timeout_age = cycle_count - last_lease_cycle;
-        if (timeout_age != WATCHDOG_CYCLES || !watchdog_timeout ||
-            !disabled || dut.watchdog_armed || dut.watchdog_expiry_due ||
-            step_out !== 3'b000 || !en_n) begin
-            $display("TIMEOUT_FAIL age=%0d timeout=%0d disabled=%0d armed=%0d due=%0d",
-                timeout_age, watchdog_timeout, disabled,
-                dut.watchdog_armed, dut.watchdog_expiry_due);
-            fail("registered timeout did not occur exactly at five seconds");
-        end
+        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;
         guard = 0;
-        while (!request_ready && guard < 512) begin
-            @(negedge clk);
+        while ((x_rises - x_before) < 100 && guard < 1024) begin
+            @(posedge clk);
+            #1;
             guard = guard + 1;
             guard = guard + 1;
         end
         end
-        if (!request_ready) fail("timeout-state status query was never accepted");
-        @(posedge clk);
-        #1;
-        if (dut.watchdog_status_refresh || refresh_count != 6) begin
-            fail("timeout-state status query generated a refresh pulse");
-        end
-        @(negedge clk);
-        request_valid = 1'b0;
-        wait_response_ok(MOTION_GET_STATUS, "timeout status response");
-        wait_request_ready("timeout status drain");
-        if (!watchdog_timeout || !disabled || dut.watchdog_armed ||
-            refresh_count != 6 || action_arm_count != 2) begin
-            fail("status query revived timed-out watchdog");
-        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 refreshes=%0d wall_cycles=%0d expiry_age=%0d",
-            refresh_count, 6 * CLK_HZ, timeout_age);
+        $display("PASS: prod2u_p4_core_watchdog_refresh_tb");
         $finish;
         $finish;
     end
     end
 endmodule
 endmodule

+ 52 - 307
tests/sim/prod2u_p4_jog_no_gates_contract_tb.v

@@ -1,335 +1,80 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
 
 
 module prod2u_p4_jog_no_gates_contract_tb;
 module prod2u_p4_jog_no_gates_contract_tb;
-    localparam [7:0] FT_MOTION_CMD = 8'h11;
-    localparam [7:0] MOTION_JOG = 8'h35;
-    localparam [7:0] STATUS_OK = 8'h00;
-    localparam integer STANDARD_STEPS = 8;
-
     reg clk = 1'b0;
     reg clk = 1'b0;
-
-    reg core_rst_n = 1'b0;
-    reg core_request_valid = 1'b0;
-    wire core_request_ready;
-    reg [7:0] core_request_type = 8'd0;
-    reg [5:0] core_request_length = 6'd0;
-    reg [271:0] core_request_payload = 272'd0;
-    reg [15:0] core_request_crc16 = 16'd0;
-    wire [2:0] core_step_out;
-    wire core_en_n;
-    wire core_disabled;
-    wire core_watchdog_timeout;
-
-    reg hub_rst_n = 1'b0;
-    reg hub_snapshot_valid = 1'b0;
-    reg [23:0] hub_snapshot_targets = 24'd0;
-    reg [2:0] hub_snapshot_busy_at_accept = 3'd0;
-    reg hub_jog_valid = 1'b0;
-    reg [1:0] hub_jog_axis = 2'd0;
-    reg hub_jog_dir = 1'b0;
-    reg [1:0] hub_jog_speed = 2'd3;
-    reg [15:0] hub_jog_steps = 16'd1;
-    wire hub_snapshot_result_valid;
-    wire [2:0] hub_snapshot_accepted_mask;
-    wire hub_jog_result_valid;
-    wire hub_jog_accepted;
-    wire [2:0] hub_axis_active_mask;
-    wire [2:0] hub_step_out;
-
-    integer failures = 0;
-    integer guard;
-    integer core_x_rises = 0;
-    integer core_y_rises = 0;
-    integer hub_x_rises = 0;
-    integer hub_y_rises = 0;
-    integer rises_before;
+    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 #5 clk = ~clk;
-    always @(posedge core_step_out[0]) core_x_rises = core_x_rises + 1;
-    always @(posedge core_step_out[1]) core_y_rises = core_y_rises + 1;
-    always @(posedge hub_step_out[0]) hub_x_rises = hub_x_rises + 1;
-    always @(posedge hub_step_out[1]) hub_y_rises = hub_y_rises + 1;
-
-    prod2u_p4_normal_v3_core #(
-        .CLK_HZ(24),
-        .WATCHDOG_SECONDS(1),
-        .STANDARD_STEPS(STANDARD_STEPS),
-        .LIMIT_CONFIRM_US(4),
-        .DIR_SETUP_US(2),
-        .SPEED0_HALF_US(2),
-        .SPEED1_HALF_US(2),
-        .SPEED2_HALF_US(2),
-        .SPEED3_HALF_US(2)
-    ) core_dut (
-        .clk(clk),
-        .rst_n(core_rst_n),
-        .tick_1us(1'b1),
-        .request_valid(core_request_valid),
-        .request_ready(core_request_ready),
-        .request_type(core_request_type),
-        .request_length(core_request_length),
-        .request_payload(core_request_payload),
-        .request_crc16(core_request_crc16),
-        .emergency_disable_valid(1'b0),
-        .emergency_disable_crc16(16'd0),
-        .frame_valid(),
-        .frame_ready(1'b1),
-        .frame_type(),
-        .frame_payload_len(),
-        .frame_payload(),
-        .x_limit_raw(1'b1),
-        .y_limit_raw(1'b1),
-        .ptc_percent(),
-        .fan_percent(),
-        .solenoid_percent(),
-        .state_hash16(),
-        .step_out(core_step_out),
-        .dir_out(),
-        .en_n(core_en_n),
-        .disabled(core_disabled),
-        .watchdog_timeout(core_watchdog_timeout)
-    );
+    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 #(
     prod2u_p4_motor_hub #(
-        .STANDARD_STEPS(STANDARD_STEPS),
-        .LIMIT_CONFIRM_US(4),
-        .DIR_SETUP_US(2),
-        .SPEED0_HALF_US(2),
-        .SPEED1_HALF_US(2),
-        .SPEED2_HALF_US(2),
-        .SPEED3_HALF_US(2)
-    ) hub_dut (
-        .clk(clk),
-        .rst_n(hub_rst_n),
-        .tick_1us(1'b1),
-        .force_stop(1'b0),
-        .disabled(1'b0),
-        .watchdog_timeout(1'b0),
-        .x_limit_raw(1'b1),
-        .y_limit_raw(1'b1),
-        .snapshot_valid(hub_snapshot_valid),
-        .snapshot_targets(hub_snapshot_targets),
-        .snapshot_busy_at_accept(hub_snapshot_busy_at_accept),
-        .snapshot_result_valid(hub_snapshot_result_valid),
-        .snapshot_busy_mask(),
-        .snapshot_invalid_mask(),
-        .snapshot_accepted_mask(hub_snapshot_accepted_mask),
-        .jog_valid(hub_jog_valid),
-        .jog_axis(hub_jog_axis),
-        .jog_dir(hub_jog_dir),
-        .jog_speed_code(hub_jog_speed),
-        .jog_steps(hub_jog_steps),
-        .jog_result_valid(hub_jog_result_valid),
-        .jog_accepted(hub_jog_accepted),
-        .axis_active_mask(hub_axis_active_mask),
-        .axis_busy_mask(),
-        .step_out(hub_step_out),
-        .dir_out(),
-        .en_n(),
-        .status_payload()
+        .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 fail;
-        input [8*120-1:0] message;
-        begin
-            failures = failures + 1;
-            $display("JOG_NO_GATES_FAIL: %0s", message);
-        end
-    endtask
-
-    task reset_core;
-        begin
-            core_rst_n = 1'b0;
-            core_request_valid = 1'b0;
-            core_request_type = 8'd0;
-            core_request_length = 6'd0;
-            core_request_payload = 272'd0;
-            core_request_crc16 = 16'd0;
-            repeat (4) @(negedge clk);
-            core_rst_n = 1'b1;
-            repeat (4) @(negedge clk);
-        end
-    endtask
-
-    task wait_core_ready;
-        input [8*80-1:0] label_text;
-        begin
-            guard = 0;
-            while (!core_request_ready && guard < 256) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (!core_request_ready) fail(label_text);
-        end
-    endtask
-
-    task send_core_jog_expect_ok;
+    task issue_jog;
         input [1:0] axis;
         input [1:0] axis;
         input direction;
         input direction;
         input [15:0] steps;
         input [15:0] steps;
-        input [15:0] crc;
-        input [8*80-1:0] label_text;
-        reg [63:0] observed_ack;
         begin
         begin
-            wait_core_ready(label_text);
             @(negedge clk);
             @(negedge clk);
-            core_request_type = FT_MOTION_CMD;
-            core_request_length = 6'd8;
-            core_request_payload = 272'd0;
-            core_request_payload[7:0] = MOTION_JOG;
-            core_request_payload[15:8] = {6'd0, axis};
-            core_request_payload[23:16] = {7'd0, direction};
-            core_request_payload[31:24] = 8'd3;
-            core_request_payload[47:32] = steps;
-            core_request_crc16 = crc;
-            core_request_valid = 1'b1;
-            @(posedge clk);
-            #1;
+            jog_axis = axis;
+            jog_dir = direction;
+            jog_steps = steps;
+            jog_start = 1'b1;
             @(negedge clk);
             @(negedge clk);
-            core_request_valid = 1'b0;
-
-            guard = 0;
-            while (!core_dut.command_response_valid && guard < 128) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (!core_dut.command_response_valid) begin
-                fail(label_text);
-            end else begin
-                observed_ack = core_dut.command_ack_payload;
-                if (observed_ack[7:0] !== 8'h01 ||
-                    observed_ack[15:8] !== MOTION_JOG ||
-                    observed_ack[23:16] !== STATUS_OK) begin
-                    $display("JOG_ACK_MISMATCH label=%0s ack=%016h status=%02h",
-                        label_text, observed_ack, observed_ack[23:16]);
-                    fail(label_text);
-                end
-            end
-            wait_core_ready("JOG response did not retire");
-        end
-    endtask
-
-    task wait_core_axis_rise;
-        input [1:0] axis;
-        input integer previous_count;
-        input [8*80-1:0] label_text;
-        begin
-            guard = 0;
-            while ((((axis == 2'd0) && (core_x_rises <= previous_count)) ||
-                    ((axis == 2'd1) && (core_y_rises <= previous_count))) &&
-                   guard < 128) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (((axis == 2'd0) && (core_x_rises <= previous_count)) ||
-                ((axis == 2'd1) && (core_y_rises <= previous_count))) begin
-                fail(label_text);
-            end
-        end
-    endtask
-
-    task reset_hub;
-        begin
-            hub_rst_n = 1'b0;
-            hub_snapshot_valid = 1'b0;
-            hub_snapshot_targets = 24'd0;
-            hub_snapshot_busy_at_accept = 3'd0;
-            hub_jog_valid = 1'b0;
-            hub_jog_axis = 2'd0;
-            hub_jog_dir = 1'b0;
-            hub_jog_speed = 2'd3;
-            hub_jog_steps = 16'd1;
-            repeat (4) @(negedge clk);
-            hub_rst_n = 1'b1;
-            repeat (3) @(negedge clk);
+            jog_start = 1'b0;
         end
         end
     endtask
     endtask
 
 
     initial begin
     initial begin
-        // An active axis is a replacement target, not a JOG admission gate.
-        reset_core();
-        rises_before = core_x_rises;
-        send_core_jog_expect_ok(2'd0, 1'b0, 16'd64, 16'h5101,
-            "initial active-axis JOG was rejected");
-        wait_core_axis_rise(2'd0, rises_before,
-            "initial active-axis JOG did not emit STEP");
-        if (!core_dut.motor_axis_active_mask[0]) begin
-            fail("axis was not active before replacement JOG");
-        end
-        rises_before = core_x_rises;
-        send_core_jog_expect_ok(2'd0, 1'b1, 16'd3, 16'h5102,
-            "active-axis replacement JOG did not ACK OK");
-        wait_core_axis_rise(2'd0, rises_before,
-            "active-axis replacement JOG did not restart STEP");
+        repeat (3) @(negedge clk);
+        rst_n = 1'b1;
 
 
-        // Watchdog expiry may stop the old motion, but the next legal JOG is
-        // itself the recovery/arm action and must never return BUSY.
-        reset_core();
-        rises_before = core_y_rises;
-        send_core_jog_expect_ok(2'd1, 1'b0, 16'd800, 16'h5201,
-            "watchdog setup JOG was rejected");
-        wait_core_axis_rise(2'd1, rises_before,
-            "watchdog setup JOG did not emit STEP");
-        guard = 0;
-        while (!core_watchdog_timeout && guard < 128) begin
+        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);
             @(negedge clk);
+            legacy_limit = ~legacy_limit;
+            legacy_disabled = ~legacy_disabled;
+            legacy_watchdog = ~legacy_watchdog;
             guard = guard + 1;
             guard = guard + 1;
         end
         end
-        if (!core_watchdog_timeout || !core_disabled || !core_en_n) begin
-            fail("watchdog did not establish the timed-out hard-stop state");
-        end
-        rises_before = core_y_rises;
-        send_core_jog_expect_ok(2'd1, 1'b1, 16'd8, 16'h5202,
-            "legal JOG after watchdog timeout returned BUSY");
-        wait_core_axis_rise(2'd1, rises_before,
-            "legal JOG after watchdog timeout did not restart motion");
-        if (core_watchdog_timeout || core_disabled) begin
-            fail("legal JOG did not clear timeout and re-arm motion");
-        end
-
-        // Snapshot dispatch and a new JOG may coincide internally. JOG must be
-        // accepted and win the target axis while the other snapshot axis runs.
-        core_rst_n = 1'b0;
-        reset_hub();
-        rises_before = hub_x_rises;
-        @(negedge clk);
-        hub_snapshot_targets = {8'd0, 8'd100, 8'd100};
-        hub_snapshot_busy_at_accept = 3'b000;
-        hub_snapshot_valid = 1'b1;
-        hub_jog_axis = 2'd0;
-        hub_jog_dir = 1'b1;
-        hub_jog_speed = 2'd3;
-        hub_jog_steps = 16'd3;
-        hub_jog_valid = 1'b1;
-        @(posedge clk);
-        #1;
-        if (!hub_snapshot_result_valid ||
-            hub_snapshot_accepted_mask !== 3'b111) begin
-            fail("snapshot side of concurrent dispatch was not accepted");
-        end
-        if (!hub_jog_result_valid || !hub_jog_accepted) begin
-            $display("CONCURRENT_RESULT jog_valid=%0d accepted=%0d snapshot=%0d accepted_mask=%03b",
-                hub_jog_result_valid, hub_jog_accepted,
-                hub_snapshot_result_valid, hub_snapshot_accepted_mask);
-            fail("snapshot-valid gate rejected concurrent legal JOG");
-        end
-        @(negedge clk);
-        hub_snapshot_valid = 1'b0;
-        hub_jog_valid = 1'b0;
-        guard = 0;
-        while ((hub_axis_active_mask != 3'b000) && guard < 256) begin
-            @(negedge clk);
-            guard = guard + 1;
-        end
-        if ((hub_x_rises - rises_before) != 3) begin
-            $display("CONCURRENT_X_STEPS observed=%0d expected=3",
-                hub_x_rises - rises_before);
-            fail("concurrent JOG did not replace the X snapshot motion");
-        end
+        repeat (6) @(negedge clk);
 
 
-        if (failures != 0) begin
-            $fatal(1, "prod2u_p4_jog_no_gates_contract_tb RED failures=%0d",
-                failures);
+        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
         end
         $display("PASS: prod2u_p4_jog_no_gates_contract_tb");
         $display("PASS: prod2u_p4_jog_no_gates_contract_tb");
         $finish;
         $finish;

+ 112 - 454
tests/sim/prod2u_p4_minimal_snapshot_contract_tb.v

@@ -3,12 +3,11 @@
 module prod2u_p4_minimal_snapshot_contract_tb;
 module prod2u_p4_minimal_snapshot_contract_tb;
     localparam [7:0] FT_HOST_BATCH_CMD = 8'h07;
     localparam [7:0] FT_HOST_BATCH_CMD = 8'h07;
     localparam [7:0] FT_MOTION_CMD = 8'h11;
     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] CMD_SET_SNAPSHOT = 8'h2a;
     localparam [7:0] MOTION_JOG = 8'h35;
     localparam [7:0] MOTION_JOG = 8'h35;
     localparam [7:0] STATUS_OK = 8'h00;
     localparam [7:0] STATUS_OK = 8'h00;
     localparam [7:0] STATUS_BAD_VALUE = 8'h05;
     localparam [7:0] STATUS_BAD_VALUE = 8'h05;
-    localparam [7:0] STATUS_PARTIAL = 8'h16;
-    localparam integer STANDARD_STEPS = 8;
 
 
     reg clk = 1'b0;
     reg clk = 1'b0;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
@@ -20,7 +19,6 @@ module prod2u_p4_minimal_snapshot_contract_tb;
     reg [15:0] request_crc16 = 16'd0;
     reg [15:0] request_crc16 = 16'd0;
     wire frame_valid;
     wire frame_valid;
     wire [7:0] frame_type;
     wire [7:0] frame_type;
-    wire [7:0] frame_payload_len;
     wire [143:0] frame_payload;
     wire [143:0] frame_payload;
     wire [191:0] ptc_percent;
     wire [191:0] ptc_percent;
     wire [31:0] fan_percent;
     wire [31:0] fan_percent;
@@ -31,53 +29,38 @@ module prod2u_p4_minimal_snapshot_contract_tb;
     wire disabled;
     wire disabled;
     wire watchdog_timeout;
     wire watchdog_timeout;
 
 
-    integer errors = 0;
+    integer x_rises = 0;
+    integer y_rises = 0;
+    integer z_rises = 0;
     integer guard;
     integer guard;
-    integer x_step_edges = 0;
-    integer y_step_edges = 0;
+    integer index;
     integer x_before;
     integer x_before;
-    integer y_before;
-    integer x_after;
-    integer y_after;
-    reg simultaneous_step_seen = 1'b0;
+    reg [271:0] payload;
 
 
     always #5 clk = ~clk;
     always #5 clk = ~clk;
-    always @(posedge step_out[0]) x_step_edges = x_step_edges + 1;
-    always @(posedge step_out[1]) y_step_edges = y_step_edges + 1;
-    always @(posedge clk) begin
-        #1;
-        if (rst_n && step_out[0] && step_out[1]) simultaneous_step_seen = 1'b1;
-    end
+    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 #(
     prod2u_p4_normal_v3_core #(
-        .CLK_HZ(100),
-        .WATCHDOG_SECONDS(5),
-        .STANDARD_STEPS(STANDARD_STEPS),
-        .LIMIT_CONFIRM_US(8),
-        .DIR_SETUP_US(20),
-        .SPEED0_HALF_US(2),
-        .SPEED1_HALF_US(2),
-        .SPEED2_HALF_US(2),
-        .SPEED3_HALF_US(2)
+        .CLK_HZ(64),
+        .WATCHDOG_SECONDS(1),
+        .DIR_SETUP_CYCLES(2),
+        .STEP_HALF_CYCLES(1)
     ) dut (
     ) dut (
         .clk(clk),
         .clk(clk),
         .rst_n(rst_n),
         .rst_n(rst_n),
-        .tick_1us(1'b1),
         .request_valid(request_valid),
         .request_valid(request_valid),
         .request_ready(request_ready),
         .request_ready(request_ready),
         .request_type(request_type),
         .request_type(request_type),
         .request_length(request_length),
         .request_length(request_length),
         .request_payload(request_payload),
         .request_payload(request_payload),
         .request_crc16(request_crc16),
         .request_crc16(request_crc16),
-        .emergency_disable_valid(1'b0),
-        .emergency_disable_crc16(16'd0),
         .frame_valid(frame_valid),
         .frame_valid(frame_valid),
         .frame_ready(1'b1),
         .frame_ready(1'b1),
         .frame_type(frame_type),
         .frame_type(frame_type),
-        .frame_payload_len(frame_payload_len),
+        .frame_payload_len(),
         .frame_payload(frame_payload),
         .frame_payload(frame_payload),
-        .x_limit_raw(1'b0),
-        .y_limit_raw(1'b0),
         .ptc_percent(ptc_percent),
         .ptc_percent(ptc_percent),
         .fan_percent(fan_percent),
         .fan_percent(fan_percent),
         .solenoid_percent(solenoid_percent),
         .solenoid_percent(solenoid_percent),
@@ -92,469 +75,144 @@ module prod2u_p4_minimal_snapshot_contract_tb;
     task fail;
     task fail;
         input [8*120-1:0] message;
         input [8*120-1:0] message;
         begin
         begin
-            errors = errors + 1;
-            $display("MINIMAL_SNAPSHOT_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;
-            simultaneous_step_seen = 1'b0;
-            repeat (4) @(negedge clk);
-            rst_n = 1'b1;
-            repeat (4) @(negedge clk);
+            $display("SNAPSHOT_CONTRACT_FAIL: %0s", message);
+            $fatal(1);
         end
         end
     endtask
     endtask
 
 
     task wait_ready;
     task wait_ready;
-        input [8*64-1:0] label_text;
-        begin
-            guard = 0;
-            while (!request_ready && guard < 512) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (!request_ready) fail(label_text);
-        end
-    endtask
-
-    task wait_ack;
-        input expected_ok;
-        input [7:0] expected_command;
-        input [7:0] expected_status;
-        input [7:0] expected_detail;
-        input [7:0] expected_flags;
-        input [8*64-1:0] label_text;
-        reg [63:0] observed_ack;
         begin
         begin
             guard = 0;
             guard = 0;
-            while (!dut.command_response_valid && guard < 512) begin
+            while (!request_ready && guard < 1024) begin
                 @(negedge clk);
                 @(negedge clk);
                 guard = guard + 1;
                 guard = guard + 1;
             end
             end
-            if (!dut.command_response_valid) begin
-                fail(label_text);
-            end else begin
-                observed_ack = dut.command_ack_payload;
-                if (observed_ack[7:0] !== {7'd0, expected_ok} ||
-                    observed_ack[15:8] !== expected_command ||
-                    observed_ack[23:16] !== expected_status ||
-                    observed_ack[31:24] !== expected_detail ||
-                    observed_ack[63:56] !== expected_flags) begin
-                    $display("ACK_MISMATCH label=%0s ack=%016h expected_cmd=%02h status=%02h detail=%02h flags=%02h",
-                        label_text, observed_ack, expected_command,
-                        expected_status, expected_detail, expected_flags);
-                    fail(label_text);
-                end
-            end
-            wait_ready("response did not retire");
-        end
-    endtask
-
-    task send_jog;
-        input [1:0] axis;
-        input direction;
-        input [15:0] steps;
-        input [15:0] crc;
-        input [8*64-1:0] label_text;
-        begin
-            wait_ready(label_text);
-            @(negedge clk);
-            request_type = FT_MOTION_CMD;
-            request_length = 6'd8;
-            request_payload = 272'd0;
-            request_payload[7:0] = MOTION_JOG;
-            request_payload[15:8] = {6'd0, axis};
-            request_payload[23:16] = {7'd0, direction};
-            request_payload[31:24] = 8'd3;
-            request_payload[47:32] = steps;
-            request_crc16 = crc;
-            request_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            request_valid = 1'b0;
-            wait_ack(1'b1, MOTION_JOG, STATUS_OK, 8'd0, 8'd0, label_text);
-        end
-    endtask
-
-    task fill_snapshot;
-        input [7:0] ptc0;
-        input [7:0] ptc23;
-        input [7:0] fan0;
-        input [7:0] fan1;
-        input [7:0] fan2;
-        input [7:0] fan3;
-        input [7:0] solenoid;
-        input [7:0] x_target;
-        input [7:0] y_target;
-        input [7:0] z_target;
-        integer index;
-        begin
-            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) begin
-                request_payload[(index + 2) * 8 +: 8] = 8'd0;
-            end
-            request_payload[2 * 8 +: 8] = ptc0;
-            request_payload[25 * 8 +: 8] = ptc23;
-            request_payload[26 * 8 +: 8] = fan0;
-            request_payload[27 * 8 +: 8] = fan1;
-            request_payload[28 * 8 +: 8] = fan2;
-            request_payload[29 * 8 +: 8] = fan3;
-            request_payload[30 * 8 +: 8] = solenoid;
-            request_payload[31 * 8 +: 8] = x_target;
-            request_payload[32 * 8 +: 8] = y_target;
-            request_payload[33 * 8 +: 8] = z_target;
-        end
-    endtask
-
-    task send_snapshot;
-        input [7:0] ptc0;
-        input [7:0] ptc23;
-        input [7:0] fan0;
-        input [7:0] fan1;
-        input [7:0] fan2;
-        input [7:0] fan3;
-        input [7:0] solenoid;
-        input [7:0] x_target;
-        input [7:0] y_target;
-        input [7:0] z_target;
-        input expected_ok;
-        input [7:0] expected_status;
-        input [7:0] expected_detail;
-        input [7:0] expected_flags;
-        input [15:0] crc;
-        input [8*64-1:0] label_text;
-        begin
-            wait_ready(label_text);
-            @(negedge clk);
-            request_type = FT_HOST_BATCH_CMD;
-            request_length = 6'd34;
-            fill_snapshot(ptc0, ptc23, fan0, fan1, fan2, fan3,
-                solenoid, x_target, y_target, z_target);
-            request_crc16 = crc;
-            request_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            request_valid = 1'b0;
-            wait_ack(expected_ok, CMD_SET_SNAPSHOT, expected_status, expected_detail,
-                expected_flags, label_text);
+            if (!request_ready) fail("request_ready timeout");
         end
         end
     endtask
     endtask
 
 
-    task begin_snapshot;
-        input [7:0] ptc0;
-        input [7:0] ptc23;
-        input [7:0] fan0;
-        input [7:0] fan1;
-        input [7:0] fan2;
-        input [7:0] fan3;
-        input [7:0] solenoid;
-        input [7:0] x_target;
-        input [7:0] y_target;
-        input [7:0] z_target;
-        input [15:0] crc;
-        input [8*64-1:0] label_text;
+    task issue_request;
+        input [7:0] kind;
+        input [5:0] length;
+        input [271:0] bytes;
         begin
         begin
-            wait_ready(label_text);
+            wait_ready();
             @(negedge clk);
             @(negedge clk);
-            request_type = FT_HOST_BATCH_CMD;
-            request_length = 6'd34;
-            fill_snapshot(ptc0, ptc23, fan0, fan1, fan2, fan3,
-                solenoid, x_target, y_target, z_target);
-            request_crc16 = crc;
+            request_type = kind;
+            request_length = length;
+            request_payload = bytes;
+            request_crc16 = request_crc16 + 16'd1;
             request_valid = 1'b1;
             request_valid = 1'b1;
             @(posedge clk);
             @(posedge clk);
             #1;
             #1;
-            if (dut.state !== 3'd1) begin
-                fail("snapshot command was not captured into validation");
-            end
             @(negedge clk);
             @(negedge clk);
             request_valid = 1'b0;
             request_valid = 1'b0;
         end
         end
     endtask
     endtask
 
 
-    task wait_edge_count;
-        input integer expected_x;
-        input integer expected_y;
-        input [8*64-1:0] label_text;
+    task expect_ack;
+        input [7:0] command;
+        input [7:0] status;
         begin
         begin
             guard = 0;
             guard = 0;
-            while (((x_step_edges < expected_x) || (y_step_edges < expected_y)) &&
-                   guard < 2048) begin
-                @(negedge clk);
+            while (!(frame_valid && frame_type == FT_HOST_ACK) && guard < 1024) begin
+                @(posedge clk);
+                #1;
                 guard = guard + 1;
                 guard = guard + 1;
             end
             end
-            if ((x_step_edges < expected_x) || (y_step_edges < expected_y)) begin
-                $display("STEP_TIMEOUT label=%0s x=%0d/%0d y=%0d/%0d",
-                    label_text, x_step_edges, expected_x,
-                    y_step_edges, expected_y);
-                fail(label_text);
-            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
         end
     endtask
     endtask
 
 
-    initial begin
-        // Validate the raw solenoid field before applying active-axis hold.
-        // Value 50 is illegal for the binary solenoid and must reject the
-        // entire snapshot without committing outputs or starting the idle Y.
-        reset_core();
-        x_before = x_step_edges;
-        y_before = y_step_edges;
-        send_jog(2'd0, 1'b0, 16'd64, 16'h0f01,
-            "invalid-solenoid setup JOG was rejected");
-        if (!dut.motor_axis_active_mask[0]) begin
-            fail("invalid-solenoid setup axis was not active");
-        end
-        send_snapshot(8'd17, 8'd99, 8'd11, 8'd22, 8'd33, 8'd44,
-            8'd50, 8'd100, 8'd100, 8'd0,
-            1'b0, STATUS_BAD_VALUE, 8'h00, 8'h00, 16'h0f02,
-            "active-axis invalid solenoid was not rejected");
-        if (ptc_percent !== 192'd0 || fan_percent !== {4{8'd30}} ||
-            solenoid_percent !== 8'd0 || y_step_edges != y_before) begin
-            $display("INVALID_SOLENOID_SIDE_EFFECT ptc=%048h fan=%08h sol=%0d y=%0d/%0d",
-                ptc_percent, fan_percent, solenoid_percent,
-                y_step_edges, y_before);
-            fail("invalid solenoid snapshot changed outputs or started Y");
-        end
-
-        // An accepted command owns its axis throughout DIR setup even though
-        // reported busy must remain low until the first physical STEP rise.
-        // Snapshot arbitration and solenoid holding use that internal active
-        // state, not the public busy bit.
-        reset_core();
-        x_before = x_step_edges;
-        y_before = y_step_edges;
-        send_jog(2'd0, 1'b0, 16'd64, 16'h1001,
-            "X setup-only JOG was rejected");
-        if (!dut.u_motors.x_drive_request || dut.motor_axis_busy_mask[0]) begin
-            $display("SETUP_STATE active=%0d busy=%03b step=%03b",
-                dut.u_motors.x_drive_request, dut.motor_axis_busy_mask,
-                step_out);
-            fail("DIR setup did not separate internal active from public busy");
-        end
-        begin_snapshot(8'd17, 8'd99, 8'd11, 8'd22, 8'd33, 8'd44,
-            8'd100, 8'd100, 8'd100, 8'd50, 16'h1002,
-            "setup-active snapshot was not accepted");
-        if (dut.snapshot_busy_at_accept !== 3'b001) begin
-            $display("SETUP_SNAPSHOT_BUSY public=%03b latched=%03b active=%0d",
-                dut.motor_axis_busy_mask, dut.snapshot_busy_at_accept,
-                dut.u_motors.x_drive_request);
-            fail("snapshot used public busy instead of internal active");
-        end
-        wait_ack(1'b1, CMD_SET_SNAPSHOT, STATUS_PARTIAL, 8'h61, 8'h05,
-            "setup-active snapshot did not preserve PARTIAL contract");
-        if (ptc_percent[7:0] !== 8'd17 ||
-            ptc_percent[23 * 8 +: 8] !== 8'd99 ||
-            fan_percent[7:0] !== 8'd11 ||
-            fan_percent[15:8] !== 8'd22 ||
-            fan_percent[23:16] !== 8'd33 ||
-            fan_percent[31:24] !== 8'd44 ||
-            solenoid_percent !== 8'd0) begin
-            fail("setup-active snapshot did not commit PTC/FAN and hold solenoid");
-        end
-
-        // Once a STEP has been emitted, another valid JOG for the same axis is
-        // still accepted by the core and replaces the previous motion.
-        wait_edge_count(x_before + 1, y_before,
-            "X setup-only JOG did not produce a STEP");
-        send_jog(2'd0, 1'b1, 16'd3, 16'h1003,
-            "same-axis replacement JOG was rejected by core");
-
-        // One command may start both independent standard-motion executors.
-        reset_core();
-        x_before = x_step_edges;
-        y_before = y_step_edges;
-        send_snapshot(8'd0, 8'd0, 8'd30, 8'd30, 8'd30, 8'd30,
-            8'd0, 8'd100, 8'd100, 8'd0,
-            1'b1, STATUS_OK, 8'h00, 8'h0f, 16'h1101,
-            "same snapshot did not accept both axes");
-        wait_edge_count(x_before + STANDARD_STEPS,
-            y_before + STANDARD_STEPS,
-            "same snapshot did not execute both axes");
-        repeat (24) @(negedge clk);
-        if ((x_step_edges - x_before) != STANDARD_STEPS ||
-            (y_step_edges - y_before) != STANDARD_STEPS ||
-            !simultaneous_step_seen || dir_out[1:0] !== 2'b00) begin
-            $display("DUAL_STANDARD x=%0d y=%0d overlap=%0d dir=%02b",
-                x_step_edges - x_before, y_step_edges - y_before,
-                simultaneous_step_seen, dir_out[1:0]);
-            fail("same snapshot did not run two independent 3200-step equivalents");
-        end
-
-        // A busy X must not create a global movement lock for an idle Y JOG.
-        reset_core();
-        x_before = x_step_edges;
-        y_before = y_step_edges;
-        send_jog(2'd0, 1'b0, 16'd64, 16'h1201,
-            "X long JOG was rejected");
-        wait_edge_count(x_before + 2, y_before,
-            "X long JOG did not begin");
-        send_jog(2'd1, 1'b0, 16'd5, 16'h1202,
-            "busy X incorrectly blocked idle Y JOG");
-        wait_edge_count(x_before + 2, y_before + 5,
-            "Y JOG did not run beside busy X");
-        repeat (24) @(negedge clk);
-        if ((y_step_edges - y_before) != 5) begin
-            fail("Y JOG step count changed because X was busy");
-        end
-
-        // Busy X is ignored, idle Y starts, invalid Z is isolated, PTC/FAN
-        // still commit, and a solenoid change is held while either axis moves.
-        reset_core();
-        x_before = x_step_edges;
-        y_before = y_step_edges;
-        send_jog(2'd0, 1'b0, 16'd64, 16'h1301,
-            "X setup JOG was rejected");
-        wait_edge_count(x_before + 2, y_before,
-            "X setup JOG did not begin");
-        send_snapshot(8'd17, 8'd99, 8'd11, 8'd22, 8'd33, 8'd44,
-            8'd100, 8'd100, 8'd100, 8'd50,
-            1'b1, STATUS_PARTIAL, 8'h61, 8'h05, 16'h1302,
-            "snapshot did not return approved PARTIAL masks");
-
-        if (ptc_percent[7:0] !== 8'd17 ||
-            ptc_percent[23 * 8 +: 8] !== 8'd99 ||
-            fan_percent[7:0] !== 8'd11 ||
-            fan_percent[15:8] !== 8'd22 ||
-            fan_percent[23:16] !== 8'd33 ||
-            fan_percent[31:24] !== 8'd44) begin
-            fail("PTC/FAN did not commit when one motor target was busy");
-        end
-        if (solenoid_percent !== 8'd0) begin
-            fail("solenoid changed while an axis was busy");
-        end
-
-        wait_edge_count(x_before + 64, y_before + STANDARD_STEPS,
-            "busy-X/idle-Y snapshot motion did not retire");
-        x_after = x_step_edges;
-        y_after = y_step_edges;
-        repeat (40) @(negedge clk);
-        if ((x_after - x_before) != 64 || x_step_edges != x_after) begin
-            fail("ignored busy-X target was deferred or restarted");
-        end
-        if ((y_after - y_before) != STANDARD_STEPS || y_step_edges != y_after) begin
-            fail("idle Y did not execute exactly one standard motion");
+    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
         end
+    endfunction
 
 
-        // Arbitration is defined at command acceptance, not after the output
-        // scanner finishes. X is busy when this snapshot is accepted, then
-        // naturally becomes idle before motor dispatch. Its target must stay
-        // ignored and its busy bit must remain in the PARTIAL response.
-        reset_core();
-        x_before = x_step_edges;
-        y_before = y_step_edges;
-        send_jog(2'd0, 1'b0, 16'd1, 16'h1401,
-            "busy-to-idle setup JOG was rejected");
-        wait_edge_count(x_before + 1, y_before,
-            "busy-to-idle setup JOG did not emit STEP");
-        if (!dut.motor_axis_busy_mask[0]) begin
-            fail("busy-to-idle setup axis was not busy at snapshot intake");
-        end
-        begin_snapshot(8'd7, 8'd8, 8'd31, 8'd32, 8'd33, 8'd34,
-            8'd0, 8'd100, 8'd100, 8'd50, 16'h1402,
-            "busy-to-idle snapshot was not accepted");
-        if (dut.snapshot_busy_at_accept !== 3'b001) begin
-            $display("SNAPSHOT_ACCEPT_BUSY_FAIL busy_to_idle live=%03b latched=%03b",
-                dut.motor_axis_busy_mask, dut.snapshot_busy_at_accept);
-            fail("busy-to-idle intake busy mask was not captured");
-        end
-        guard = 0;
-        while (dut.motor_axis_busy_mask[0] && guard < 256) begin
-            @(negedge clk);
-            guard = guard + 1;
-        end
-        if (dut.motor_axis_busy_mask[0] || dut.motor_snapshot_start) begin
-            fail("busy-to-idle setup did not cross the validation window");
-        end
-        wait_ack(1'b1, CMD_SET_SNAPSHOT, STATUS_PARTIAL, 8'h21, 8'h05,
-            "busy-to-idle arbitration was resampled at dispatch");
-        wait_edge_count(x_before + 1, y_before + STANDARD_STEPS,
-            "busy-to-idle peer motion did not retire");
-        x_after = x_step_edges;
-        y_after = y_step_edges;
-        repeat (48) @(negedge clk);
-        if ((x_after - x_before) != 1 || x_step_edges != x_after) begin
-            fail("busy-at-intake X target started after X became idle");
-        end
-        if ((y_after - y_before) != STANDARD_STEPS || y_step_edges != y_after) begin
-            fail("idle-at-intake Y target was disturbed by X transition");
-        end
+    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");
+
+        payload = 272'd0;
+        payload[7:0] = MOTION_JOG;
+        payload[15:8] = 8'd0;
+        payload[23:16] = 8'd1;
+        payload[31:24] = 8'd3;
+        payload[47:32] = 16'd100;
+        x_before = x_rises;
+        issue_request(FT_MOTION_CMD, 6'd8, payload);
+        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");
 
 
-        // Fault-inject a second independent axis event after an idle snapshot
-        // has been accepted. The response masks must still describe the idle
-        // intake state instead of the later busy state at hub dispatch.
-        reset_core();
-        send_jog(2'd0, 1'b0, 16'd1, 16'h1501,
-            "idle-to-busy watchdog arm JOG was rejected");
         guard = 0;
         guard = 0;
-        while (dut.motor_axis_active_mask[0] && guard < 128) begin
-            @(negedge clk);
+        while (!watchdog_timeout && guard < 256) begin
+            @(posedge clk);
+            #1;
             guard = guard + 1;
             guard = guard + 1;
         end
         end
-        if (dut.motor_axis_active_mask[0]) begin
-            fail("idle-to-busy setup did not reach idle");
-        end
-        begin_snapshot(8'd9, 8'd10, 8'd35, 8'd36, 8'd37, 8'd38,
-            8'd0, 8'd100, 8'd100, 8'd0, 16'h1502,
-            "idle-to-busy snapshot was not accepted");
-        if (dut.snapshot_busy_at_accept !== 3'b000) begin
-            $display("SNAPSHOT_ACCEPT_BUSY_FAIL idle_to_busy live=%03b latched=%03b",
-                dut.motor_axis_busy_mask, dut.snapshot_busy_at_accept);
-            fail("idle-to-busy intake idle mask was not captured");
-        end
-        force dut.motor_jog_axis = 2'd0;
-        force dut.motor_jog_dir = 1'b0;
-        force dut.motor_jog_speed = 2'd3;
-        force dut.motor_jog_steps = 16'd64;
-        force dut.motor_jog_start = 1'b1;
-        @(posedge clk);
-        #1;
-        release dut.motor_jog_start;
-        release dut.motor_jog_axis;
-        release dut.motor_jog_dir;
-        release dut.motor_jog_speed;
-        release dut.motor_jog_steps;
-        if (!dut.motor_axis_active_mask[0]) begin
-            fail("idle-to-busy injected axis event did not start");
-        end
-        wait_ack(1'b1, CMD_SET_SNAPSHOT, STATUS_OK, 8'h00, 8'h0f,
-            "idle-to-busy arbitration was resampled at dispatch");
+        if (!watchdog_timeout || !disabled || en_n !== 1'b0)
+            fail("watchdog did not safe non-motor state");
 
 
-        // A valid long JOG arms the watchdog. Without a status heartbeat the
-        // five-second expiry hard-stops pins and clears both public busy and
-        // internal axis ownership.
-        reset_core();
-        send_jog(2'd0, 1'b0, 16'd800, 16'h1601,
-            "watchdog setup JOG was rejected");
-        wait_edge_count(x_step_edges + 1, y_step_edges,
-            "watchdog setup JOG did not produce STEP");
         guard = 0;
         guard = 0;
-        while (!watchdog_timeout && guard < 700) begin
-            @(negedge clk);
+        while ((x_rises - x_before) < 100 && guard < 1024) begin
+            @(posedge clk);
+            #1;
             guard = guard + 1;
             guard = guard + 1;
         end
         end
-        if (!watchdog_timeout || !disabled || step_out !== 3'b000 || !en_n ||
-            dut.motor_axis_active_mask !== 3'b000 ||
-            dut.motor_axis_busy_mask !== 3'b000) begin
-            $display("WATCHDOG_STOP timeout=%0d disabled=%0d active=%03b busy=%03b step=%03b en_n=%0d guard=%0d",
-                watchdog_timeout, disabled, dut.motor_axis_active_mask,
-                dut.motor_axis_busy_mask, step_out, en_n, guard);
-            fail("watchdog did not hard-stop active long JOG");
-        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");
 
 
-        if (errors != 0) begin
-            $fatal(1, "prod2u_p4_minimal_snapshot_contract_tb RED failures=%0d", errors);
-        end
         $display("PASS: prod2u_p4_minimal_snapshot_contract_tb");
         $display("PASS: prod2u_p4_minimal_snapshot_contract_tb");
         $finish;
         $finish;
     end
     end

+ 86 - 265
tests/sim/prod2u_p4_motor_hub_axis_isolation_tb.v

@@ -1,337 +1,158 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
 
 
 module prod2u_p4_motor_hub_axis_isolation_tb;
 module prod2u_p4_motor_hub_axis_isolation_tb;
-    localparam integer STANDARD_STEPS = 8;
+    localparam integer DIR_SETUP_CYCLES = 3;
+    localparam integer STEP_HALF_CYCLES = 2;
 
 
     reg clk = 1'b0;
     reg clk = 1'b0;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
-    reg force_stop = 1'b0;
-    reg disabled = 1'b0;
-    reg watchdog_timeout = 1'b0;
-    reg x_limit_raw = 1'b0;
-    reg y_limit_raw = 1'b0;
-    reg snapshot_valid = 1'b0;
-    reg [23:0] snapshot_targets = 24'd0;
-    reg [2:0] snapshot_busy_at_accept = 3'd0;
-    reg jog_valid = 1'b0;
+    reg jog_start = 1'b0;
     reg [1:0] jog_axis = 2'd0;
     reg [1:0] jog_axis = 2'd0;
     reg jog_dir = 1'b0;
     reg jog_dir = 1'b0;
-    reg [1:0] jog_speed_code = 2'd3;
     reg [15:0] jog_steps = 16'd1;
     reg [15:0] jog_steps = 16'd1;
 
 
-    wire snapshot_result_valid;
-    wire [2:0] snapshot_busy_mask;
-    wire [2:0] snapshot_invalid_mask;
-    wire [2:0] snapshot_accepted_mask;
-    wire jog_result_valid;
-    wire jog_accepted;
-    wire [2:0] axis_active_mask;
-    wire [2:0] axis_busy_mask;
+    wire [1:0] axis_started_pulse;
     wire [2:0] step_out;
     wire [2:0] step_out;
     wire [2:0] dir_out;
     wire [2:0] dir_out;
-    wire en_n;
-    wire [79:0] status_payload;
 
 
     integer failures = 0;
     integer failures = 0;
-    integer guard;
     integer x_rises = 0;
     integer x_rises = 0;
     integer y_rises = 0;
     integer y_rises = 0;
-    integer x_before;
-    integer y_before;
-    integer x_at_replace;
-    integer x_after_limit;
-    integer y_after_limit;
-    reg overlap_seen = 1'b0;
+    integer x_started = 0;
+    integer y_started = 0;
+    integer guard;
 
 
     always #5 clk = ~clk;
     always #5 clk = ~clk;
     always @(posedge step_out[0]) x_rises = x_rises + 1;
     always @(posedge step_out[0]) x_rises = x_rises + 1;
     always @(posedge step_out[1]) y_rises = y_rises + 1;
     always @(posedge step_out[1]) y_rises = y_rises + 1;
     always @(posedge clk) begin
     always @(posedge clk) begin
         #1;
         #1;
-        if (axis_active_mask[0] && axis_active_mask[1]) overlap_seen = 1'b1;
+        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
     end
 
 
     prod2u_p4_motor_hub #(
     prod2u_p4_motor_hub #(
-        .STANDARD_STEPS(STANDARD_STEPS),
-        .LIMIT_CONFIRM_US(8),
-        .DIR_SETUP_US(3),
-        .SPEED0_HALF_US(2),
-        .SPEED1_HALF_US(2),
-        .SPEED2_HALF_US(2),
-        .SPEED3_HALF_US(2)
+        .DIR_SETUP_CYCLES(DIR_SETUP_CYCLES),
+        .STEP_HALF_CYCLES(STEP_HALF_CYCLES)
     ) dut (
     ) dut (
         .clk(clk),
         .clk(clk),
         .rst_n(rst_n),
         .rst_n(rst_n),
-        .tick_1us(1'b1),
-        .force_stop(force_stop),
-        .disabled(disabled),
-        .watchdog_timeout(watchdog_timeout),
-        .x_limit_raw(x_limit_raw),
-        .y_limit_raw(y_limit_raw),
-        .snapshot_valid(snapshot_valid),
-        .snapshot_targets(snapshot_targets),
-        .snapshot_busy_at_accept(snapshot_busy_at_accept),
-        .snapshot_result_valid(snapshot_result_valid),
-        .snapshot_busy_mask(snapshot_busy_mask),
-        .snapshot_invalid_mask(snapshot_invalid_mask),
-        .snapshot_accepted_mask(snapshot_accepted_mask),
-        .jog_valid(jog_valid),
+        .jog_start(jog_start),
         .jog_axis(jog_axis),
         .jog_axis(jog_axis),
         .jog_dir(jog_dir),
         .jog_dir(jog_dir),
-        .jog_speed_code(jog_speed_code),
         .jog_steps(jog_steps),
         .jog_steps(jog_steps),
-        .jog_result_valid(jog_result_valid),
-        .jog_accepted(jog_accepted),
-        .axis_active_mask(axis_active_mask),
-        .axis_busy_mask(axis_busy_mask),
+        .axis_started_pulse(axis_started_pulse),
         .step_out(step_out),
         .step_out(step_out),
-        .dir_out(dir_out),
-        .en_n(en_n),
-        .status_payload(status_payload)
+        .dir_out(dir_out)
     );
     );
 
 
-    task fail;
-        input [8*96-1:0] message;
-        begin
-            failures = failures + 1;
-            $display("HUB_ISOLATION_FAIL: %0s", message);
-        end
-    endtask
-
-    task reset_hub;
-        begin
-            rst_n = 1'b0;
-            force_stop = 1'b0;
-            disabled = 1'b0;
-            watchdog_timeout = 1'b0;
-            x_limit_raw = 1'b0;
-            y_limit_raw = 1'b0;
-            snapshot_valid = 1'b0;
-            snapshot_targets = 24'd0;
-            snapshot_busy_at_accept = 3'd0;
-            jog_valid = 1'b0;
-            jog_axis = 2'd0;
-            jog_dir = 1'b0;
-            jog_speed_code = 2'd3;
-            jog_steps = 16'd1;
-            overlap_seen = 1'b0;
-            repeat (4) @(negedge clk);
-            rst_n = 1'b1;
-            repeat (3) @(negedge clk);
-            if (!en_n || step_out !== 3'b000 ||
-                axis_active_mask !== 3'b000 || axis_busy_mask !== 3'b000) begin
-                fail("reset did not establish idle motor pins");
-            end
-        end
-    endtask
-
-    task pulse_jog;
+    task issue_jog;
         input [1:0] axis;
         input [1:0] axis;
         input direction;
         input direction;
         input [15:0] steps;
         input [15:0] steps;
-        input expected_accept;
-        input [8*72-1:0] label_text;
         begin
         begin
             @(negedge clk);
             @(negedge clk);
             jog_axis = axis;
             jog_axis = axis;
             jog_dir = direction;
             jog_dir = direction;
-            jog_speed_code = 2'd3;
             jog_steps = steps;
             jog_steps = steps;
-            jog_valid = 1'b1;
+            jog_start = 1'b1;
             @(posedge clk);
             @(posedge clk);
             #1;
             #1;
-            if (!jog_result_valid || jog_accepted !== expected_accept) begin
-                $display("JOG_RESULT label=%0s valid=%0d accepted=%0d/%0d busy=%03b",
-                    label_text, jog_result_valid, jog_accepted,
-                    expected_accept, axis_busy_mask);
-                fail(label_text);
+            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
             end
-            @(negedge clk);
-            jog_valid = 1'b0;
-        end
-    endtask
-
-    task pulse_snapshot;
-        input [23:0] targets;
-        input [2:0] busy_at_accept;
-        input [2:0] expected_busy;
-        input [2:0] expected_invalid;
-        input [2:0] expected_accepted;
-        input [8*72-1:0] label_text;
-        begin
-            @(negedge clk);
-            snapshot_targets = targets;
-            snapshot_busy_at_accept = busy_at_accept;
-            snapshot_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            if (!snapshot_result_valid ||
-                snapshot_busy_mask !== expected_busy ||
-                snapshot_invalid_mask !== expected_invalid ||
-                snapshot_accepted_mask !== expected_accepted) begin
-                $display("SNAPSHOT_RESULT label=%0s busy=%03b/%03b invalid=%03b/%03b accepted=%03b/%03b live=%03b",
-                    label_text, snapshot_busy_mask, expected_busy,
-                    snapshot_invalid_mask, expected_invalid,
-                    snapshot_accepted_mask, expected_accepted,
-                    axis_busy_mask);
-                fail(label_text);
+            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
             end
             @(negedge clk);
             @(negedge clk);
-            snapshot_valid = 1'b0;
-            snapshot_busy_at_accept = 3'd0;
+            jog_start = 1'b0;
         end
         end
     endtask
     endtask
 
 
-    task wait_rises;
+    task wait_counts;
         input integer expected_x;
         input integer expected_x;
         input integer expected_y;
         input integer expected_y;
-        input [8*72-1:0] label_text;
         begin
         begin
             guard = 0;
             guard = 0;
             while (((x_rises < expected_x) || (y_rises < expected_y)) &&
             while (((x_rises < expected_x) || (y_rises < expected_y)) &&
-                   guard < 2048) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if ((x_rises < expected_x) || (y_rises < expected_y)) begin
-                $display("STEP_TIMEOUT label=%0s x=%0d/%0d y=%0d/%0d busy=%03b",
-                    label_text, x_rises, expected_x, y_rises, expected_y,
-                    axis_busy_mask);
-                fail(label_text);
-            end
-        end
-    endtask
-
-    task wait_idle;
-        input [8*72-1:0] label_text;
-        begin
-            guard = 0;
-            while ((axis_active_mask != 3'b000) && guard < 4096) begin
+                   (guard < 512)) begin
                 @(negedge clk);
                 @(negedge clk);
                 guard = guard + 1;
                 guard = guard + 1;
             end
             end
-            if (axis_active_mask != 3'b000 ||
-                axis_busy_mask != 3'b000 || step_out != 3'b000 || !en_n) begin
-                $display("IDLE_TIMEOUT label=%0s active=%02b busy=%03b step=%03b en_n=%0d",
-                    label_text, axis_active_mask[1:0],
-                    axis_busy_mask, step_out, en_n);
-                fail(label_text);
+            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
         end
         end
     endtask
     endtask
 
 
     initial begin
     initial begin
-        // Each axis accepts independently and may overlap in time.
-        reset_hub();
-        x_before = x_rises;
-        y_before = y_rises;
-        pulse_jog(2'd0, 1'b0, 16'd24, 1'b1,
-            "X long JOG was rejected");
-        wait_rises(x_before + 2, y_before, "X long JOG did not start");
-        pulse_jog(2'd1, 1'b0, 16'd5, 1'b1,
-            "busy X blocked idle Y");
-        x_at_replace = x_rises;
-        pulse_jog(2'd0, 1'b1, 16'd3, 1'b1,
-            "active X rejected replacement JOG");
-        wait_idle("overlapping JOGs did not retire");
-        if ((x_rises - x_at_replace) != 3 ||
-            (x_rises - x_before) >= 24 ||
-            (y_rises - y_before) != 5 || !overlap_seen || !dir_out[0]) begin
-            $display("OVERLAP_COUNT x=%0d post_replace=%0d y=%0d overlap=%0d dir=%0d",
-                x_rises - x_before, x_rises - x_at_replace,
-                y_rises - y_before, overlap_seen, dir_out[0]);
-            fail("replacement JOG did not discard old X tail or preserve Y");
-        end
-
-        // Snapshot uses the intake-time busy mask: busy X is ignored, idle Y
-        // starts, and invalid Z is reported without disturbing either axis.
-        reset_hub();
-        x_before = x_rises;
-        y_before = y_rises;
-        pulse_jog(2'd0, 1'b0, 16'd24, 1'b1,
-            "snapshot setup X JOG was rejected");
-        wait_rises(x_before + 2, y_before, "snapshot setup X did not start");
-        pulse_snapshot({8'd50, 8'd100, 8'd100}, 3'b001,
-            3'b001, 3'b100, 3'b010,
-            "snapshot did not isolate busy X and idle Y");
-        wait_idle("snapshot peer motion did not retire");
-        if ((x_rises - x_before) != 24 ||
-            (y_rises - y_before) != STANDARD_STEPS) begin
-            $display("SNAPSHOT_COUNT x=%0d y=%0d",
-                x_rises - x_before, y_rises - y_before);
-            fail("snapshot restarted busy X or lost idle Y");
+        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
         end
 
 
-        // Symmetric stagger: busy Y must not block a new X JOG.
-        reset_hub();
-        x_before = x_rises;
-        y_before = y_rises;
-        pulse_jog(2'd1, 1'b0, 16'd20, 1'b1,
-            "Y long JOG was rejected");
-        wait_rises(x_before, y_before + 2, "Y long JOG did not start");
-        pulse_jog(2'd0, 1'b0, 16'd6, 1'b1,
-            "busy Y blocked idle X");
-        wait_idle("symmetric stagger did not retire");
-        if ((x_rises - x_before) != 6 || (y_rises - y_before) != 20) begin
-            fail("symmetric independent JOG count mismatch");
+        // 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
         end
-
-        // Force-motion V1 ignores both limit inputs. A changing X limit cannot
-        // alter either the closing X count or the opening Y peer count.
-        reset_hub();
-        x_before = x_rises;
-        y_before = y_rises;
-        pulse_jog(2'd0, 1'b1, 16'd32, 1'b1,
-            "X close JOG was rejected");
-        pulse_jog(2'd1, 1'b0, 16'd12, 1'b1,
-            "Y open peer JOG was rejected");
-        wait_rises(x_before + 1, y_before + 1,
-            "limit isolation motions did not start");
-        @(negedge clk);
-        x_limit_raw = 1'b1;
-        wait_idle("X limit-ignored motions did not retire");
-        x_after_limit = x_rises - x_before;
-        y_after_limit = y_rises - y_before;
-        if ((x_after_limit != 32) || (y_after_limit != 12)) begin
-            $display("X_LIMIT_COUNT x=%0d y=%0d", x_after_limit, y_after_limit);
-            fail("X limit changed force-motion JOG counts");
+        guard = 0;
+        while ((y_rises < 9) && (guard < 128)) begin
+            @(negedge clk);
+            guard = guard + 1;
         end
         end
-
-        // A limit already high before command acceptance is ignored as well.
-        reset_hub();
-        x_before = x_rises;
-        y_before = y_rises;
-        y_limit_raw = 1'b1;
-        pulse_jog(2'd1, 1'b1, 16'd32, 1'b1,
-            "Y close JOG was rejected");
-        pulse_jog(2'd0, 1'b0, 16'd12, 1'b1,
-            "X open peer JOG was rejected");
-        wait_idle("Y high-limit force motions did not retire");
-        if (((y_rises - y_before) != 32) ||
-            ((x_rises - x_before) != 12)) begin
-            fail("startup-high Y limit changed force-motion counts");
+        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
         end
 
 
-        // DISABLE/watchdog hard-stop semantics are pin-combinational and then
-        // clear both independent executors on the following clock.
-        reset_hub();
-        pulse_jog(2'd0, 1'b0, 16'd32, 1'b1,
-            "hard-stop X setup was rejected");
-        pulse_jog(2'd1, 1'b0, 16'd32, 1'b1,
-            "hard-stop Y setup was rejected");
-        wait_rises(x_rises + 1, y_rises + 1,
-            "hard-stop motions did not start");
-        #1 force_stop = 1'b1;
-        #1;
-        if (step_out !== 3'b000 || !en_n) begin
-            fail("force_stop did not gate STEP and EN_N immediately");
-        end
-        @(posedge clk);
-        #1;
-        if (axis_active_mask !== 3'b000 || axis_busy_mask !== 3'b000 ||
-            step_out !== 3'b000 || !en_n ||
-            status_payload[79:72] !== 8'd0) begin
-            fail("force_stop did not clear both axis executors");
+        // 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
         end
 
 
         if (failures != 0) begin
         if (failures != 0) begin

+ 40 - 238
tests/sim/prod2u_p4_motor_status_payload_tb.v

@@ -1,258 +1,60 @@
 `timescale 1ns/1ps
 `timescale 1ns/1ps
 
 
 module prod2u_p4_motor_status_payload_tb;
 module prod2u_p4_motor_status_payload_tb;
-    localparam integer STANDARD_STEPS = 8;
-
     reg clk = 1'b0;
     reg clk = 1'b0;
     reg rst_n = 1'b0;
     reg rst_n = 1'b0;
-    reg force_stop = 1'b0;
-    reg disabled = 1'b0;
-    reg watchdog_timeout = 1'b0;
-    reg x_limit_raw = 1'b0;
-    reg y_limit_raw = 1'b0;
-    reg snapshot_valid = 1'b0;
-    reg [23:0] snapshot_targets = 24'd0;
-    reg [2:0] snapshot_busy_at_accept = 3'd0;
-    reg jog_valid = 1'b0;
+    reg jog_start = 1'b0;
     reg [1:0] jog_axis = 2'd0;
     reg [1:0] jog_axis = 2'd0;
     reg jog_dir = 1'b0;
     reg jog_dir = 1'b0;
-    reg [15:0] jog_steps = 16'd1;
-
-    wire [2:0] axis_active_mask;
-    wire [2:0] axis_busy_mask;
+    reg [15:0] jog_steps = 16'd2;
+    wire [1:0] axis_started_pulse;
     wire [2:0] step_out;
     wire [2:0] step_out;
-    wire en_n;
-    wire [79:0] status_payload;
+    wire [2:0] dir_out;
 
 
-    integer failures = 0;
-    integer guard;
+    integer started_events = 0;
 
 
     always #5 clk = ~clk;
     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 #(
     prod2u_p4_motor_hub #(
-        .STANDARD_STEPS(STANDARD_STEPS),
-        .LIMIT_CONFIRM_US(8),
-        .DIR_SETUP_US(3),
-        .SPEED0_HALF_US(2),
-        .SPEED1_HALF_US(2),
-        .SPEED2_HALF_US(2),
-        .SPEED3_HALF_US(2)
+        .DIR_SETUP_CYCLES(1),
+        .STEP_HALF_CYCLES(1)
     ) dut (
     ) dut (
-        .clk(clk),
-        .rst_n(rst_n),
-        .tick_1us(1'b1),
-        .force_stop(force_stop),
-        .disabled(disabled),
-        .watchdog_timeout(watchdog_timeout),
-        .x_limit_raw(x_limit_raw),
-        .y_limit_raw(y_limit_raw),
-        .snapshot_valid(snapshot_valid),
-        .snapshot_targets(snapshot_targets),
-        .snapshot_busy_at_accept(snapshot_busy_at_accept),
-        .snapshot_result_valid(),
-        .snapshot_busy_mask(),
-        .snapshot_invalid_mask(),
-        .snapshot_accepted_mask(),
-        .jog_valid(jog_valid),
-        .jog_axis(jog_axis),
-        .jog_dir(jog_dir),
-        .jog_speed_code(2'd3),
-        .jog_steps(jog_steps),
-        .jog_result_valid(),
-        .jog_accepted(),
-        .axis_active_mask(axis_active_mask),
-        .axis_busy_mask(axis_busy_mask),
-        .step_out(step_out),
-        .dir_out(),
-        .en_n(en_n),
-        .status_payload(status_payload)
+        .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 fail;
-        input [8*96-1:0] message;
-        begin
-            failures = failures + 1;
-            $display("MOTION_STATUS_FAIL: %0s payload=%020h", message,
-                status_payload);
-        end
-    endtask
-
-    task expect_status;
-        input [7:0] flags;
-        input [7:0] valid_mask;
-        input [7:0] busy_mask;
-        input [7:0] x_current;
-        input [7:0] y_current;
-        input [7:0] z_current;
-        input [7:0] x_target;
-        input [7:0] y_target;
-        input [7:0] z_target;
-        input [7:0] fault_mask;
-        input [8*72-1:0] label_text;
-        reg [79:0] expected;
-        begin
-            expected = {fault_mask, z_target, y_target, x_target,
-                z_current, y_current, x_current,
-                busy_mask, valid_mask, flags};
-            #1;
-            if (status_payload !== expected) begin
-                $display("STATUS_MISMATCH label=%0s actual=%020h expected=%020h",
-                    label_text, status_payload, expected);
-                fail(label_text);
-            end
-        end
-    endtask
-
-    task reset_hub;
-        begin
-            rst_n = 1'b0;
-            force_stop = 1'b0;
-            disabled = 1'b0;
-            watchdog_timeout = 1'b0;
-            x_limit_raw = 1'b0;
-            y_limit_raw = 1'b0;
-            snapshot_valid = 1'b0;
-            snapshot_busy_at_accept = 3'd0;
-            jog_valid = 1'b0;
-            repeat (4) @(negedge clk);
-            rst_n = 1'b1;
-            repeat (3) @(negedge clk);
-        end
-    endtask
-
-    task start_x_standard;
-        input [7:0] target;
-        begin
-            @(negedge clk);
-            snapshot_targets = {8'd50, 8'd50, target};
-            snapshot_busy_at_accept = 3'd0;
-            snapshot_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            snapshot_valid = 1'b0;
-        end
-    endtask
-
-    task start_x_jog;
-        input direction;
-        input [15:0] steps;
-        begin
-            @(negedge clk);
-            jog_axis = 2'd0;
-            jog_dir = direction;
-            jog_steps = steps;
-            jog_valid = 1'b1;
-            @(posedge clk);
-            #1;
-            @(negedge clk);
-            jog_valid = 1'b0;
-        end
-    endtask
-
-    task wait_idle;
-        begin
-            guard = 0;
-            while ((axis_active_mask != 3'b000) && guard < 2048) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (axis_active_mask != 3'b000 || axis_busy_mask != 3'b000) begin
-                fail("axis did not retire");
-            end
-        end
-    endtask
-
-    task wait_x_step;
-        begin
-            guard = 0;
-            while (!step_out[0] && guard < 256) begin
-                @(negedge clk);
-                guard = guard + 1;
-            end
-            if (!step_out[0]) fail("X did not emit first STEP");
-        end
-    endtask
-
     initial begin
     initial begin
-        reset_hub();
-        expect_status(8'h00, 8'h00, 8'h00,
-            8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'h00,
-            "reset unknown status");
-
-        start_x_standard(8'd100);
-        expect_status(8'h02, 8'h00, 8'h00,
-            8'hfe, 8'hff, 8'hff, 8'd100, 8'hff, 8'hff, 8'h00,
-            "standard OPEN setup status");
-        wait_x_step();
-        expect_status(8'h03, 8'h00, 8'h01,
-            8'hfe, 8'hff, 8'hff, 8'd100, 8'hff, 8'hff, 8'h00,
-            "standard OPEN first-STEP busy status");
-        wait_idle();
-        expect_status(8'h00, 8'h01, 8'h00,
-            8'd100, 8'hff, 8'hff, 8'd100, 8'hff, 8'hff, 8'h00,
-            "standard OPEN completion status");
-
-        start_x_standard(8'd0);
-        expect_status(8'h02, 8'h00, 8'h00,
-            8'hfe, 8'hff, 8'hff, 8'd0, 8'hff, 8'hff, 8'h00,
-            "standard CLOSE setup status");
-        wait_x_step();
-        expect_status(8'h03, 8'h00, 8'h01,
-            8'hfe, 8'hff, 8'hff, 8'd0, 8'hff, 8'hff, 8'h00,
-            "standard CLOSE first-STEP busy status");
-        wait_idle();
-        expect_status(8'h00, 8'h01, 8'h00,
-            8'd0, 8'hff, 8'hff, 8'd0, 8'hff, 8'hff, 8'h00,
-            "standard CLOSE completion status");
-
-        start_x_jog(1'b0, 16'd4);
-        expect_status(8'h02, 8'h00, 8'h00,
-            8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'h00,
-            "JOG setup unknown status");
-        wait_x_step();
-        expect_status(8'h03, 8'h00, 8'h01,
-            8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'h00,
-            "JOG first-STEP busy unknown status");
-        wait_idle();
-        expect_status(8'h00, 8'h00, 8'h00,
-            8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'h00,
-            "JOG completion unknown status");
-
-        start_x_jog(1'b1, 16'd8);
-        wait_x_step();
-        x_limit_raw = 1'b1;
-        wait_idle();
-        expect_status(8'h00, 8'h00, 8'h00,
-            8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'h00,
-            "limit-ignored JOG completion status");
-
-        reset_hub();
-        start_x_jog(1'b0, 16'd32);
-        disabled = 1'b1;
-        #1;
-        if (step_out != 3'b000 || !en_n) fail("DISABLE did not gate pins");
-        @(posedge clk);
-        #1;
-        expect_status(8'h04, 8'h00, 8'h00,
-            8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'h00,
-            "DISABLE status");
-
-        reset_hub();
-        start_x_jog(1'b0, 16'd32);
-        disabled = 1'b1;
-        watchdog_timeout = 1'b1;
-        #1;
-        if (step_out != 3'b000 || !en_n) fail("watchdog did not gate pins");
-        @(posedge clk);
-        #1;
-        expect_status(8'h0c, 8'h00, 8'h00,
-            8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'hff, 8'h00,
-            "watchdog timeout status");
-
-        if (failures != 0) begin
-            $fatal(1, "prod2u_p4_motor_status_payload_tb failures=%0d",
-                failures);
+        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
         end
         $display("PASS: prod2u_p4_motor_status_payload_tb");
         $display("PASS: prod2u_p4_motor_status_payload_tb");
         $finish;
         $finish;

+ 28 - 94
tests/sim/prod2u_p4_normal_v3_rx_tb.v

@@ -16,8 +16,6 @@ module prod2u_p4_normal_v3_rx_tb;
     wire [5:0] request_length;
     wire [5:0] request_length;
     wire [271:0] request_payload;
     wire [271:0] request_payload;
     wire [15:0] request_crc16;
     wire [15:0] request_crc16;
-    wire emergency_disable_valid;
-    wire [15:0] emergency_disable_crc16;
     wire [15:0] crc_error_count;
     wire [15:0] crc_error_count;
     wire [15:0] timeout_count;
     wire [15:0] timeout_count;
     wire [15:0] format_error_count;
     wire [15:0] format_error_count;
@@ -29,14 +27,13 @@ module prod2u_p4_normal_v3_rx_tb;
     reg [5:0] held_request_length;
     reg [5:0] held_request_length;
     reg [271:0] held_request_payload;
     reg [271:0] held_request_payload;
     reg [15:0] held_request_crc16;
     reg [15:0] held_request_crc16;
-    reg [15:0] disable_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;
     reg check_held_request;
-    reg bounded_send_completed;
     integer frame_length;
     integer frame_length;
     integer i;
     integer i;
     integer wait_cycles;
     integer wait_cycles;
-    integer emergency_pulse_count;
-    integer emergency_count_before;
     reg timeout_probe_valid;
     reg timeout_probe_valid;
     reg [7:0] timeout_probe_data;
     reg [7:0] timeout_probe_data;
     wire timeout1_probe_ready;
     wire timeout1_probe_ready;
@@ -59,8 +56,6 @@ module prod2u_p4_normal_v3_rx_tb;
         .request_length(request_length),
         .request_length(request_length),
         .request_payload(request_payload),
         .request_payload(request_payload),
         .request_crc16(request_crc16),
         .request_crc16(request_crc16),
-        .emergency_disable_valid(emergency_disable_valid),
-        .emergency_disable_crc16(emergency_disable_crc16),
         .crc_error_count(crc_error_count),
         .crc_error_count(crc_error_count),
         .timeout_count(timeout_count),
         .timeout_count(timeout_count),
         .format_error_count(format_error_count)
         .format_error_count(format_error_count)
@@ -81,8 +76,6 @@ module prod2u_p4_normal_v3_rx_tb;
         .request_length(),
         .request_length(),
         .request_payload(),
         .request_payload(),
         .request_crc16(),
         .request_crc16(),
-        .emergency_disable_valid(),
-        .emergency_disable_crc16(),
         .crc_error_count(),
         .crc_error_count(),
         .timeout_count(timeout1_probe_count),
         .timeout_count(timeout1_probe_count),
         .format_error_count()
         .format_error_count()
@@ -103,8 +96,6 @@ module prod2u_p4_normal_v3_rx_tb;
         .request_length(),
         .request_length(),
         .request_payload(),
         .request_payload(),
         .request_crc16(),
         .request_crc16(),
-        .emergency_disable_valid(),
-        .emergency_disable_crc16(),
         .crc_error_count(),
         .crc_error_count(),
         .timeout_count(timeout3_probe_count),
         .timeout_count(timeout3_probe_count),
         .format_error_count()
         .format_error_count()
@@ -116,11 +107,6 @@ module prod2u_p4_normal_v3_rx_tb;
     end
     end
 
 
     always @(posedge clk) begin
     always @(posedge clk) begin
-        if (!rst_n) begin
-            emergency_pulse_count <= 0;
-        end else if (emergency_disable_valid) begin
-            emergency_pulse_count <= emergency_pulse_count + 1;
-        end
         if (check_held_request &&
         if (check_held_request &&
             (!request_valid || request_type !== held_request_type ||
             (!request_valid || request_type !== held_request_type ||
              request_length !== held_request_length ||
              request_length !== held_request_length ||
@@ -256,23 +242,6 @@ module prod2u_p4_normal_v3_rx_tb;
         end
         end
     endtask
     endtask
 
 
-    task send_built_frame_bounded;
-        input integer timeout_cycles;
-        begin
-            bounded_send_completed = 1'b0;
-            fork : bounded_frame_send
-                begin
-                    send_built_frame();
-                    bounded_send_completed = 1'b1;
-                end
-                begin
-                    repeat (timeout_cycles) @(negedge clk);
-                end
-            join_any
-            disable bounded_frame_send;
-        end
-    endtask
-
     task expect_request;
     task expect_request;
         input [7:0] expected_type;
         input [7:0] expected_type;
         input [5:0] expected_length;
         input [5:0] expected_length;
@@ -332,8 +301,6 @@ module prod2u_p4_normal_v3_rx_tb;
         rx_data = 8'h00;
         rx_data = 8'h00;
         request_ready = 1'b1;
         request_ready = 1'b1;
         check_held_request = 1'b0;
         check_held_request = 1'b0;
-        bounded_send_completed = 1'b0;
-        emergency_pulse_count = 0;
         timeout_probe_valid = 1'b0;
         timeout_probe_valid = 1'b0;
         timeout_probe_data = 8'h00;
         timeout_probe_data = 8'h00;
         repeat (4) @(negedge clk);
         repeat (4) @(negedge clk);
@@ -405,18 +372,10 @@ module prod2u_p4_normal_v3_rx_tb;
         expect_request(HOST_CMD, 6'd4, expected_payload);
         expect_request(HOST_CMD, 6'd4, expected_payload);
 
 
         build_host_command(8'h26);
         build_host_command(8'h26);
+        expected_payload = 272'd0;
+        expected_payload[7:0] = 8'h26;
         send_built_frame();
         send_built_frame();
-        if (!emergency_disable_valid || request_valid ||
-            emergency_disable_crc16 !== {frame[frame_length - 1], frame[frame_length - 2]}) begin
-            $display("exact DISABLE did not produce one emergency event");
-            $fatal;
-        end
-        @(posedge clk);
-        #1;
-        if (emergency_disable_valid || request_valid) begin
-            $display("emergency DISABLE event did not clear after one cycle");
-            $fatal;
-        end
+        expect_request(HOST_CMD, 6'd4, expected_payload);
 
 
         build_motion_command(8'h35);
         build_motion_command(8'h35);
         expected_payload = 272'd0;
         expected_payload = 272'd0;
@@ -463,7 +422,7 @@ module prod2u_p4_normal_v3_rx_tb;
         count_before = crc_error_count;
         count_before = crc_error_count;
         send_built_frame();
         send_built_frame();
         repeat (3) @(negedge clk);
         repeat (3) @(negedge clk);
-        if (request_valid || emergency_disable_valid || crc_error_count !== count_before + 16'd1) begin
+        if (request_valid || crc_error_count !== count_before + 16'd1) begin
             $display("CRC rejection mismatch count=%0d valid=%0d", crc_error_count, request_valid);
             $display("CRC rejection mismatch count=%0d valid=%0d", crc_error_count, request_valid);
             $fatal;
             $fatal;
         end
         end
@@ -484,7 +443,7 @@ module prod2u_p4_normal_v3_rx_tb;
             $fatal;
             $fatal;
         end
         end
 
 
-        // A held ordinary request must not block or be overwritten by emergency DISABLE.
+        // The one-entry request buffer backpressures RX until the request retires.
         request_ready = 1'b0;
         request_ready = 1'b0;
         build_motion_command(8'h37);
         build_motion_command(8'h37);
         send_built_frame();
         send_built_frame();
@@ -501,60 +460,35 @@ module prod2u_p4_normal_v3_rx_tb;
         held_request_length = request_length;
         held_request_length = request_length;
         held_request_payload = request_payload;
         held_request_payload = request_payload;
         held_request_crc16 = request_crc16;
         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;
         check_held_request = 1'b1;
-        emergency_count_before = emergency_pulse_count;
-
-        build_host_command(8'h26);
-        disable_crc16 = {frame[frame_length - 1], frame[frame_length - 2]};
-        send_built_frame_bounded(256);
-        if (!bounded_send_completed) begin
-            $display("held ordinary request blocked first emergency DISABLE frame");
-            $fatal;
-        end
-        wait_cycles = 0;
-        while (!emergency_disable_valid && wait_cycles < 2) begin
-            @(negedge clk);
-            wait_cycles = wait_cycles + 1;
-        end
-        if (!emergency_disable_valid || emergency_disable_crc16 !== disable_crc16) begin
-            $display("first held-request DISABLE did not produce one correlated emergency pulse");
-            $fatal;
+        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 did not backpressure RX or changed parser counters");
+                $fatal;
+            end
         end
         end
         check_held_request = 1'b0;
         check_held_request = 1'b0;
+        request_ready = 1'b1;
         @(posedge clk);
         @(posedge clk);
         #1;
         #1;
-        if (emergency_pulse_count !== emergency_count_before + 1 || request_valid) begin
-            $display("first emergency DISABLE did not flush the held ordinary request");
-            $fatal;
-        end
-
-        send_built_frame_bounded(256);
-        if (!bounded_send_completed) begin
-            $display("held ordinary request blocked second emergency DISABLE frame");
-            $fatal;
-        end
-        wait_cycles = 0;
-        while (!emergency_disable_valid && wait_cycles < 2) begin
-            @(negedge clk);
-            wait_cycles = wait_cycles + 1;
-        end
-        if (!emergency_disable_valid || emergency_disable_crc16 !== disable_crc16) begin
-            $display("second held-request DISABLE did not produce one correlated emergency pulse");
-            $fatal;
-        end
-        @(posedge clk);
-        #1;
-        if (emergency_pulse_count !== emergency_count_before + 2 || request_valid) begin
-            $display("second emergency DISABLE pulse did not leave the parser flushed");
-            $fatal;
-        end
-
-        request_ready = 1'b1;
         if (request_valid || !rx_ready) begin
         if (request_valid || !rx_ready) begin
-            $display("emergency flush did not leave RX ready for the next frame");
+            $display("request handshake did not restore RX ready");
             $fatal;
             $fatal;
         end
         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");
         $display("PASS: prod2u_p4_normal_v3_rx_tb");
         $finish;
         $finish;
     end
     end

+ 41 - 1
tests/sim/prod2u_p4_normal_v3_top_tb.v

@@ -31,6 +31,7 @@ module prod2u_p4_normal_v3_top_tb;
     integer i;
     integer i;
     integer guard;
     integer guard;
     integer failures = 0;
     integer failures = 0;
+    integer x_rises = 0;
     reg [15:0] crc;
     reg [15:0] crc;
     reg [7:0] rx_frame_type;
     reg [7:0] rx_frame_type;
     reg [7:0] rx_payload_len;
     reg [7:0] rx_payload_len;
@@ -80,6 +81,10 @@ module prod2u_p4_normal_v3_top_tb;
         end
         end
     end
     end
 
 
+    always @(posedge x_step) begin
+        x_rises = x_rises + 1;
+    end
+
     function [15:0] crc16_byte;
     function [15:0] crc16_byte;
         input [15:0] crc_in;
         input [15:0] crc_in;
         input [7:0] data;
         input [7:0] data;
@@ -130,6 +135,27 @@ module prod2u_p4_normal_v3_top_tb;
         end
         end
     endtask
     endtask
 
 
+    task build_jog;
+        input [1:0] axis;
+        input direction;
+        input [1:0] speed_code;
+        input [15:0] steps;
+        begin
+            build_command(8'h11, 8, 8'h35);
+            request_frame[15] = {6'd0, axis};
+            request_frame[16] = {7'd0, direction};
+            request_frame[17] = {6'd0, speed_code};
+            request_frame[18] = steps[7:0];
+            request_frame[19] = steps[15:8];
+            crc = 16'hffff;
+            for (i = 2; i < 22; i = i + 1) begin
+                crc = crc16_byte(crc, request_frame[i]);
+            end
+            request_frame[22] = crc[7:0];
+            request_frame[23] = crc[15:8];
+        end
+    endtask
+
     task read_frame;
     task read_frame;
         integer frame_start;
         integer frame_start;
         integer frame_bytes;
         integer frame_bytes;
@@ -300,6 +326,20 @@ module prod2u_p4_normal_v3_top_tb;
             failures = failures + 1;
             failures = failures + 1;
         end
         end
 
 
+        // Motor movement is independent of disabled/watchdog and LS inputs.
+        x_limit_raw = 1'b1;
+        y_limit_raw = 1'b1;
+        build_jog(2'd0, 1'b1, 2'd3, 16'd1);
+        send_request();
+        expect_ack_without_trace(8'h35, 8'h00, 1'b1);
+        if (x_rises != 1 || motor_en_n !== 1'b0 || !dut.disabled) begin
+            $display("NO_GATES_TOP_FAIL rises=%0d en_n=%0d disabled=%0d",
+                x_rises, motor_en_n, dut.disabled);
+            failures = failures + 1;
+        end
+        wait (x_step === 1'b0);
+        expect_transaction_quiet(8'h35);
+
         build_command(8'h05, 4, 8'h24);
         build_command(8'h05, 4, 8'h24);
         send_request();
         send_request();
         expect_ack_without_trace(8'h24, 8'h00, 1'b1);
         expect_ack_without_trace(8'h24, 8'h00, 1'b1);
@@ -348,7 +388,7 @@ module prod2u_p4_normal_v3_top_tb;
         expect_ack_without_trace(8'h26, 8'h00, 1'b1);
         expect_ack_without_trace(8'h26, 8'h00, 1'b1);
         expect_transaction_quiet(8'h26);
         expect_transaction_quiet(8'h26);
 
 
-        if (!motor_en_n || x_step || y_step || z_step || solenoid_out) $fatal;
+        if (motor_en_n || x_step || y_step || z_step || solenoid_out) $fatal;
         if (!dut.disabled) $fatal;
         if (!dut.disabled) $fatal;
         if (failures != 0) begin
         if (failures != 0) begin
             $display("ACK_ONLY_CONTRACT_RED failures=%0d", failures);
             $display("ACK_ONLY_CONTRACT_RED failures=%0d", failures);

+ 13 - 21
tests/sim/prod2u_p4_production_defaults_tb.v

@@ -56,31 +56,23 @@ module prod2u_p4_production_defaults_tb;
     initial begin
     initial begin
         #1;
         #1;
         check_integer("watchdog seconds", dut.WATCHDOG_SECONDS, 5);
         check_integer("watchdog seconds", dut.WATCHDOG_SECONDS, 5);
-        check_integer("standard steps", dut.MOTOR_STANDARD_STEPS, 3200);
-        check_integer("limit confirm us", dut.MOTOR_LIMIT_CONFIRM_US, 1000);
-        check_integer("dir setup us", dut.MOTOR_DIR_SETUP_US, 1000);
-        check_integer("speed0 half us", dut.MOTOR_SPEED0_HALF_US, 25000);
-        check_integer("speed1 half us", dut.MOTOR_SPEED1_HALF_US, 12500);
-        check_integer("speed2 half us", dut.MOTOR_SPEED2_HALF_US, 5000);
-        check_integer("speed3 half us", dut.MOTOR_SPEED3_HALF_US, 500);
-
-        check_integer("core standard steps", dut.u_core.STANDARD_STEPS, 3200);
-        check_integer("core limit confirm", dut.u_core.LIMIT_CONFIRM_US, 1000);
-        check_integer("core dir setup", dut.u_core.DIR_SETUP_US, 1000);
-        check_integer("hub standard steps", dut.u_core.u_motors.STANDARD_STEPS, 3200);
-        check_integer("hub limit confirm", dut.u_core.u_motors.LIMIT_CONFIRM_US, 1000);
-        check_integer("hub dir setup", dut.u_core.u_motors.DIR_SETUP_US, 1000);
-        check_integer("X standard steps", dut.u_core.u_motors.u_x_axis.STANDARD_STEPS, 3200);
-        check_integer("Y standard steps", dut.u_core.u_motors.u_y_axis.STANDARD_STEPS, 3200);
-        check_integer("X sync stages", $bits(dut.u_core.u_motors.u_x_axis.limit_sync_pipe), 3);
-        check_integer("Y sync stages", $bits(dut.u_core.u_motors.u_y_axis.limit_sync_pipe), 3);
-        check_integer("X JOG counter bits", $bits(dut.u_core.u_motors.u_x_axis.remaining_steps_reg), 16);
-        check_integer("Y JOG counter bits", $bits(dut.u_core.u_motors.u_y_axis.remaining_steps_reg), 16);
+        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);
         wait (dut.sys_rst_n === 1'b1);
         repeat (4) @(posedge sys_clk);
         repeat (4) @(posedge sys_clk);
         #1;
         #1;
-        if (!motor_en_n || x_step || y_step || z_step ||
+        if (motor_en_n || x_step || y_step || z_step ||
             dut.disabled !== 1'b1 || dut.watchdog_timeout !== 1'b0) begin
             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",
             $display("DEFAULT_SAFE_FAIL en_n=%0d step=%0d%0d%0d disabled=%0d timeout=%0d",
                 motor_en_n, z_step, y_step, x_step,
                 motor_en_n, z_step, y_step, x_step,

+ 7 - 8
tests/unit/test_prod2u_p4_ack_only_host_contract.py

@@ -126,7 +126,7 @@ class Prod2UP4MinimalAckOnlyContractTests(unittest.TestCase):
             result_flags=0x08,
             result_flags=0x08,
         )
         )
         status_wire = protocol.build_motion_status(
         status_wire = protocol.build_motion_status(
-            flags=0,
+            flags=0x02,
             position_valid_mask=0,
             position_valid_mask=0,
             busy_mask=0,
             busy_mask=0,
             current_xyz=(0xFF, 0xFF, 0xFF),
             current_xyz=(0xFF, 0xFF, 0xFF),
@@ -185,22 +185,21 @@ class Prod2UP4MinimalAckOnlyContractTests(unittest.TestCase):
         self.assertEqual(decoded.steps, 65535)
         self.assertEqual(decoded.steps, 65535)
         self.assertEqual(protocol.decode_frame(maximum).payload[4:6], b"\xFF\xFF")
         self.assertEqual(protocol.decode_frame(maximum).payload[4:6], b"\xFF\xFF")
 
 
-    def test_partial_ack_preserves_solenoid_skip_bit_and_actual_state_hash(self) -> None:
+    def test_snapshot_ack_has_no_axis_acceptance_or_skip_bits(self) -> None:
         wire = protocol.build_host_ack(
         wire = protocol.build_host_ack(
             ok=True,
             ok=True,
             command=protocol.CommandId.SET_OUTPUT_SNAPSHOT,
             command=protocol.CommandId.SET_OUTPUT_SNAPSHOT,
-            status=protocol.StatusCode.PARTIAL,
-            detail=0x41,
+            status=protocol.StatusCode.OK,
+            detail=0,
             state_hash16=0xE177,
             state_hash16=0xE177,
-            result_flags=0x0D,
+            result_flags=0x01,
         )
         )
 
 
         ack = protocol.decode_host_ack(protocol.decode_frame(wire))
         ack = protocol.decode_host_ack(protocol.decode_frame(wire))
 
 
-        self.assertEqual(ack.detail & 0x40, 0x40)
-        self.assertEqual(ack.detail & 0x07, 0x01)
+        self.assertEqual(ack.detail, 0)
         self.assertEqual(ack.state_hash16, 0xE177)
         self.assertEqual(ack.state_hash16, 0xE177)
-        self.assertEqual(ack.result_flags, 0x0D)
+        self.assertEqual(ack.result_flags, 0x01)
 
 
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":

+ 5 - 3
tests/unit/test_prod2u_p4_cli_v3.py

@@ -123,7 +123,9 @@ class Prod2UP4CliV3Tests(unittest.TestCase):
         self.assertEqual(payload["status"], "pass")
         self.assertEqual(payload["status"], "pass")
         self.assertEqual(payload["profile"], "prod2u-p4-normal-actuator-binary921-v3")
         self.assertEqual(payload["profile"], "prod2u-p4-normal-actuator-binary921-v3")
         self.assertEqual(payload["jog_request_steps_max"], 65535)
         self.assertEqual(payload["jog_request_steps_max"], 65535)
-        self.assertEqual(payload["jog_actual_steps_cap"], 800)
+        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["hardware_opened"])
         self.assertFalse(payload["program_sram_attempted"])
         self.assertFalse(payload["program_sram_attempted"])
 
 
@@ -173,7 +175,7 @@ class Prod2UP4CliV3Tests(unittest.TestCase):
             result_flags=0x08,
             result_flags=0x08,
         )
         )
         status = protocol.build_motion_status(
         status = protocol.build_motion_status(
-            flags=0,
+            flags=0x02,
             position_valid_mask=0,
             position_valid_mask=0,
             busy_mask=0,
             busy_mask=0,
             current_xyz=(0xFF, 0xFF, 0xFF),
             current_xyz=(0xFF, 0xFF, 0xFF),
@@ -191,7 +193,7 @@ class Prod2UP4CliV3Tests(unittest.TestCase):
     def test_unexpected_first_frame_sends_one_disable_and_terminates(self) -> None:
     def test_unexpected_first_frame_sends_one_disable_and_terminates(self) -> None:
         request = protocol.build_host_command(command=protocol.CommandId.GET_STATUS)
         request = protocol.build_host_command(command=protocol.CommandId.GET_STATUS)
         unexpected = protocol.build_motion_status(
         unexpected = protocol.build_motion_status(
-            flags=0,
+            flags=0x02,
             position_valid_mask=0,
             position_valid_mask=0,
             busy_mask=0,
             busy_mask=0,
             current_xyz=(0xFF, 0xFF, 0xFF),
             current_xyz=(0xFF, 0xFF, 0xFF),

+ 579 - 57
tests/unit/test_prod2u_p4_harness.py

@@ -5,7 +5,9 @@ from __future__ import annotations
 
 
 import argparse
 import argparse
 import copy
 import copy
+import hashlib
 import json
 import json
+import re
 import subprocess
 import subprocess
 import tempfile
 import tempfile
 import unittest
 import unittest
@@ -41,6 +43,53 @@ EXPECTED_SOURCES = (
     "src/top/prod2u_p4_normal_v3_top.v",
     "src/top/prod2u_p4_normal_v3_top.v",
 )
 )
 
 
+REQUIRED_MOTOR_LIMIT_PINS = {
+    "motor_en_n": {"location": "A10", "direction": "OUTPUT", "pull_type": "NONE"},
+    "x_step": {"location": "C11", "direction": "OUTPUT", "pull_type": "NONE"},
+    "x_dir": {"location": "B12", "direction": "OUTPUT", "pull_type": "NONE"},
+    "y_step": {"location": "D15", "direction": "OUTPUT", "pull_type": "NONE"},
+    "y_dir": {"location": "H14", "direction": "OUTPUT", "pull_type": "NONE"},
+    "x_limit_raw": {"location": "B9", "direction": "INPUT", "pull_type": "PULLUP"},
+    "y_limit_raw": {"location": "A11", "direction": "INPUT", "pull_type": "PULLUP"},
+}
+
+UART_ONLY_CDC_REGISTERS = frozenset(
+    {
+        "u_uart_rx/rx_sync_pipe[0]",
+        "u_uart_rx/rx_sync_pipe[1]",
+    }
+)
+UART_ONLY_CDC_ENDPOINTS = frozenset({"u_uart_rx/rx_sync_pipe[0]"})
+
+
+def valid_io_rows() -> list[dict[str, str]]:
+    rows = [
+        {
+            "name": f"dummy_{index}",
+            "direction": "OUTPUT",
+            "location": f"DUMMY{index}",
+            "io_standard": "LVCMOS33",
+            "io_type": "PAD",
+            "drive_strength": "8",
+            "pull_type": "NONE",
+            "pack_reg": "NONE",
+            "diff_resistor": "NONE",
+        }
+        for index in range(41 - len(REQUIRED_MOTOR_LIMIT_PINS))
+    ]
+    template = rows[0]
+    rows.extend(
+        {
+            **template,
+            "name": name,
+            "location": expected["location"],
+            "direction": expected["direction"],
+            "pull_type": expected["pull_type"],
+        }
+        for name, expected in REQUIRED_MOTOR_LIMIT_PINS.items()
+    )
+    return rows
+
 
 
 def valid_resources() -> dict[str, object]:
 def valid_resources() -> dict[str, object]:
     return {
     return {
@@ -61,6 +110,11 @@ def valid_resources() -> dict[str, object]:
 
 
 def valid_td_receipt(bitstream: Path, *, commit: str = "a" * 40) -> dict[str, object]:
 def valid_td_receipt(bitstream: Path, *, commit: str = "a" * 40) -> dict[str, object]:
     digest = harness.sha256_file(bitstream)
     digest = harness.sha256_file(bitstream)
+    observed_pins = {
+        row["name"]: row
+        for row in valid_io_rows()
+        if row["name"] in REQUIRED_MOTOR_LIMIT_PINS
+    }
     return {
     return {
         "schema": harness.TD_RECEIPT_SCHEMA,
         "schema": harness.TD_RECEIPT_SCHEMA,
         "status": "pass",
         "status": "pass",
@@ -73,18 +127,7 @@ def valid_td_receipt(bitstream: Path, *, commit: str = "a" * 40) -> dict[str, ob
         "post_route_pin_gate": {
         "post_route_pin_gate": {
             "status": "pass",
             "status": "pass",
             "row_count": 41,
             "row_count": 41,
-            "observed": {
-                "x_limit_raw": {
-                    "location": "B9",
-                    "io_standard": "LVCMOS33",
-                    "pull_type": "PULLUP",
-                },
-                "y_limit_raw": {
-                    "location": "A11",
-                    "io_standard": "LVCMOS33",
-                    "pull_type": "PULLUP",
-                },
-            },
+            "observed": observed_pins,
         },
         },
         "binding_gate": {"status": "pass"},
         "binding_gate": {"status": "pass"},
         "timing_gate": {"status": "pass"},
         "timing_gate": {"status": "pass"},
@@ -114,7 +157,11 @@ def valid_td_receipt(bitstream: Path, *, commit: str = "a" * 40) -> dict[str, ob
             "log_has_error": False,
             "log_has_error": False,
             "critical_warning_count": 0,
             "critical_warning_count": 0,
         },
         },
-        "bitstream": {"path": str(bitstream), "size": bitstream.stat().st_size},
+        "bitstream": {
+            "path": str(bitstream),
+            "size": bitstream.stat().st_size,
+            "sha256": digest,
+        },
         "run_id": "1" * 32,
         "run_id": "1" * 32,
         "work_root": "C:/td-a",
         "work_root": "C:/td-a",
         "td_tool": {"sha256": "c" * 64},
         "td_tool": {"sha256": "c" * 64},
@@ -150,11 +197,168 @@ def valid_package_receipt(
         "commit": commit,
         "commit": commit,
         "bitstream_sha256": digest,
         "bitstream_sha256": digest,
         "package_dir": str(package),
         "package_dir": str(package),
+        "delivery_mode": "normal_dual_td",
+        "verification_complete": True,
+        "confirmation_td_present": True,
+        "validation_status": "pass",
+        "packaged_selftest_status": "pass",
         "failures": [],
         "failures": [],
         "selftest": {"status": "pass", "returncode": 0},
         "selftest": {"status": "pass", "returncode": 0},
     }
     }
 
 
 
 
+def materialize_valid_package(
+    package: Path,
+    *,
+    bitstream_bytes: bytes = b"package-final-gate",
+    commit: str = "a" * 40,
+) -> tuple[dict[str, object], dict[str, object], dict[str, object]]:
+    package.mkdir(parents=True)
+    bitstream = package / "fw.bit"
+    bitstream.write_bytes(bitstream_bytes)
+    digest = harness.sha256_file(bitstream)
+    primary = valid_td_receipt(bitstream, commit=commit)
+    confirmation = copy.deepcopy(primary)
+    confirmation["run_id"] = "2" * 32
+    confirmation["work_root"] = "C:/td-b"
+
+    for relative in harness.package_required_files(confirmation_td_present=True):
+        path = package / relative
+        path.parent.mkdir(parents=True, exist_ok=True)
+        if not path.exists():
+            path.write_text(f"fixture:{relative}\n", encoding="utf-8")
+
+    primary_path = package / "evidence" / "td-primary-receipt.json"
+    confirmation_path = package / "evidence" / "td-confirmation-receipt.json"
+    primary_path.write_text(json.dumps(primary), encoding="utf-8")
+    confirmation_path.write_text(json.dumps(confirmation), encoding="utf-8")
+    validation = {
+        "schema": "prod2u-p4-normal-v3-validation-summary-v1",
+        "commit": commit,
+        "bitstream_sha256": digest,
+        "delivery_mode": "normal_dual_td",
+        "verification_complete": True,
+        "confirmation_td_present": True,
+        "layers": {
+            name: {"status": "pass"}
+            for name in (
+                "python",
+                "icarus",
+                "verilator",
+                "cocotb",
+                "formal",
+                "td_primary",
+                "td_confirmation",
+                "td_primary_artifacts",
+                "td_confirmation_artifacts",
+                "td_confirmation_bitstream",
+                "td_confirmation_synthesis",
+                "td_confirmation_manifest",
+                "resource_primary",
+                "resource_confirmation",
+                "package_selftest",
+            )
+        },
+    }
+    validation_path = package / "evidence" / "validation-summary.json"
+    validation_path.write_text(json.dumps(validation), encoding="utf-8")
+    packaged_selftest_path = package / "evidence" / "package-selftest-result.json"
+    packaged_selftest_path.write_text(
+        json.dumps(
+            {
+                "schema": "prod2u-p4-normal-v3-package-selftest-result-v1",
+                "status": "pass",
+                "returncode": 0,
+            }
+        ),
+        encoding="utf-8",
+    )
+    info_path = package / "package-info.json"
+    actual_files = {
+        path.relative_to(package).as_posix(): harness.sha256_file(path)
+        for path in sorted(package.rglob("*"))
+        if path.is_file() and path not in {info_path, packaged_selftest_path}
+    }
+    info = {
+        "schema": "prod2u-p4-normal-v3-folder-package-info-v3",
+        "profile": harness.RUNTIME_PROFILE,
+        "commit": commit,
+        "bitstream_sha256": digest,
+        "delivery_mode": "normal_dual_td",
+        "verification_complete": True,
+        "confirmation_td_present": True,
+        "confirmation_bitstream_sha256": digest,
+        "td_receipt_sha256": harness.sha256_file(primary_path),
+        "confirmation_td_receipt_sha256": harness.sha256_file(confirmation_path),
+        "validation_summary_sha256": harness.sha256_file(validation_path),
+        "package_selftest_result_sha256": harness.sha256_file(packaged_selftest_path),
+        "synthesis_input_hash": primary["synthesis_input_hash"],
+        "confirmation_synthesis_input_hash": confirmation["synthesis_input_hash"],
+        "file_sha256": actual_files,
+    }
+    info_path.write_text(json.dumps(info), encoding="utf-8")
+    receipt = valid_package_receipt(package, digest=digest, commit=commit)
+    receipt.update(
+        {
+            "package_info_sha256": harness.sha256_file(info_path),
+            "td_receipt_sha256": harness.sha256_file(primary_path),
+            "confirmation_td_receipt_sha256": harness.sha256_file(confirmation_path),
+            "validation_summary_sha256": harness.sha256_file(validation_path),
+            "package_selftest_result_sha256": harness.sha256_file(packaged_selftest_path),
+            "package_file_sha256": actual_files,
+            "package_file_manifest_sha256": harness.canonical_sha256(actual_files),
+        }
+    )
+    return receipt, primary, confirmation
+
+
+def refresh_package_bindings(package: Path, receipt: dict[str, object]) -> None:
+    info_path = package / "package-info.json"
+    primary_path = package / "evidence" / "td-primary-receipt.json"
+    confirmation_path = package / "evidence" / "td-confirmation-receipt.json"
+    validation_path = package / "evidence" / "validation-summary.json"
+    packaged_selftest_path = package / "evidence" / "package-selftest-result.json"
+    info = json.loads(info_path.read_text(encoding="utf-8"))
+    info["td_receipt_sha256"] = harness.sha256_file(primary_path)
+    info["confirmation_td_receipt_sha256"] = (
+        harness.sha256_file(confirmation_path) if confirmation_path.is_file() else None
+    )
+    info["validation_summary_sha256"] = harness.sha256_file(validation_path)
+    info["package_selftest_result_sha256"] = harness.sha256_file(packaged_selftest_path)
+    actual_files = {
+        path.relative_to(package).as_posix(): harness.sha256_file(path)
+        for path in sorted(package.rglob("*"))
+        if path.is_file() and path not in {info_path, packaged_selftest_path}
+    }
+    info["file_sha256"] = actual_files
+    info_path.write_text(json.dumps(info), encoding="utf-8")
+    receipt.update(
+        {
+            "delivery_mode": info["delivery_mode"],
+            "verification_complete": info["verification_complete"],
+            "confirmation_td_present": info["confirmation_td_present"],
+            "package_info_sha256": harness.sha256_file(info_path),
+            "td_receipt_sha256": info["td_receipt_sha256"],
+            "confirmation_td_receipt_sha256": info[
+                "confirmation_td_receipt_sha256"
+            ],
+            "validation_summary_sha256": info["validation_summary_sha256"],
+            "package_selftest_result_sha256": info[
+                "package_selftest_result_sha256"
+            ],
+            "package_file_sha256": actual_files,
+            "package_file_manifest_sha256": harness.canonical_sha256(actual_files),
+        }
+    )
+
+
+def update_package_info(package: Path, **updates: object) -> None:
+    info_path = package / "package-info.json"
+    info = json.loads(info_path.read_text(encoding="utf-8"))
+    info.update(updates)
+    info_path.write_text(json.dumps(info), encoding="utf-8")
+
+
 class Prod2UP4HarnessTests(unittest.TestCase):
 class Prod2UP4HarnessTests(unittest.TestCase):
     def test_cdc_report_preserves_advisory_failures_and_source_only_paths(self) -> None:
     def test_cdc_report_preserves_advisory_failures_and_source_only_paths(self) -> None:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
@@ -193,6 +397,51 @@ class Prod2UP4HarnessTests(unittest.TestCase):
         )
         )
         self.assertIn("source_only_false_paths_used:host_uart_rx", gate["failures"])
         self.assertIn("source_only_false_paths_used:host_uart_rx", gate["failures"])
 
 
+    def test_cdc_gate_accepts_uart_only_synchronizers(self) -> None:
+        uart_only_report = {
+            "retained_sync_registers": sorted(UART_ONLY_CDC_REGISTERS),
+            "false_path_endpoints": sorted(UART_ONLY_CDC_ENDPOINTS),
+            "source_only_false_paths": [],
+            "structural_failures": [],
+        }
+        accepted = harness.structural_cdc_gate(
+            uart_only_report,
+            async_reg_count=2,
+            input_register_count=0,
+        )
+        self.assertEqual(accepted["status"], "pass", accepted["failures"])
+
+    def test_cdc_gate_rejects_legacy_limit_synchronizers(self) -> None:
+        legacy_registers = sorted(
+            UART_ONLY_CDC_REGISTERS
+            | {
+                "u_core/u_motors/u_x_axis/limit_sync_pipe[0]",
+                "u_core/u_motors/u_x_axis/limit_sync_pipe[1]",
+                "u_core/u_motors/u_x_axis/limit_sync_pipe[2]",
+                "u_core/u_motors/u_y_axis/limit_sync_pipe[0]",
+                "u_core/u_motors/u_y_axis/limit_sync_pipe[1]",
+                "u_core/u_motors/u_y_axis/limit_sync_pipe[2]",
+            }
+        )
+        legacy_report = {
+            "retained_sync_registers": legacy_registers,
+            "false_path_endpoints": sorted(
+                UART_ONLY_CDC_ENDPOINTS
+                | {
+                    "u_core/u_motors/u_x_axis/limit_sync_pipe[0]",
+                    "u_core/u_motors/u_y_axis/limit_sync_pipe[0]",
+                }
+            ),
+            "source_only_false_paths": [],
+            "structural_failures": [],
+        }
+        rejected = harness.structural_cdc_gate(
+            legacy_report,
+            async_reg_count=8,
+            input_register_count=0,
+        )
+        self.assertEqual(rejected["status"], "fail")
+
     def test_fsm_report_preserves_advisory_discovery_failures(self) -> None:
     def test_fsm_report_preserves_advisory_discovery_failures(self) -> None:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
             report_path = Path(temporary) / "fsm.rpt"
             report_path = Path(temporary) / "fsm.rpt"
@@ -224,6 +473,28 @@ class Prod2UP4HarnessTests(unittest.TestCase):
             gate["failures"],
             gate["failures"],
         )
         )
 
 
+    def test_fsm_gate_accepts_two_bit_simplified_axes(self) -> None:
+        accepted = harness.structural_fsm_gate(
+            {
+                "axes": {"x": 2, "y": 2},
+                "encodings": {"x": "sequential", "y": "sequential"},
+                "structural_failures": [],
+            },
+            syn_log="FSM_ENCODING_GATE_PASS=sequential",
+        )
+        self.assertEqual(accepted["status"], "pass", accepted["failures"])
+
+    def test_fsm_gate_rejects_legacy_three_bit_axes(self) -> None:
+        rejected = harness.structural_fsm_gate(
+            {
+                "axes": {"x": 3, "y": 3},
+                "encodings": {"x": "sequential", "y": "sequential"},
+                "structural_failures": [],
+            },
+            syn_log="FSM_ENCODING_GATE_PASS=sequential",
+        )
+        self.assertEqual(rejected["status"], "fail")
+
     def test_bitgen_eligibility_depends_only_on_successful_route(self) -> None:
     def test_bitgen_eligibility_depends_only_on_successful_route(self) -> None:
         self.assertTrue(
         self.assertTrue(
             harness.td_bitgen_eligible(
             harness.td_bitgen_eligible(
@@ -374,40 +645,101 @@ class Prod2UP4HarnessTests(unittest.TestCase):
         with self.assertRaisesRegex(ValueError, "outside the repository"):
         with self.assertRaisesRegex(ValueError, "outside the repository"):
             harness.resolve_report_file(ROOT / "receipt.json")
             harness.resolve_report_file(ROOT / "receipt.json")
 
 
-    def test_pin_binding_gate_requires_b9_a11_and_rejects_a5(self) -> None:
+    def test_pin_binding_gate_blocks_every_motor_and_limit_ball_mutation(self) -> None:
         evidence = harness.pin_binding_gate()
         evidence = harness.pin_binding_gate()
 
 
         self.assertEqual(evidence["status"], "pass", evidence["failures"])
         self.assertEqual(evidence["status"], "pass", evidence["failures"])
         self.assertEqual(evidence["pad_count"], 41)
         self.assertEqual(evidence["pad_count"], 41)
 
 
-    def test_post_route_pin_gate_requires_41_unique_rows_and_verified_limits(self) -> None:
-        rows = [
-            {
-                "name": f"dummy_{index}",
-                "direction": "Output",
-                "location": f"DUMMY{index}",
-                "io_standard": "LVCMOS33",
-                "io_type": "single",
-                "drive_strength": "8",
-                "pull_type": "NONE",
-                "pack_reg": "OFF",
-                "diff_resistor": "OFF",
-            }
-            for index in range(39)
-        ]
-        rows.extend(
-            [
-                {**rows[0], "name": "x_limit_raw", "location": "B9", "pull_type": "PULLUP"},
-                {**rows[0], "name": "y_limit_raw", "location": "A11", "pull_type": "PULLUP"},
-            ]
+        original = (ROOT / "constraints" / "prod2u_p4_normal_v3.adc").read_text(
+            encoding="ascii"
         )
         )
-        evidence = harness.post_route_pin_gate(rows)
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            temporary_root = Path(temporary)
+            constraints = temporary_root / "constraints"
+            constraints.mkdir()
+            target = constraints / "prod2u_p4_normal_v3.adc"
+            for signal, expected in REQUIRED_MOTOR_LIMIT_PINS.items():
+                with self.subTest(signal=signal):
+                    pattern = re.compile(
+                        rf"(set_pin_assignment\s+\{{\s*{re.escape(signal)}\s*\}}\s+"
+                        rf"\{{\s*LOCATION\s*=\s*){re.escape(expected['location'])}(;)"
+                    )
+                    mutated, count = pattern.subn(r"\1WRONG_BALL\2", original)
+                    self.assertEqual(count, 1)
+                    target.write_text(mutated, encoding="ascii")
+                    with mock.patch.object(harness, "ROOT", temporary_root):
+                        rejected = harness.pin_binding_gate()
+                    self.assertEqual(rejected["status"], "fail", rejected)
+
+            target.write_text(
+                original.replace("LOCATION = A10;", "LOCATION = A5;", 1),
+                encoding="ascii",
+            )
+            with mock.patch.object(harness, "ROOT", temporary_root):
+                forbidden = harness.pin_binding_gate()
+            self.assertEqual(forbidden["status"], "fail")
+            self.assertIn("forbidden_ball_assigned:A5", forbidden["failures"])
+
+    def test_post_route_pin_gate_blocks_motor_limit_a5_and_io_count_mutations(self) -> None:
+        rows = valid_io_rows()
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            report_path = Path(temporary) / "prod2u_p4_normal_v3_phy.area"
+            report_path.write_text(
+                "\n".join(
+                    [
+                        "Detailed IO Report",
+                        (
+                            "Name Direction Location IOStandard IOType "
+                            "DriveStrength PullType PackReg DiffResistor"
+                        ),
+                        *(
+                            " ".join(
+                                row[field]
+                                for field in (
+                                    "name",
+                                    "direction",
+                                    "location",
+                                    "io_standard",
+                                    "io_type",
+                                    "drive_strength",
+                                    "pull_type",
+                                    "pack_reg",
+                                    "diff_resistor",
+                                )
+                            )
+                            for row in rows
+                        ),
+                        "",
+                    ]
+                ),
+                encoding="ascii",
+            )
+            parsed_rows = harness.parse_td_io_report(report_path)
+
+        self.assertIsNotNone(parsed_rows)
+        assert parsed_rows is not None
+        self.assertEqual(len(parsed_rows), 41)
+        evidence = harness.post_route_pin_gate(parsed_rows)
         self.assertEqual(evidence["status"], "pass", evidence["failures"])
         self.assertEqual(evidence["status"], "pass", evidence["failures"])
 
 
-        rows[-1]["location"] = "A5"
-        rejected = harness.post_route_pin_gate(rows)
-        self.assertEqual(rejected["status"], "fail")
-        self.assertIn("forbidden_location_assigned:A5", rejected["failures"])
+        for signal in REQUIRED_MOTOR_LIMIT_PINS:
+            with self.subTest(signal=signal):
+                changed = copy.deepcopy(parsed_rows)
+                row = next(item for item in changed if item["name"] == signal)
+                row["location"] = "WRONG_BALL"
+                rejected = harness.post_route_pin_gate(changed)
+                self.assertEqual(rejected["status"], "fail", rejected)
+
+        forbidden_rows = copy.deepcopy(parsed_rows)
+        forbidden_rows[0]["location"] = "A5"
+        forbidden = harness.post_route_pin_gate(forbidden_rows)
+        self.assertEqual(forbidden["status"], "fail")
+        self.assertIn("forbidden_location_assigned:A5", forbidden["failures"])
+
+        missing_row = harness.post_route_pin_gate(parsed_rows[:-1])
+        self.assertEqual(missing_row["status"], "fail")
+        self.assertIn("io_row_count:40", missing_row["failures"])
 
 
     def test_structural_resource_gate_requires_all_bram_zero_dsp_zero_io_41(self) -> None:
     def test_structural_resource_gate_requires_all_bram_zero_dsp_zero_io_41(self) -> None:
         accepted = harness.structural_resource_gate(valid_resources())
         accepted = harness.structural_resource_gate(valid_resources())
@@ -442,6 +774,21 @@ class Prod2UP4HarnessTests(unittest.TestCase):
                 timing[field] = 0
                 timing[field] = 0
                 self.assertEqual(harness.timing_gate(timing)["status"], "fail")
                 self.assertEqual(harness.timing_gate(timing)["status"], "fail")
 
 
+    def test_td_bitstream_binding_requires_existing_hash_matching_file(self) -> None:
+        digest = "a" * 64
+        receipt = {
+            "bitstream_sha256": digest,
+            "bitstream": {
+                "path": str(ROOT.parent / "definitely-missing-final-gate.bit"),
+                "sha256": digest,
+            },
+        }
+
+        self.assertEqual(
+            harness.td_receipt_bitstream_binding_status(receipt),
+            "fail",
+        )
+
     def test_final_td_semantic_recheck_rejects_forged_pass_fields(self) -> None:
     def test_final_td_semantic_recheck_rejects_forged_pass_fields(self) -> None:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
             bitstream = Path(temporary) / "fw.bit"
             bitstream = Path(temporary) / "fw.bit"
@@ -466,6 +813,7 @@ class Prod2UP4HarnessTests(unittest.TestCase):
             mutations = {
             mutations = {
                 "timing": lambda value: value["timing"].__setitem__("worst_setup_slack_ns", 0),
                 "timing": lambda value: value["timing"].__setitem__("worst_setup_slack_ns", 0),
                 "pins": lambda value: value["post_route_pin_gate"]["observed"]["y_limit_raw"].__setitem__("location", "A5"),
                 "pins": lambda value: value["post_route_pin_gate"]["observed"]["y_limit_raw"].__setitem__("location", "A5"),
+                "motor_pin": lambda value: value["post_route_pin_gate"]["observed"]["x_step"].__setitem__("location", "WRONG_BALL"),
                 "source": lambda value: value["source_state"].__setitem__("clean", False),
                 "source": lambda value: value["source_state"].__setitem__("clean", False),
                 "phase": lambda value: value["phy"].__setitem__("status", "fail"),
                 "phase": lambda value: value["phy"].__setitem__("status", "fail"),
             }
             }
@@ -492,65 +840,225 @@ class Prod2UP4HarnessTests(unittest.TestCase):
     def test_final_package_semantic_recheck_binds_info_and_firmware_hash(self) -> None:
     def test_final_package_semantic_recheck_binds_info_and_firmware_hash(self) -> None:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
             package = Path(temporary) / "package"
             package = Path(temporary) / "package"
-            package.mkdir(parents=True)
-            bitstream = package / "fw.bit"
-            bitstream.write_bytes(b"package-final-gate")
-            digest = harness.sha256_file(bitstream)
-            info = {"commit": "a" * 40, "bitstream_sha256": digest}
-            (package / "package-info.json").write_text(json.dumps(info), encoding="utf-8")
-            receipt = valid_package_receipt(package, digest=digest)
+            receipt, _, _ = materialize_valid_package(package)
+            digest = str(receipt["bitstream_sha256"])
+            primary_sha = str(receipt["td_receipt_sha256"])
+            confirmation_sha = str(receipt["confirmation_td_receipt_sha256"])
 
 
             self.assertEqual(
             self.assertEqual(
                 harness._package_final_failures(
                 harness._package_final_failures(
                     receipt,
                     receipt,
                     expected_commit="a" * 40,
                     expected_commit="a" * 40,
                     expected_bitstream_sha256=digest,
                     expected_bitstream_sha256=digest,
+                    expected_primary_td_receipt_sha256=primary_sha,
+                    expected_confirmation_td_receipt_sha256=confirmation_sha,
                 ),
                 ),
                 [],
                 [],
             )
             )
 
 
+            info_path = package / "package-info.json"
+            info = json.loads(info_path.read_text(encoding="utf-8"))
             info["commit"] = "b" * 40
             info["commit"] = "b" * 40
-            (package / "package-info.json").write_text(json.dumps(info), encoding="utf-8")
+            info_path.write_text(json.dumps(info), encoding="utf-8")
             self.assertIn(
             self.assertIn(
                 "package:info_binding",
                 "package:info_binding",
                 harness._package_final_failures(
                 harness._package_final_failures(
                     receipt,
                     receipt,
                     expected_commit="a" * 40,
                     expected_commit="a" * 40,
                     expected_bitstream_sha256=digest,
                     expected_bitstream_sha256=digest,
+                    expected_primary_td_receipt_sha256=primary_sha,
+                    expected_confirmation_td_receipt_sha256=confirmation_sha,
                 ),
                 ),
             )
             )
             info["commit"] = "a" * 40
             info["commit"] = "a" * 40
-            (package / "package-info.json").write_text(json.dumps(info), encoding="utf-8")
-            bitstream.write_bytes(b"tampered")
+            info_path.write_text(json.dumps(info), encoding="utf-8")
+            (package / "fw.bit").write_bytes(b"tampered")
             self.assertIn(
             self.assertIn(
                 "package:file_hash",
                 "package:file_hash",
                 harness._package_final_failures(
                 harness._package_final_failures(
                     receipt,
                     receipt,
                     expected_commit="a" * 40,
                     expected_commit="a" * 40,
                     expected_bitstream_sha256=digest,
                     expected_bitstream_sha256=digest,
+                    expected_primary_td_receipt_sha256=primary_sha,
+                    expected_confirmation_td_receipt_sha256=confirmation_sha,
+                ),
+            )
+
+            incomplete = valid_package_receipt(package, digest=digest)
+            incomplete["verification_complete"] = False
+            self.assertIn(
+                "package:verification_incomplete",
+                harness._package_final_failures(
+                    incomplete,
+                    expected_commit="a" * 40,
+                    expected_bitstream_sha256=digest,
+                    expected_primary_td_receipt_sha256=primary_sha,
+                    expected_confirmation_td_receipt_sha256=confirmation_sha,
                 ),
                 ),
             )
             )
 
 
+    def test_final_package_rechecks_closed_normal_package_and_external_td_bindings(self) -> None:
+        mutations = (
+            ("urgent_receipt", "package:delivery_mode", lambda package, receipt: receipt.__setitem__("delivery_mode", "urgent_single_td")),
+            ("urgent_info", "package:info_delivery_mode", lambda package, receipt: update_package_info(package, delivery_mode="urgent_single_td")),
+            ("false_info_verification", "package:info_verification_incomplete", lambda package, receipt: update_package_info(package, verification_complete=False)),
+            ("false_info_confirmation", "package:info_confirmation_td_missing", lambda package, receipt: update_package_info(package, confirmation_td_present=False)),
+            ("missing_confirmation", "package:required_file", lambda package, receipt: (package / "evidence" / "td-confirmation-receipt.json").unlink()),
+            ("missing_validation", "package:required_file", lambda package, receipt: (package / "evidence" / "validation-summary.json").unlink()),
+            ("missing_selftest", "package:required_file", lambda package, receipt: (package / "evidence" / "package-selftest-result.json").unlink()),
+        )
+        for name, expected, mutate in mutations:
+            with self.subTest(name=name), tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+                package = Path(temporary) / "package"
+                receipt, _, _ = materialize_valid_package(package)
+                mutate(package, receipt)
+                failures = harness._package_final_failures(
+                    receipt,
+                    expected_commit="a" * 40,
+                    expected_bitstream_sha256=str(receipt["bitstream_sha256"]),
+                    expected_primary_td_receipt_sha256=str(receipt["td_receipt_sha256"]),
+                    expected_confirmation_td_receipt_sha256=str(
+                        receipt["confirmation_td_receipt_sha256"]
+                    ),
+                )
+                self.assertTrue(
+                    any(item.startswith(expected) for item in failures),
+                    failures,
+                )
+
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            package = Path(temporary) / "package"
+            receipt, _, _ = materialize_valid_package(package)
+            failures = harness._package_final_failures(
+                receipt,
+                expected_commit="a" * 40,
+                expected_bitstream_sha256=str(receipt["bitstream_sha256"]),
+                expected_primary_td_receipt_sha256="0" * 64,
+                expected_confirmation_td_receipt_sha256="1" * 64,
+            )
+            self.assertIn("package:primary_td_external_binding", failures)
+            self.assertIn("package:confirmation_td_external_binding", failures)
+
+    def test_package_validator_preserves_running_but_final_gate_rejects_it(self) -> None:
+        bitstream_bytes = b"running-validation-package"
+        digest = hashlib.sha256(bitstream_bytes).hexdigest()
+        commit = "a" * 40
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            package = (
+                Path(temporary)
+                / commit
+                / f"prod2u-p4-normal-{commit}-{digest[:16]}"
+            )
+            receipt, _, _ = materialize_valid_package(
+                package,
+                bitstream_bytes=bitstream_bytes,
+                commit=commit,
+            )
+            validation_path = package / "evidence" / "validation-summary.json"
+            validation = json.loads(validation_path.read_text(encoding="utf-8"))
+            validation["layers"]["td_confirmation"]["status"] = "running"
+            validation_path.write_text(json.dumps(validation), encoding="utf-8")
+            refresh_package_bindings(package, receipt)
+
+            completed = subprocess.CompletedProcess(
+                ["powershell.exe"], 0, stdout="selftest pass", stderr=""
+            )
+            with mock.patch.object(harness.subprocess, "run", return_value=completed):
+                observed = harness.package_selftest_payload(package)
+
+            self.assertEqual(observed["status"], "pass", observed["failures"])
+            self.assertEqual(observed["validation_status"], "running")
+            receipt.update(observed)
+            failures = harness._package_final_failures(
+                receipt,
+                expected_commit=commit,
+                expected_bitstream_sha256=digest,
+                expected_primary_td_receipt_sha256=str(receipt["td_receipt_sha256"]),
+                expected_confirmation_td_receipt_sha256=str(
+                    receipt["confirmation_td_receipt_sha256"]
+                ),
+            )
+            self.assertIn("package:validation_incomplete", failures)
+
+    def test_urgent_validator_allows_running_td_confirmation_only(self) -> None:
+        bitstream_bytes = b"urgent-running-confirmation"
+        digest = hashlib.sha256(bitstream_bytes).hexdigest()
+        commit = "a" * 40
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            package = (
+                Path(temporary)
+                / commit
+                / f"prod2u-p4-normal-{commit}-{digest[:16]}"
+            )
+            receipt, _, _ = materialize_valid_package(
+                package,
+                bitstream_bytes=bitstream_bytes,
+                commit=commit,
+            )
+            (package / "evidence" / "td-confirmation-receipt.json").unlink()
+            info_path = package / "package-info.json"
+            info = json.loads(info_path.read_text(encoding="utf-8"))
+            info.update(
+                {
+                    "delivery_mode": "urgent_single_td",
+                    "verification_complete": False,
+                    "confirmation_td_present": False,
+                    "confirmation_bitstream_sha256": None,
+                    "confirmation_synthesis_input_hash": None,
+                }
+            )
+            info_path.write_text(json.dumps(info), encoding="utf-8")
+            validation_path = package / "evidence" / "validation-summary.json"
+            validation = json.loads(validation_path.read_text(encoding="utf-8"))
+            validation.update(
+                {
+                    "delivery_mode": "urgent_single_td",
+                    "verification_complete": False,
+                    "confirmation_td_present": False,
+                }
+            )
+            validation["layers"]["td_confirmation"]["status"] = "running"
+            for name in (
+                "td_confirmation_artifacts",
+                "td_confirmation_bitstream",
+                "td_confirmation_synthesis",
+                "td_confirmation_manifest",
+                "resource_confirmation",
+            ):
+                validation["layers"][name]["status"] = "not_run"
+            validation_path.write_text(json.dumps(validation), encoding="utf-8")
+            refresh_package_bindings(package, receipt)
+
+            completed = subprocess.CompletedProcess(
+                ["powershell.exe"], 0, stdout="selftest pass", stderr=""
+            )
+            with mock.patch.object(harness.subprocess, "run", return_value=completed):
+                observed = harness.package_selftest_payload(package)
+
+            self.assertEqual(observed["status"], "pass", observed["failures"])
+            self.assertEqual(observed["validation_status"], "running")
+
     def test_final_gate_rejects_two_td_receipts_from_same_run_or_work_root(self) -> None:
     def test_final_gate_rejects_two_td_receipts_from_same_run_or_work_root(self) -> None:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
             root = Path(temporary)
             root = Path(temporary)
             bitstream = root / "td.bit"
             bitstream = root / "td.bit"
             bitstream.write_bytes(b"two-build-final-gate")
             bitstream.write_bytes(b"two-build-final-gate")
             digest = harness.sha256_file(bitstream)
             digest = harness.sha256_file(bitstream)
-            primary = valid_td_receipt(bitstream)
-            confirmation = copy.deepcopy(primary)
             package = root / "package"
             package = root / "package"
-            package.mkdir(parents=True)
-            (package / "fw.bit").write_bytes(bitstream.read_bytes())
-            (package / "package-info.json").write_text(
-                json.dumps({"commit": "a" * 40, "bitstream_sha256": digest}),
-                encoding="utf-8",
+            package_receipt, packaged_primary, packaged_confirmation = (
+                materialize_valid_package(
+                    package,
+                    bitstream_bytes=bitstream.read_bytes(),
+                )
             )
             )
+            primary = packaged_primary
+            confirmation = copy.deepcopy(packaged_primary)
+            packaged_confirmation = confirmation
             receipts = {
             receipts = {
                 "offline": valid_offline_receipt(),
                 "offline": valid_offline_receipt(),
                 "td": primary,
                 "td": primary,
                 "td_confirmation": confirmation,
                 "td_confirmation": confirmation,
-                "package": valid_package_receipt(package, digest=digest),
+                "package": package_receipt,
             }
             }
             paths = {}
             paths = {}
             for name, payload in receipts.items():
             for name, payload in receipts.items():
@@ -582,6 +1090,20 @@ class Prod2UP4HarnessTests(unittest.TestCase):
 
 
             confirmation["run_id"] = "2" * 32
             confirmation["run_id"] = "2" * 32
             confirmation["work_root"] = "C:/td-b"
             confirmation["work_root"] = "C:/td-b"
+            packaged_confirmation["run_id"] = confirmation["run_id"]
+            packaged_confirmation["work_root"] = confirmation["work_root"]
+            packaged_primary_path = package / "evidence" / "td-primary-receipt.json"
+            packaged_confirmation_path = (
+                package / "evidence" / "td-confirmation-receipt.json"
+            )
+            packaged_primary_path.write_text(
+                json.dumps(packaged_primary), encoding="utf-8"
+            )
+            packaged_confirmation_path.write_text(
+                json.dumps(packaged_confirmation), encoding="utf-8"
+            )
+            refresh_package_bindings(package, package_receipt)
+            paths["package"].write_text(json.dumps(package_receipt), encoding="utf-8")
             paths["td_confirmation"].write_text(json.dumps(confirmation), encoding="utf-8")
             paths["td_confirmation"].write_text(json.dumps(confirmation), encoding="utf-8")
             with (
             with (
                 mock.patch.object(
                 mock.patch.object(

+ 560 - 45
tests/unit/test_prod2u_p4_minimal_delivery_contract.py

@@ -38,6 +38,41 @@ PACKAGE_MACHINE_ARTIFACTS = {
         "config/prod2u_p4_verification_targets_v1.json"
         "config/prod2u_p4_verification_targets_v1.json"
     ),
     ),
 }
 }
+REQUIRED_PIN_LOCATIONS = {
+    "motor_en_n": "A10",
+    "x_step": "C11",
+    "x_dir": "B12",
+    "y_step": "D15",
+    "y_dir": "H14",
+    "x_limit_raw": "B9",
+    "y_limit_raw": "A11",
+}
+REQUIRED_PIN_BINDINGS = {
+    signal: {
+        "location": location,
+        "direction": "INPUT" if signal.endswith("limit_raw") else "OUTPUT",
+        "io_standard": "LVCMOS33",
+        "pull_type": "PULLUP" if signal.endswith("limit_raw") else "NONE",
+    }
+    for signal, location in REQUIRED_PIN_LOCATIONS.items()
+}
+EXPECTED_VALIDATION_LAYERS = {
+    "python",
+    "icarus",
+    "verilator",
+    "cocotb",
+    "formal",
+    "td_primary",
+    "td_confirmation",
+    "td_primary_artifacts",
+    "td_confirmation_artifacts",
+    "td_confirmation_bitstream",
+    "td_confirmation_synthesis",
+    "td_confirmation_manifest",
+    "resource_primary",
+    "resource_confirmation",
+    "package_selftest",
+}
 PACKAGE_CONTRACT_INPUTS = (
 PACKAGE_CONTRACT_INPUTS = (
     ROOT / "tools" / f"package_{STEM}.ps1",
     ROOT / "tools" / f"package_{STEM}.ps1",
     ROOT / "config" / "prod2u_p4_normal_host_contract_v4.json",
     ROOT / "config" / "prod2u_p4_normal_host_contract_v4.json",
@@ -69,6 +104,10 @@ def _git(repo: Path, *arguments: str) -> str:
     ).stdout.strip()
     ).stdout.strip()
 
 
 
 
+def _ps_literal(value: object) -> str:
+    return "'" + str(value).replace("'", "''") + "'"
+
+
 def _copy_active_source(destination: Path) -> None:
 def _copy_active_source(destination: Path) -> None:
     ignored_names = {
     ignored_names = {
         ".git",
         ".git",
@@ -128,10 +167,46 @@ def _build_package(
     confirmation_commit: str | None = None,
     confirmation_commit: str | None = None,
     confirmation_image: bytes | None = None,
     confirmation_image: bytes | None = None,
     selftest_fails: bool = False,
     selftest_fails: bool = False,
+    urgent_single_td: bool = False,
+    include_confirmation: bool = True,
+    bitstream_bytes: bytes = b"minimal-normal-v3-package-contract",
+    primary_commit: str | None = None,
+    primary_hash: str | None = None,
+    primary_pin_overrides: dict[str, str] | None = None,
+    primary_pin_field_overrides: dict[str, dict[str, str]] | None = None,
+    primary_pin_row_count: int = 41,
+    primary_pin_failures: list[str] | None = None,
+    primary_schema: str = "prod2u-p4-normal-v3-td-build-receipt-v2",
+    primary_status: str = "fail",
+    primary_source_clean: bool = True,
+    primary_source_commit: str | None = None,
+    primary_source_binding_status: str = "pass",
+    primary_synthesis_hash: str = "1" * 64,
+    primary_manifest_hash: str | None = None,
+    primary_bitstream_artifact: bool = True,
+    primary_bitstream_artifact_hash: str | None = None,
+    primary_bitstream_artifact_path: str | None = None,
+    primary_resource_status: str = "fail",
+    confirmation_status: str = "blocked_license",
+    validation_statuses: tuple[str, ...] = ("fail",),
+    running_validation_layers: tuple[str, ...] = (),
+    dirty_source: bool = False,
+    untracked_source: bool = False,
 ) -> tuple[Path, str, str]:
 ) -> tuple[Path, str, str]:
     source, commit = _create_clean_package_fixture(root, selftest_fails=selftest_fails)
     source, commit = _create_clean_package_fixture(root, selftest_fails=selftest_fails)
+    if dirty_source:
+        package_script = source / "tools" / f"package_{STEM}.ps1"
+        package_script.write_text(
+            package_script.read_text(encoding="utf-8") + "\n# dirty source fixture\n",
+            encoding="utf-8",
+        )
+    if untracked_source:
+        (source / "tools" / "untracked-package-fixture.ps1").write_text(
+            "# untracked source fixture\n",
+            encoding="utf-8",
+        )
     bitstream = root / "normal.bit"
     bitstream = root / "normal.bit"
-    bitstream.write_bytes(b"minimal-normal-v3-package-contract")
+    bitstream.write_bytes(bitstream_bytes)
     bitstream_sha256 = hashlib.sha256(bitstream.read_bytes()).hexdigest()
     bitstream_sha256 = hashlib.sha256(bitstream.read_bytes()).hexdigest()
     td_primary_dir = root / "td-primary"
     td_primary_dir = root / "td-primary"
     td_confirmation_dir = root / "td-confirmation"
     td_confirmation_dir = root / "td-confirmation"
@@ -156,23 +231,50 @@ def _build_package(
         confirmation_bitstream_sha256 = hashlib.sha256(confirmation_image).hexdigest()
         confirmation_bitstream_sha256 = hashlib.sha256(confirmation_image).hexdigest()
 
 
     td_primary = root / "td-primary-receipt.json"
     td_primary = root / "td-primary-receipt.json"
+    primary_pins = {
+        signal: dict(binding) for signal, binding in REQUIRED_PIN_BINDINGS.items()
+    }
+    for signal, location in (primary_pin_overrides or {}).items():
+        primary_pins[signal]["location"] = location
+    for signal, overrides in (primary_pin_field_overrides or {}).items():
+        primary_pins[signal].update(overrides)
+    primary_artifact = _artifact(bitstream)
+    if primary_bitstream_artifact_hash is not None:
+        primary_artifact["sha256"] = primary_bitstream_artifact_hash
+    if primary_bitstream_artifact_path is not None:
+        primary_artifact["path"] = primary_bitstream_artifact_path
+    manifest_hash = primary_manifest_hash or primary_synthesis_hash
     td_primary.write_text(
     td_primary.write_text(
         json.dumps(
         json.dumps(
             {
             {
-                "schema": "prod2u-p4-normal-v3-td-build-receipt-v2",
-                "status": "fail",
-                "commit": commit,
-                "bitstream_sha256": bitstream_sha256,
-                "synthesis_input_hash": "1" * 64,
-                "synthesis_input_manifest": {"sha256": "1" * 64, "inputs": {}},
+                "schema": primary_schema,
+                "status": primary_status,
+                "commit": primary_commit or commit,
+                "source_state": {
+                    "clean": primary_source_clean,
+                    "commit": primary_source_commit or commit,
+                },
+                "source_binding_gate": {"status": primary_source_binding_status},
+                "binding_gate": {"status": "pass"},
+                "bitstream_sha256": primary_hash or bitstream_sha256,
+                "bitstream": primary_artifact if primary_bitstream_artifact else None,
+                "synthesis_input_hash": primary_synthesis_hash,
+                "synthesis_input_manifest": {
+                    "sha256": manifest_hash,
+                    "inputs": {"src/top/prod2u_p4_normal_v3_top.v": "2" * 64},
+                },
                 "run_id": "1" * 32,
                 "run_id": "1" * 32,
                 "work_root": str(td_primary_dir),
                 "work_root": str(td_primary_dir),
                 "post_route_pin_gate": {
                 "post_route_pin_gate": {
-                    "status": "pass",
-                    "observed": {"x_limit_raw": {"location": "B9"}},
+                    "status": "pass" if not primary_pin_failures else "fail",
+                    "row_count": primary_pin_row_count,
+                    "observed": primary_pins,
+                    "failures": list(primary_pin_failures or []),
                 },
                 },
+                "resource_gate": {"status": primary_resource_status},
                 "measurement_artifacts": {
                 "measurement_artifacts": {
-                    name: _artifact(path) for name, path in primary_reports.items()
+                    **{name: _artifact(path) for name, path in primary_reports.items()},
+                    **({"bitstream": primary_artifact} if primary_bitstream_artifact else {}),
                 },
                 },
             }
             }
         ),
         ),
@@ -183,7 +285,7 @@ def _build_package(
         json.dumps(
         json.dumps(
             {
             {
                 "schema": "prod2u-p4-normal-v3-td-build-receipt-v2",
                 "schema": "prod2u-p4-normal-v3-td-build-receipt-v2",
-                "status": "blocked_license",
+                "status": confirmation_status,
                 "commit": confirmation_commit or commit,
                 "commit": confirmation_commit or commit,
                 "bitstream_sha256": confirmation_bitstream_sha256,
                 "bitstream_sha256": confirmation_bitstream_sha256,
                 "bitstream": (
                 "bitstream": (
@@ -192,12 +294,17 @@ def _build_package(
                     else None
                     else None
                 ),
                 ),
                 "synthesis_input_hash": "1" * 64,
                 "synthesis_input_hash": "1" * 64,
-                "synthesis_input_manifest": {"sha256": "1" * 64, "inputs": {}},
+                "synthesis_input_manifest": {
+                    "sha256": "1" * 64,
+                    "inputs": {"src/top/prod2u_p4_normal_v3_top.v": "2" * 64},
+                },
                 "run_id": "2" * 32,
                 "run_id": "2" * 32,
                 "work_root": str(td_confirmation_dir),
                 "work_root": str(td_confirmation_dir),
                 "post_route_pin_gate": {
                 "post_route_pin_gate": {
                     "status": "pass",
                     "status": "pass",
-                    "observed": {"y_limit_raw": {"location": "A11"}},
+                    "row_count": 41,
+                    "observed": REQUIRED_PIN_BINDINGS,
+                    "failures": [],
                 },
                 },
                 "measurement_artifacts": {
                 "measurement_artifacts": {
                     **{name: _artifact(path) for name, path in confirmation_reports.items()},
                     **{name: _artifact(path) for name, path in confirmation_reports.items()},
@@ -211,46 +318,67 @@ def _build_package(
         ),
         ),
         encoding="utf-8",
         encoding="utf-8",
     )
     )
-    validation_receipt = root / "formal-receipt.json"
-    validation_receipt.write_text(
-        json.dumps(
-            {
-                "schema": "prod2u-p4-normal-v3-formal-receipt-v1",
-                "verification_layer": "formal",
-                "status": "fail",
-                "failures": ["fixture_failure"],
-            }
-        ),
-        encoding="utf-8",
-    )
+    validation_receipts = []
+    for index, status in enumerate(validation_statuses, start=1):
+        validation_receipt = root / f"formal-receipt-{index}.json"
+        validation_receipt.write_text(
+            json.dumps(
+                {
+                    "schema": "prod2u-p4-normal-v3-formal-receipt-v1",
+                    "verification_layer": "formal",
+                    "status": status,
+                    "commit": commit,
+                    "failures": [] if status == "pass" else ["fixture_failure"],
+                }
+            ),
+            encoding="utf-8",
+        )
+        validation_receipts.append(validation_receipt)
     wheelhouse = root / "wheelhouse"
     wheelhouse = root / "wheelhouse"
     wheelhouse.mkdir()
     wheelhouse.mkdir()
     (wheelhouse / "pyserial-3.5-py2.py3-none-any.whl").write_bytes(b"fixture")
     (wheelhouse / "pyserial-3.5-py2.py3-none-any.whl").write_bytes(b"fixture")
     output = root / "out"
     output = root / "out"
+    validation_array = "@(" + ",".join(
+        _ps_literal(path) for path in validation_receipts
+    ) + ")"
+    running_array = "@(" + ",".join(
+        _ps_literal(layer) for layer in running_validation_layers
+    ) + ")"
+    invocation = root / "invoke-package.ps1"
+    invocation.write_text(
+        "$ErrorActionPreference = 'Stop'\n"
+        + "& " + _ps_literal(source / "tools" / f"package_{STEM}.ps1") + " `\n"
+        + "    -OutputDir " + _ps_literal(output) + " `\n"
+        + "    -NormalBitstream " + _ps_literal(bitstream) + " `\n"
+        + "    -TdReceipt " + _ps_literal(td_primary) + " `\n"
+        + "    -ConfirmationTdReceipt "
+        + _ps_literal(td_confirmation if include_confirmation else "")
+        + " `\n"
+        + "    -ValidationReceipt " + validation_array + " `\n"
+        + "    -WheelhouseRoot " + _ps_literal(wheelhouse)
+        + (" `\n    -UrgentSingleTd" if urgent_single_td else "")
+        + (
+            " `\n    -RunningValidationLayer " + running_array
+            if running_validation_layers
+            else ""
+        )
+        + "\nexit 0\n",
+        encoding="utf-8",
+    )
+    command = [
+        "powershell.exe",
+        "-NoProfile",
+        "-ExecutionPolicy",
+        "Bypass",
+        "-File",
+        str(invocation),
+    ]
     completed = subprocess.run(
     completed = subprocess.run(
-        [
-            "powershell.exe",
-            "-NoProfile",
-            "-ExecutionPolicy",
-            "Bypass",
-            "-File",
-            str(source / "tools" / f"package_{STEM}.ps1"),
-            "-OutputDir",
-            str(output),
-            "-NormalBitstream",
-            str(bitstream),
-            "-TdReceipt",
-            str(td_primary),
-            "-ConfirmationTdReceipt",
-            str(td_confirmation),
-            "-ValidationReceipt",
-            str(validation_receipt),
-            "-WheelhouseRoot",
-            str(wheelhouse),
-        ],
+        command,
         cwd=source,
         cwd=source,
         capture_output=True,
         capture_output=True,
         text=True,
         text=True,
+        timeout=30,
         check=False,
         check=False,
     )
     )
     if completed.returncode != 0:
     if completed.returncode != 0:
@@ -263,6 +391,74 @@ def _build_package(
 
 
 
 
 class Prod2UP4MinimalDeliveryContractTests(unittest.TestCase):
 class Prod2UP4MinimalDeliveryContractTests(unittest.TestCase):
+    def test_root_readme_tombstones_standard_motion_800_cap_and_busy_telemetry(self) -> None:
+        readme = (ROOT / "README.zh-CN.md").read_text(encoding="utf-8")
+
+        for obsolete in (
+            "标准 OPEN/CLOSE 每次固定 3200 步",
+            "每条只实际执行 `min(steps, 800)`",
+            "对外 busy 只在首个实际 STEP",
+        ):
+            self.assertNotIn(obsolete, readme)
+        for required in (
+            "只有 `0x35 JOG` 能驱动电机",
+            "超过 800 步的请求也会完整执行",
+            "合法 X/Y JOG 永不返回 BUSY",
+            "Snapshot",
+            "任意 `u8`",
+        ):
+            self.assertIn(required, readme)
+
+    def test_runbook_has_four_800_step_hex_and_ack_ordered_xy_example(self) -> None:
+        runbook = (ROOT / "docs" / "prod2u-p4-normal-v3-runbook.zh-CN.md").read_text(
+            encoding="utf-8"
+        )
+        jog_hex = {
+            "X JOG 打开,speed=3,800 步": "A55A02041100000000000000000835000003200300005E70",
+            "X JOG 关闭,speed=3,800 步": "A55A0204110000000000000000083500010320030000FE35",
+            "Y JOG 打开,speed=3,800 步": "A55A02041100000000000000000835010003200300003FC8",
+            "Y JOG 关闭,speed=3,800 步": "A55A02041100000000000000000835010103200300009F8D",
+        }
+        for label, wire_hex in jog_hex.items():
+            with self.subTest(label=label):
+                self.assertIn(label, runbook)
+                self.assertIn(wire_hex, runbook)
+
+        heading = runbook.index("X ACK 后启动 Y")
+        x_command = runbook.index(
+            "powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\\SEND_HEX.ps1 -Port COM5 -Baud 921600 -Hex 'A55A02041100000000000000000835000003200300005E70'",
+            heading,
+        )
+        ack_notice = runbook.index("HOST_ACK", x_command)
+        y_command = runbook.index(
+            "powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\\SEND_HEX.ps1 -Port COM5 -Baud 921600 -Hex 'A55A02041100000000000000000835010003200300003FC8'",
+            ack_notice,
+        )
+        self.assertLess(x_command, ack_notice)
+        self.assertLess(ack_notice, y_command)
+
+    def test_initialize_disable_template_is_ascii_and_warns_it_cannot_stop_jog(self) -> None:
+        initialize = ROOT / "tools" / "package_templates" / "INITIALIZE_DISABLE.ps1"
+        source = initialize.read_bytes().decode("ascii")
+
+        self.assertRegex(source, r"(?i)DANGER")
+        self.assertRegex(source, r"(?i)DISABLE[^\r\n]*DOES NOT STOP[^\r\n]*JOG")
+        self.assertRegex(source, r"(?i)(?:RESET|POWER-OFF|RECONFIGUR)[^\r\n]*STOP")
+
+    def test_retired_standard_axis_testbench_is_absent(self) -> None:
+        retired = ROOT / "tests" / "sim" / "prod2u_p4_axis_minimal_standard_tb.v"
+        manifest = json.loads(
+            (ROOT / "config" / "prod2u_p4_verification_targets_v1.json").read_text(
+                encoding="utf-8"
+            )
+        )
+
+        self.assertFalse(retired.exists())
+        self.assertNotIn(
+            "prod2u_p4_axis_minimal_standard_tb",
+            manifest["layers"]["icarus"],
+        )
+
     def test_version_one_docs_describe_force_jog_without_limit_protection(self) -> None:
     def test_version_one_docs_describe_force_jog_without_limit_protection(self) -> None:
         runbook = (ROOT / "docs" / "prod2u-p4-normal-v3-runbook.zh-CN.md").read_text(
         runbook = (ROOT / "docs" / "prod2u-p4-normal-v3-runbook.zh-CN.md").read_text(
             encoding="utf-8"
             encoding="utf-8"
@@ -463,6 +659,325 @@ class Prod2UP4MinimalDeliveryContractTests(unittest.TestCase):
         self.assertIsNone(harness_receipt["confirmation_bitstream_sha256"])
         self.assertIsNone(harness_receipt["confirmation_bitstream_sha256"])
         self.assertEqual(harness_receipt["confirmation_synthesis_input_hash"], "1" * 64)
         self.assertEqual(harness_receipt["confirmation_synthesis_input_hash"], "1" * 64)
 
 
+    def test_packaged_risk_notice_describes_first_step_ack_jog_only_motion(self) -> None:
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            package, _commit, _digest = _build_package(Path(temporary))
+            risk_notice = (package / "README.zh-CN.md").read_text(encoding="utf-8")
+
+        required_risks = {
+            "disable_does_not_stop": r"(?i)DISABLE[^。;\r\n]{0,24}(?:不能|不会|不再|不负责|不参与)[^。;\r\n]{0,24}(?:停止|中止|终止|打断)",
+            "watchdog_does_not_stop": r"(?i)watchdog[^。;\r\n]{0,24}(?:不能|不会|不再|不负责|不参与)[^。;\r\n]{0,24}(?:停止|中止|终止|打断)",
+            "limit_does_not_stop": r"(?i)(?:LS|限位)[^。;\r\n]{0,24}(?:不能|不会|不再|不负责|不参与)[^。;\r\n]{0,24}(?:停止|中止|终止|打断)",
+            "over_800_executes_fully": r"(?im)^(?=[^\r\n]*(?:(?:超过|大于)\s*800\s*步|>\s*800))(?=[^\r\n]*(?:完整|全部))(?=[^\r\n]*执行)[^\r\n]+$",
+            "speed_is_ignored": r"(?im)^(?=[^\r\n]*speed)(?=[^\r\n]*(?:忽略|不使用|无效))[^\r\n]+$",
+            "first_step_ack": r"(?im)^(?=[^\r\n]*(?:首个|第一)[^\r\n]*STEP)(?=[^\r\n]*ACK)[^\r\n]+$",
+            "snapshot_xy_no_motor_effect": r"(?im)^(?=[^\r\n]*snapshot)(?=[^\r\n]*X/Y)(?=[^\r\n]*(?:不驱动|不产生|无[^\r\n]*作用|忽略))[^\r\n]+$",
+            "power_or_reset_stops_motion": r"(?im)^(?=[^\r\n]*(?:断电|掉电|power))(?=[^\r\n]*(?:复位|reset))(?=[^\r\n]*(?:停止|中止|终止))[^\r\n]+$",
+        }
+        for name, pattern in required_risks.items():
+            with self.subTest(risk=name):
+                self.assertRegex(risk_notice, pattern)
+
+    def test_urgent_single_td_packages_primary_image_without_confirmation(self) -> None:
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            package, commit, bitstream_sha256 = _build_package(
+                Path(temporary),
+                urgent_single_td=True,
+                include_confirmation=False,
+            )
+            info = json.loads((package / "package-info.json").read_text(encoding="utf-8"))
+            validation = json.loads(
+                (package / "evidence" / "validation-summary.json").read_text(
+                    encoding="utf-8"
+                )
+            )
+            selftest = subprocess.run(
+                [
+                    "powershell.exe",
+                    "-NoProfile",
+                    "-ExecutionPolicy",
+                    "Bypass",
+                    "-File",
+                    str(package / "selftest.ps1"),
+                ],
+                cwd=package,
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+            harness_receipt = harness.package_selftest_payload(package)
+
+        self.assertEqual(info["commit"], commit)
+        self.assertEqual(info["bitstream_sha256"], bitstream_sha256)
+        self.assertEqual(info["delivery_mode"], "urgent_single_td")
+        self.assertFalse(info["verification_complete"])
+        self.assertFalse(info["confirmation_td_present"])
+        self.assertIsNone(info["confirmation_bitstream_sha256"])
+        self.assertFalse((package / "evidence" / "td-confirmation-receipt.json").exists())
+        self.assertEqual(validation["delivery_mode"], "urgent_single_td")
+        self.assertFalse(validation["verification_complete"])
+        self.assertFalse(validation["confirmation_td_present"])
+        self.assertEqual(validation["layers"]["td_primary"]["status"], "fail")
+        self.assertEqual(validation["layers"]["formal"]["status"], "fail")
+        for layer in (
+            "td_confirmation",
+            "td_confirmation_artifacts",
+            "td_confirmation_bitstream",
+            "td_confirmation_synthesis",
+            "td_confirmation_manifest",
+            "resource_confirmation",
+        ):
+            self.assertEqual(validation["layers"][layer]["status"], "not_run")
+        self.assertEqual(selftest.returncode, 0, selftest.stdout + selftest.stderr)
+        self.assertEqual(harness_receipt["status"], "pass", harness_receipt["failures"])
+        self.assertEqual(harness_receipt["delivery_mode"], "urgent_single_td")
+        self.assertFalse(harness_receipt["verification_complete"])
+        self.assertFalse(harness_receipt["confirmation_td_present"])
+
+    def test_urgent_single_td_rejects_missing_primary_integrity_requirements(self) -> None:
+        cases = (
+            ("empty bitstream", {"bitstream_bytes": b""}, "bitstream"),
+            ("receipt schema", {"primary_schema": "legacy-receipt"}, "schema"),
+            ("commit mismatch", {"primary_commit": "f" * 40}, "commit"),
+            ("hash mismatch", {"primary_hash": "0" * 64}, "hash"),
+            (
+                "dirty receipt source",
+                {"primary_source_clean": False},
+                "source state",
+            ),
+            (
+                "receipt source commit",
+                {"primary_source_commit": "f" * 40},
+                "source state",
+            ),
+            (
+                "source binding",
+                {"primary_source_binding_status": "fail"},
+                "source binding",
+            ),
+            (
+                "synthesis hash format",
+                {"primary_synthesis_hash": "bad"},
+                "synthesis",
+            ),
+            (
+                "synthesis manifest mismatch",
+                {"primary_manifest_hash": "3" * 64},
+                "manifest",
+            ),
+            (
+                "missing bitstream artifact",
+                {"primary_bitstream_artifact": False},
+                "bitstream artifact",
+            ),
+            (
+                "bitstream artifact hash",
+                {"primary_bitstream_artifact_hash": "0" * 64},
+                "bitstream artifact",
+            ),
+            (
+                "bitstream artifact path",
+                {"primary_bitstream_artifact_path": str(ROOT / "missing.bit")},
+                "bitstream artifact",
+            ),
+            (
+                "pin mismatch",
+                {"primary_pin_overrides": {"x_step": "WRONG_BALL"}},
+                "pin",
+            ),
+            (
+                "pin direction",
+                {"primary_pin_field_overrides": {"x_step": {"direction": "INPUT"}}},
+                "pin",
+            ),
+            (
+                "pin io standard",
+                {
+                    "primary_pin_field_overrides": {
+                        "x_step": {"io_standard": "LVCMOS18"}
+                    }
+                },
+                "pin",
+            ),
+            (
+                "limit pull",
+                {
+                    "primary_pin_field_overrides": {
+                        "x_limit_raw": {"pull_type": "NONE"}
+                    }
+                },
+                "pin",
+            ),
+            ("io row count", {"primary_pin_row_count": 40}, "41"),
+            (
+                "io uniqueness gate",
+                {"primary_pin_failures": ["io_location_not_unique"]},
+                "pin",
+            ),
+            (
+                "forbidden A5",
+                {"primary_pin_overrides": {"x_step": "A5"}},
+                "A5|pin",
+            ),
+            ("dirty source", {"dirty_source": True}, "tracked source changes"),
+            ("untracked source", {"untracked_source": True}, "untracked"),
+        )
+        for name, overrides, pattern in cases:
+            with self.subTest(name=name), tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+                with self.assertRaisesRegex(AssertionError, pattern):
+                    _build_package(
+                        Path(temporary),
+                        urgent_single_td=True,
+                        include_confirmation=False,
+                        **overrides,
+                    )
+
+    def test_urgent_allows_failed_td_resource_and_validation_status(self) -> None:
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            package, _commit, _digest = _build_package(
+                Path(temporary), urgent_single_td=True, include_confirmation=False
+            )
+            validation = json.loads(
+                (package / "evidence" / "validation-summary.json").read_text(
+                    encoding="utf-8"
+                )
+            )
+
+        self.assertEqual(validation["layers"]["td_primary"]["status"], "fail")
+        self.assertEqual(validation["layers"]["resource_primary"]["status"], "fail")
+        self.assertEqual(validation["layers"]["formal"]["status"], "fail")
+
+    def test_normal_incomplete_evidence_is_not_verification_complete(self) -> None:
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            package, _commit, _digest = _build_package(Path(temporary))
+            info = json.loads((package / "package-info.json").read_text(encoding="utf-8"))
+            validation = json.loads(
+                (package / "evidence" / "validation-summary.json").read_text(
+                    encoding="utf-8"
+                )
+            )
+
+        self.assertFalse(info["verification_complete"])
+        self.assertFalse(validation["verification_complete"])
+
+    def test_validation_receipt_fail_cannot_be_overwritten_by_later_pass(self) -> None:
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            package, _commit, _digest = _build_package(
+                Path(temporary), validation_statuses=("fail", "pass")
+            )
+            validation = json.loads(
+                (package / "evidence" / "validation-summary.json").read_text(
+                    encoding="utf-8"
+                )
+            )
+
+        self.assertEqual(validation["layers"]["formal"]["status"], "fail")
+
+    def test_running_layers_are_preserved_until_a_receipt_completes_them(self) -> None:
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            package, _commit, _digest = _build_package(
+                Path(temporary),
+                urgent_single_td=True,
+                include_confirmation=False,
+                validation_statuses=(),
+                running_validation_layers=("cocotb", "td_confirmation"),
+            )
+            validation = json.loads(
+                (package / "evidence" / "validation-summary.json").read_text(
+                    encoding="utf-8"
+                )
+            )
+            selftest = subprocess.run(
+                [
+                    "powershell.exe",
+                    "-NoProfile",
+                    "-ExecutionPolicy",
+                    "Bypass",
+                    "-File",
+                    str(package / "selftest.ps1"),
+                ],
+                cwd=package,
+                capture_output=True,
+                text=True,
+                check=False,
+            )
+
+        self.assertEqual(validation["layers"]["cocotb"]["status"], "running")
+        self.assertEqual(
+            validation["layers"]["td_confirmation"]["status"], "running"
+        )
+        self.assertFalse(validation["verification_complete"])
+        self.assertEqual(selftest.returncode, 0, selftest.stdout + selftest.stderr)
+
+    def test_completed_receipt_replaces_declared_running_layer(self) -> None:
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            package, _commit, _digest = _build_package(
+                Path(temporary),
+                validation_statuses=("pass",),
+                running_validation_layers=("formal",),
+            )
+            validation = json.loads(
+                (package / "evidence" / "validation-summary.json").read_text(
+                    encoding="utf-8"
+                )
+            )
+
+        self.assertEqual(validation["layers"]["formal"]["status"], "pass")
+
+    def test_folder_selftest_rejects_layer_set_and_urgent_confirmation_mutations(self) -> None:
+        mutations = (
+            ("missing layer", lambda layers: layers.pop("formal")),
+            (
+                "unknown layer",
+                lambda layers: layers.__setitem__(
+                    "unknown", {"status": "pass", "source": "fixture"}
+                ),
+            ),
+            (
+                "urgent confirmation pass",
+                lambda layers: layers["td_confirmation"].__setitem__("status", "pass"),
+            ),
+        )
+        for name, mutate in mutations:
+            with self.subTest(name=name), tempfile.TemporaryDirectory(
+                dir=ROOT.parent
+            ) as temporary:
+                package, _commit, _digest = _build_package(
+                    Path(temporary), urgent_single_td=True, include_confirmation=False
+                )
+                validation_path = package / "evidence" / "validation-summary.json"
+                info_path = package / "package-info.json"
+                validation = json.loads(validation_path.read_text(encoding="utf-8"))
+                mutate(validation["layers"])
+                validation_path.write_text(json.dumps(validation), encoding="utf-8")
+                info = json.loads(info_path.read_text(encoding="utf-8"))
+                validation_hash = hashlib.sha256(validation_path.read_bytes()).hexdigest()
+                info["validation_summary_sha256"] = validation_hash
+                info["file_sha256"]["evidence/validation-summary.json"] = validation_hash
+                info_path.write_text(json.dumps(info), encoding="utf-8")
+
+                completed = subprocess.run(
+                    [
+                        "powershell.exe",
+                        "-NoProfile",
+                        "-ExecutionPolicy",
+                        "Bypass",
+                        "-File",
+                        str(package / "selftest.ps1"),
+                    ],
+                    cwd=package,
+                    capture_output=True,
+                    text=True,
+                    check=False,
+                )
+
+                self.assertNotEqual(completed.returncode, 0)
+
+    def test_normal_dual_td_mode_still_requires_confirmation_receipt(self) -> None:
+        with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
+            with self.assertRaisesRegex(AssertionError, "Confirmation"):
+                _build_package(Path(temporary), include_confirmation=False)
+
     def test_package_includes_hash_bound_machine_readable_contract_artifacts(self) -> None:
     def test_package_includes_hash_bound_machine_readable_contract_artifacts(self) -> None:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
         with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
             package, _commit, _digest = _build_package(Path(temporary))
             package, _commit, _digest = _build_package(Path(temporary))

+ 546 - 0
tests/unit/test_prod2u_p4_motion_source_mutations.py

@@ -0,0 +1,546 @@
+#!/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"
+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,
+) -> IcarusResult:
+    executable = workdir / f"{top}.vvp"
+    started = time.perf_counter()
+    compile_result = subprocess.run(
+        [
+            str(iverilog),
+            "-g2005-sv",
+            "-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_hub_with_speed_tiers(source: str) -> str:
+    source = _replace_exact(
+        source,
+        "    input  wire        jog_dir,\n"
+        "    input  wire [15:0] jog_steps,",
+        "    input  wire        jog_dir,\n"
+        "    input  wire [1:0]  jog_speed,\n"
+        "    input  wire [15:0] jog_steps,",
+        label="hub speed port",
+    )
+    return _replace_exact(
+        source,
+        "        .command_steps(jog_steps),\n"
+        "        .step_out",
+        "        .command_steps(jog_steps),\n"
+        "        .command_speed(jog_speed),\n"
+        "        .step_out",
+        label="hub speed routing",
+        expected_count=2,
+    )
+
+
+def _mutate_core_with_speed_tiers(source: str) -> str:
+    source = _replace_exact(
+        source,
+        "    reg motor_jog_dir;\n"
+        "    reg [15:0] motor_jog_steps;",
+        "    reg motor_jog_dir;\n"
+        "    reg [1:0] motor_jog_speed;\n"
+        "    reg [15:0] motor_jog_steps;",
+        label="core speed register",
+    )
+    source = _replace_exact(
+        source,
+        "        .jog_dir(motor_jog_dir),\n"
+        "        .jog_steps(motor_jog_steps),",
+        "        .jog_dir(motor_jog_dir),\n"
+        "        .jog_speed(motor_jog_speed),\n"
+        "        .jog_steps(motor_jog_steps),",
+        label="core speed routing",
+    )
+    source = _replace_exact(
+        source,
+        "            motor_jog_dir <= 1'b0;\n"
+        "            motor_jog_steps <= 16'd0;",
+        "            motor_jog_dir <= 1'b0;\n"
+        "            motor_jog_speed <= 2'd0;\n"
+        "            motor_jog_steps <= 16'd0;",
+        label="core speed reset",
+    )
+    return _replace_exact(
+        source,
+        "                                    motor_jog_dir <= request_value[0];\n"
+        "                                    motor_jog_steps <= request_steps;",
+        "                                    motor_jog_dir <= request_value[0];\n"
+        "                                    motor_jog_speed <= request_flags[1:0];\n"
+        "                                    motor_jog_steps <= request_steps;",
+        label="core speed capture",
+    )
+
+
+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",
+    )
+
+
+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 request_valid = 1'b0;
+        reg [7:0] request_type = 8'h11;
+        reg [5:0] request_length = 6'd8;
+        reg [271:0] request_payload = 272'd0;
+        wire request_ready;
+        wire [2:0] step_out;
+        integer cycle_count = 0;
+        integer guard;
+        integer interval0;
+        integer interval1;
+        integer interval2;
+        integer interval3;
+
+        always #5 clk = ~clk;
+        always @(posedge clk) cycle_count = cycle_count + 1;
+
+        prod2u_p4_normal_v3_core #(
+            .CLK_HZ(64),
+            .WATCHDOG_SECONDS(8),
+            .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),
+            .frame_valid(), .frame_ready(1'b1), .frame_type(),
+            .frame_payload_len(), .frame_payload(), .ptc_percent(),
+            .fan_percent(), .solenoid_percent(), .state_hash16(),
+            .step_out(step_out), .dir_out(), .en_n(), .disabled(),
+            .watchdog_timeout()
+        );
+
+        task reset_core;
+            begin
+                rst_n = 1'b0;
+                request_valid = 1'b0;
+                request_payload = 272'd0;
+                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_core();
+                guard = 0;
+                while (!request_ready && guard < 64) begin
+                    @(negedge clk);
+                    guard = guard + 1;
+                end
+                if (!request_ready) $fatal(1, "SPEED_FIXED_RATE_READY_FAIL");
+
+                @(negedge clk);
+                request_payload = 272'd0;
+                request_payload[7:0] = 8'h35;
+                request_payload[15:8] = 8'd0;
+                request_payload[23:16] = 8'd0;
+                request_payload[31:24] = {6'd0, speed_code};
+                request_payload[47:32] = 16'd2;
+                request_valid = 1'b1;
+                @(posedge clk);
+                #1;
+                @(negedge clk);
+                request_valid = 1'b0;
+
+                @(posedge step_out[0]);
+                first_cycle = cycle_count;
+                @(posedge step_out[0]);
+                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 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")
+            common = (
+                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",
+            )
+            tail = (
+                ROOT / "src/rtl/prod2u_p4_response_scheduler.v",
+            )
+
+            baseline = _run_icarus(
+                iverilog=self.iverilog,
+                vvp=self.vvp,
+                top="prod2u_p4_fixed_speed_contract_mutation_tb",
+                sources=(
+                    *common,
+                    AXIS_SOURCE,
+                    HUB_SOURCE,
+                    *tail,
+                    CORE_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_hub = workdir / "prod2u_p4_motor_hub_speed.v"
+            mutant_core = workdir / "prod2u_p4_normal_v3_core_speed.v"
+            mutant_axis.write_text(
+                _mutate_axis_with_speed_tiers(
+                    AXIS_SOURCE.read_text(encoding="ascii")
+                ),
+                encoding="ascii",
+                newline="\n",
+            )
+            mutant_hub.write_text(
+                _mutate_hub_with_speed_tiers(
+                    HUB_SOURCE.read_text(encoding="ascii")
+                ),
+                encoding="ascii",
+                newline="\n",
+            )
+            mutant_core.write_text(
+                _mutate_core_with_speed_tiers(
+                    CORE_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=(
+                    *common,
+                    mutant_axis,
+                    mutant_hub,
+                    *tail,
+                    mutant_core,
+                    speed_tb,
+                ),
+                workdir=workdir,
+            )
+            self.assert_mutant_killed(mutant, "SPEED_FIXED_RATE_FAIL")
+
+    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")
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 228 - 315
tests/unit/test_prod2u_p4_normal_v3_model.py

@@ -1,5 +1,5 @@
 #!/usr/bin/env python3
 #!/usr/bin/env python3
-"""Independent model tests for the minimal two-axis Normal-v3 contract."""
+"""Independent model tests for the unprotected JOG-only Normal-v3 contract."""
 
 
 from __future__ import annotations
 from __future__ import annotations
 
 
@@ -17,87 +17,115 @@ import prod2u_p4_normal_v3_model as model  # noqa: E402
 import prod2u_p4_protocol as protocol  # noqa: E402
 import prod2u_p4_protocol as protocol  # noqa: E402
 
 
 
 
-def snapshot(*, ptc: int = 0, fan: int = 30, solenoid: int = 0, x: int, y: int) -> bytes:
-    return protocol.build_output_snapshot(
-        ptc_percent=(ptc,) * 24,
-        fan_percent=(fan,) * 4,
-        solenoid=solenoid,
-        xyz=(x, y, 0),
+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):
 class Prod2UP4NormalV3ModelTests(unittest.TestCase):
-    def test_standard_axes_run_independently_for_exactly_3200_steps_and_ignore_limits(self) -> None:
-        subject = model.NormalV3Model()
-        result = subject.apply_frame(snapshot(x=100, y=0))
+    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.assertTrue(result.accepted)
-        self.assertEqual(result.status, protocol.StatusCode.OK)
-        self.assertEqual(subject.active_mask, 0x03)
-        self.assertEqual(subject.busy_mask, 0)
-        self.assertEqual(subject.axes[0].raw_dir, 0)
-        self.assertEqual(subject.axes[1].raw_dir, 1)
-        self.assertEqual(subject.axes[0].remaining_steps, 3200)
-        self.assertEqual(subject.axes[1].remaining_steps, 3200)
-        self.assertFalse(hasattr(subject.axes[0], "limit_stop_enabled"))
-        self.assertFalse(hasattr(subject.axes[1], "limit_stop_enabled"))
-
-        self.assertEqual(subject.execute_parallel_steps((3200, 3200, 0)), (3200, 3200, 0))
-        self.assertEqual(subject.busy_mask, 0)
-        self.assertEqual(subject.position_valid_mask, 0x03)
-        self.assertEqual(subject.axes[0].current, 100)
-        self.assertEqual(subject.axes[1].current, 0)
-        self.assertEqual(subject.fault_mask, 0)
-
-    def test_repeated_standard_command_starts_a_fresh_full_move(self) -> None:
-        subject = model.NormalV3Model()
-        request = snapshot(x=100, y=100)
-        subject.apply_frame(request)
-        subject.execute_parallel_steps((3200, 3200, 0))
-
-        repeated = subject.apply_frame(request)
-
-        self.assertTrue(repeated.accepted)
-        self.assertEqual(subject.active_mask, 0x03)
-        self.assertEqual(subject.busy_mask, 0)
-        self.assertEqual(subject.axes[0].remaining_steps, 3200)
-        self.assertEqual(subject.axes[1].remaining_steps, 3200)
-        self.assertEqual(subject.axes[0].current, 0xFE)
-        self.assertEqual(subject.axes[1].current, 0xFE)
-        self.assertEqual(subject.position_valid_mask, 0)
-
-    def test_busy_snapshot_commits_ptc_fan_starts_idle_peer_and_holds_solenoid(self) -> None:
+        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()
         subject = model.NormalV3Model()
-        subject.apply_frame(
-            protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=3, steps=10)
+        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(
         result = subject.apply_frame(
-            snapshot(ptc=11, fan=22, solenoid=100, x=100, y=0)
+            protocol.build_motor_jog(axis=0, raw_dir=1, speed_code=0, steps=2)
         )
         )
-
         self.assertTrue(result.accepted)
         self.assertTrue(result.accepted)
-        self.assertEqual(result.status, protocol.StatusCode.PARTIAL)
-        self.assertEqual(result.detail, 0x41)
-        self.assertEqual(result.result_flags, 0x0D)
-        self.assertEqual(subject.ptc_percent, (11,) * 24)
-        self.assertEqual(subject.fan_percent, (22,) * 4)
-        self.assertEqual(subject.solenoid, 0)
-        self.assertEqual(subject.axes[0].move_kind, "jog")
-        self.assertEqual(subject.axes[0].remaining_steps, 10)
-        self.assertEqual(subject.axes[1].move_kind, "standard")
-        self.assertEqual(subject.axes[1].remaining_steps, 3200)
-
-    def test_force_jog_clamps_actual_steps_but_preserves_full_wire_request(self) -> None:
-        for requested, expected in ((1, 1), (799, 799), (800, 800), (801, 800), (8191, 800), (65535, 800)):
+        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):
             with self.subTest(requested=requested):
                 subject = model.NormalV3Model()
                 subject = model.NormalV3Model()
                 request = protocol.build_motor_jog(
                 request = protocol.build_motor_jog(
                     axis=0,
                     axis=0,
                     raw_dir=1,
                     raw_dir=1,
-                    speed_code=3,
+                    speed_code=2,
                     steps=requested,
                     steps=requested,
                 )
                 )
+
                 result = subject.apply_frame(request)
                 result = subject.apply_frame(request)
 
 
                 self.assertTrue(result.accepted)
                 self.assertTrue(result.accepted)
@@ -106,309 +134,195 @@ class Prod2UP4NormalV3ModelTests(unittest.TestCase):
                     protocol.decode_motion_command(protocol.decode_frame(request)).steps,
                     protocol.decode_motion_command(protocol.decode_frame(request)).steps,
                     requested,
                     requested,
                 )
                 )
-                self.assertEqual(subject.axes[0].remaining_steps, expected)
-                self.assertEqual(subject.active_mask, 0x01)
-                self.assertEqual(subject.busy_mask, 0)
-                for retired in (
-                    "awaiting_limit_confirmation",
-                    "limit_stop_enabled",
-                    "close_dir",
-                    "distance_steps",
-                    "recovery_steps_used",
-                    "pending_reverse",
-                    "terminal",
-                ):
-                    self.assertFalse(hasattr(subject.axes[0], retired), retired)
-
-                subject.advance_time(1)
-                self.assertEqual(subject.execute_axis_steps(0, expected), expected)
-                self.assertEqual(subject.active_mask, 0)
+                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)
                 self.assertEqual(subject.busy_mask, 0)
 
 
-    def test_latest_jog_replaces_same_axis_during_setup_and_rearms_watchdog(self) -> None:
-        subject = model.NormalV3Model()
-        first = subject.apply_frame(
-            protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=0, steps=700)
-        )
-        latest = subject.apply_frame(
-            protocol.build_motor_jog(axis=0, raw_dir=1, speed_code=3, steps=65535)
-        )
-
-        self.assertTrue(first.accepted)
-        self.assertTrue(latest.accepted)
-        self.assertEqual(latest.status, protocol.StatusCode.OK)
-        self.assertEqual(subject.axes[0].raw_dir, 1)
-        self.assertEqual(subject.axes[0].speed_code, 3)
-        self.assertEqual(subject.axes[0].remaining_steps, 800)
-        self.assertEqual(subject.axes[0].dir_setup_remaining_ms, 1)
-        self.assertEqual(subject.watchdog_elapsed_ms, 0)
-        self.assertEqual(subject.busy_mask, 0)
-
-    def test_every_valid_jog_class_returns_ok_while_both_axes_are_active(self) -> None:
-        for axis_index, raw_dir, speed_code, requested in product(
-            (0, 1),
-            (0, 1),
-            range(4),
-            (1, 800, 801, 65535),
-        ):
-            with self.subTest(
-                axis=axis_index,
-                raw_dir=raw_dir,
-                speed_code=speed_code,
-                requested=requested,
-            ):
-                subject = model.NormalV3Model()
-                started = subject.apply_frame(snapshot(x=100, y=0))
-                self.assertTrue(started.accepted)
-                self.assertEqual(subject.active_mask, 0x03)
-
-                result = subject.apply_frame(
-                    protocol.build_motor_jog(
-                        axis=axis_index,
-                        raw_dir=raw_dir,
-                        speed_code=speed_code,
-                        steps=requested,
-                    )
-                )
-
-                self.assertTrue(result.accepted)
-                self.assertEqual(result.status, protocol.StatusCode.OK)
-                self.assertEqual(subject.axes[axis_index].move_kind, "jog")
-                self.assertEqual(
-                    subject.axes[axis_index].remaining_steps,
-                    min(requested, 800),
-                )
-                self.assertTrue(subject.axes[1 - axis_index].drive_active)
-
-    def test_valid_jog_recovers_latched_watchdog_and_executes_capped_steps(self) -> None:
-        for axis_index, raw_dir, requested in product(
-            (0, 1),
-            (0, 1),
-            (1, 800, 801, 65535),
-        ):
-            with self.subTest(axis=axis_index, raw_dir=raw_dir, requested=requested):
+    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 = model.NormalV3Model()
                 subject.apply_frame(
                 subject.apply_frame(
                     protocol.build_motor_jog(
                     protocol.build_motor_jog(
-                        axis=axis_index,
-                        raw_dir=1 - raw_dir,
-                        speed_code=3,
-                        steps=10,
-                    )
-                )
-                subject.watchdog_expire()
-                self.assertTrue(subject.watchdog_timeout)
-                self.assertTrue(subject.disabled)
-
-                result = subject.apply_frame(
-                    protocol.build_motor_jog(
-                        axis=axis_index,
-                        raw_dir=raw_dir,
-                        speed_code=3,
-                        steps=requested,
+                        axis=0,
+                        raw_dir=0,
+                        speed_code=speed_code,
+                        steps=2,
                     )
                     )
                 )
                 )
 
 
-                expected_steps = min(requested, 800)
-                self.assertTrue(result.accepted)
-                self.assertEqual(result.status, protocol.StatusCode.OK)
-                self.assertFalse(subject.watchdog_timeout)
-                self.assertFalse(subject.disabled)
-                self.assertTrue(subject.watchdog_armed)
-                self.assertEqual(subject.watchdog_elapsed_ms, 0)
-                self.assertEqual(subject.axes[axis_index].remaining_steps, expected_steps)
-                self.assertEqual(subject.active_mask, 1 << axis_index)
-                self.assertEqual(subject.busy_mask, 0)
-
+                self.assertEqual(subject.axes[0].step_phase, "high")
                 subject.advance_time(1)
                 subject.advance_time(1)
-                self.assertEqual(
-                    subject.execute_axis_steps(axis_index, expected_steps),
-                    expected_steps,
-                )
-                self.assertEqual(subject.active_mask, 0)
-                self.assertEqual(subject.busy_mask, 0)
-
-    def test_wallclock_advance_emits_speed3_step_after_setup_for_single_or_split_time(self) -> None:
-        for chunks in ((2,), (1, 1)):
-            with self.subTest(chunks=chunks):
-                subject = model.NormalV3Model()
-                subject.apply_frame(
-                    protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=3, steps=1)
-                )
-
-                for elapsed_ms in chunks:
-                    subject.advance_time(elapsed_ms)
 
 
-                self.assertEqual(subject.active_mask, 0)
+                self.assertEqual(subject.axes[0].steps_executed, 1)
+                self.assertEqual(subject.axes[0].remaining_steps, 1)
                 self.assertEqual(subject.busy_mask, 0)
                 self.assertEqual(subject.busy_mask, 0)
-                self.assertEqual(subject.axes[0].remaining_steps, 0)
-                self.assertEqual(subject.axes[0].current, 0xFF)
-
-    def test_jog_received_during_step_applies_after_complete_low_and_latest_wins(self) -> None:
-        for arrival_phase in ("high", "low"):
-            with self.subTest(arrival_phase=arrival_phase):
-                subject = model.NormalV3Model()
-                subject.apply_frame(
-                    protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=3, steps=10)
-                )
-                subject.advance_time(1)
-                subject.begin_axis_step(0)
-                if arrival_phase == "low":
-                    subject.lower_axis_step(0)
 
 
-                subject.apply_frame(
-                    protocol.build_motor_jog(axis=0, raw_dir=1, speed_code=0, steps=20)
-                )
-                subject.apply_frame(
-                    protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=2, steps=801)
-                )
+    def test_zero_step_jog_remains_bad_value_and_atomic(self) -> None:
+        subject = model.NormalV3Model()
+        before = subject.state_fingerprint()
 
 
-                self.assertEqual(subject.busy_mask, 0x01)
-                self.assertEqual(subject.axes[0].raw_dir, 0)
-                self.assertEqual(subject.axes[0].remaining_steps, 10)
-                self.assertEqual(subject.axes[0].pending_jog, (0, 2, 800))
+        result = subject.apply_frame(zero_step_jog())
 
 
-                subject.finish_axis_step(0)
+        self.assertFalse(result.accepted)
+        self.assertEqual(result.status, protocol.StatusCode.BAD_VALUE)
+        self.assertEqual(subject.state_fingerprint(), before)
 
 
-                self.assertEqual(subject.axes[0].raw_dir, 0)
-                self.assertEqual(subject.axes[0].speed_code, 2)
-                self.assertEqual(subject.axes[0].remaining_steps, 800)
-                self.assertEqual(subject.axes[0].dir_setup_remaining_ms, 1)
-                self.assertEqual(subject.busy_mask, 0)
-                self.assertEqual(subject.active_mask, 0x01)
-
-    def test_force_jog_executes_both_directions_without_a_limit_input_path(self) -> None:
-        self.assertNotIn(
-            "limit",
-            inspect.getsource(model.NormalV3Model._apply_jog).lower(),
-        )
-        self.assertFalse(
-            any("limit" in field.lower() for field in model.AxisState.__dataclass_fields__)
-        )
-        for raw_dir in (0, 1):
-            with self.subTest(raw_dir=raw_dir):
+    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()
                 subject = model.NormalV3Model()
-                subject.apply_frame(
-                    protocol.build_motor_jog(axis=1, raw_dir=raw_dir, speed_code=3, steps=3)
+                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,
+                    )
                 )
                 )
-                subject.advance_time(1)
 
 
-                self.assertEqual(subject.execute_axis_steps(1, 3), 3)
-                self.assertEqual(subject.active_mask, 0)
+                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.busy_mask, 0)
+                self.assertEqual(subject.axes[0].raw_dir, x_dir)
+                self.assertEqual(subject.axes[1].raw_dir, y_dir)
 
 
-    def test_snapshot_uses_axis_active_during_setup_not_reported_busy(self) -> None:
+    def test_new_same_axis_jog_immediately_truncates_and_reloads_old_step(self) -> None:
         subject = model.NormalV3Model()
         subject = model.NormalV3Model()
         subject.apply_frame(
         subject.apply_frame(
-            protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=3, steps=10)
+            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(
         result = subject.apply_frame(
-            snapshot(ptc=11, fan=22, solenoid=100, x=100, y=0)
+            protocol.build_motor_jog(axis=0, raw_dir=1, speed_code=3, steps=20)
         )
         )
 
 
-        self.assertEqual(subject.busy_mask, 0)
-        self.assertEqual(subject.active_mask, 0x03)
-        self.assertEqual(result.status, protocol.StatusCode.PARTIAL)
-        self.assertEqual(result.detail, 0x41)
-        self.assertEqual(result.result_flags, 0x0D)
+        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_snapshot_active_axis_precedes_invalid_target_classification(self) -> None:
+    def test_jog_does_not_arm_or_refresh_watchdog(self) -> None:
         subject = model.NormalV3Model()
         subject = model.NormalV3Model()
+        before = (
+            subject.disabled,
+            subject.watchdog_timeout,
+            subject.watchdog_armed,
+            subject.watchdog_elapsed_ms,
+        )
+
         subject.apply_frame(
         subject.apply_frame(
             protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=3, steps=10)
             protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=3, steps=10)
         )
         )
-        request = bytearray(snapshot(ptc=11, fan=22, solenoid=100, x=100, y=0))
-        request[45] = 50
-        request[-2:] = protocol.crc16_ccitt(request[2:-2]).to_bytes(2, "little")
-
-        result = subject.apply_frame(bytes(request))
 
 
-        self.assertTrue(result.accepted)
-        self.assertEqual(result.status, protocol.StatusCode.PARTIAL)
-        self.assertEqual(result.detail, 0x41)
-        self.assertEqual(result.detail & 0x08, 0)
-        self.assertEqual(result.result_flags, 0x0D)
+        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_forget_idle_completed_standard_positions(self) -> None:
+    def test_disable_and_watchdog_only_safe_non_motor_outputs(self) -> None:
         for stop in ("disable", "watchdog"):
         for stop in ("disable", "watchdog"):
             with self.subTest(stop=stop):
             with self.subTest(stop=stop):
                 subject = model.NormalV3Model()
                 subject = model.NormalV3Model()
-                subject.apply_frame(snapshot(x=100, y=0))
-                subject.execute_parallel_steps((3200, 3200, 0))
-                self.assertEqual(subject.position_valid_mask, 0x03)
+                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":
                 if stop == "disable":
-                    subject.apply_frame(
-                        protocol.build_host_command(command=protocol.CommandId.DISABLE)
-                    )
-                    self.assertFalse(subject.watchdog_timeout)
+                    subject.disable()
                 else:
                 else:
+                    subject.disabled = False
+                    subject.watchdog_armed = True
                     subject.watchdog_expire()
                     subject.watchdog_expire()
-                    self.assertTrue(subject.watchdog_timeout)
 
 
-                self.assertEqual(subject.position_valid_mask, 0)
+                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.busy_mask, 0)
-                self.assertEqual(subject.active_mask, 0)
-                self.assertEqual(
-                    tuple(axis.current for axis in subject.axes[:2]),
-                    (0xFF, 0xFF),
-                )
-                self.assertEqual(
-                    tuple(axis.target for axis in subject.axes[:2]),
-                    (0xFF, 0xFF),
-                )
+                self.assertEqual(subject.fault_mask, 0)
 
 
-    def test_force_jog_model_excludes_retired_limit_qualification_state(self) -> None:
+    def test_model_has_no_limit_input_or_qualification_state(self) -> None:
         subject = model.NormalV3Model()
         subject = model.NormalV3Model()
-        payload = subject.state_payload()
-        for retired in (
-            "limit_guard_mask",
-            "limit_fast_mask",
-            "limit_confirmed_mask",
-            "limit_ready_mask",
-        ):
-            self.assertNotIn(retired, payload)
-            self.assertNotIn(retired, inspect.signature(subject.apply_frame).parameters)
-
+        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, "observe_limits"))
         self.assertFalse(hasattr(subject, "advance_limit_confirmation"))
         self.assertFalse(hasattr(subject, "advance_limit_confirmation"))
         self.assertFalse(hasattr(model, "HighActiveLimitOracle"))
         self.assertFalse(hasattr(model, "HighActiveLimitOracle"))
 
 
-    def test_motor_status_refreshes_armed_watchdog_but_timeout_hard_stops(self) -> None:
-        subject = model.NormalV3Model()
-        subject.apply_frame(
-            protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=0, steps=65535)
-        )
-        subject.advance_time(4000)
-        status = subject.apply_frame(protocol.build_get_motor_status())
-
-        self.assertTrue(status.accepted)
-        self.assertEqual(status.response_type, protocol.FrameType.MOTION_STATUS)
-        self.assertEqual(subject.watchdog_elapsed_ms, 0)
-        subject.advance_time(4999)
-        self.assertFalse(subject.watchdog_timeout)
-        subject.advance_time(1)
-
-        self.assertTrue(subject.watchdog_timeout)
-        self.assertTrue(subject.disabled)
-        self.assertFalse(subject.axes[0].busy)
-        self.assertFalse(subject.axes[0].drive_active)
-        self.assertEqual(subject.axes[0].current, 0xFF)
-
     def test_unsupported_legacy_commands_are_atomic(self) -> None:
     def test_unsupported_legacy_commands_are_atomic(self) -> None:
         subject = model.NormalV3Model()
         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 (
         for request, command in (
             (model.GOLDEN_VECTORS["mark_x"], 0x36),
             (model.GOLDEN_VECTORS["mark_x"], 0x36),
-            (
-                protocol.encode_frame(
-                    frame_type=protocol.FrameType.HOST_CMD,
-                    seq=0,
-                    timestamp_tick=0,
-                    payload=b"\x29\x00\x00\x00",
-                ),
-                0x29,
-            ),
+            (temperature, 0x29),
         ):
         ):
             with self.subTest(command=command):
             with self.subTest(command=command):
                 before = subject.state_fingerprint()
                 before = subject.state_fingerprint()
@@ -418,7 +332,7 @@ class Prod2UP4NormalV3ModelTests(unittest.TestCase):
                 self.assertEqual(result.status, protocol.StatusCode.UNSUPPORTED_IN_PROFILE)
                 self.assertEqual(result.status, protocol.StatusCode.UNSUPPORTED_IN_PROFILE)
                 self.assertEqual(subject.state_fingerprint(), before)
                 self.assertEqual(subject.state_fingerprint(), before)
 
 
-    def test_model_replay_and_fuzz_are_green_for_force_jog_contract(self) -> None:
+    def test_model_replay_and_fuzz_follow_the_jog_only_contract(self) -> None:
         self.assertEqual(model.run_model()["status"], "pass")
         self.assertEqual(model.run_model()["status"], "pass")
         self.assertEqual(model.run_replay()["status"], "pass")
         self.assertEqual(model.run_replay()["status"], "pass")
         fuzz = model.run_fuzz(seed=921003, iterations=90)
         fuzz = model.run_fuzz(seed=921003, iterations=90)
@@ -426,7 +340,6 @@ class Prod2UP4NormalV3ModelTests(unittest.TestCase):
 
 
     def test_source_detector_requires_git_only_identity_and_explicit_solenoid_polarity(self) -> None:
     def test_source_detector_requires_git_only_identity_and_explicit_solenoid_polarity(self) -> None:
         detector = model.run_detector(ROOT)
         detector = model.run_detector(ROOT)
-
         self.assertEqual(detector["status"], "pass", detector)
         self.assertEqual(detector["status"], "pass", detector)
         self.assertTrue(detector["guards"]["runtime_build_identity_absent"])
         self.assertTrue(detector["guards"]["runtime_build_identity_absent"])
         self.assertTrue(detector["guards"]["solenoid_polarity_default_explicit"])
         self.assertTrue(detector["guards"]["solenoid_polarity_default_explicit"])

+ 90 - 18
tests/unit/test_prod2u_p4_normal_v3_td_files.py

@@ -90,12 +90,80 @@ class Prod2UP4NormalV3TDFilesTests(unittest.TestCase):
 
 
         self.assertEqual(len(rows), 41)
         self.assertEqual(len(rows), 41)
         self.assertEqual(len(set(assignments.values())), 41)
         self.assertEqual(len(set(assignments.values())), 41)
-        self.assertEqual(assignments["x_limit_raw"], "B9")
-        self.assertEqual(assignments["y_limit_raw"], "A11")
+        self.assertEqual(
+            {
+                signal: assignments[signal]
+                for signal in (
+                    "motor_en_n",
+                    "x_step",
+                    "x_dir",
+                    "y_step",
+                    "y_dir",
+                    "x_limit_raw",
+                    "y_limit_raw",
+                )
+            },
+            {
+                "motor_en_n": "A10",
+                "x_step": "C11",
+                "x_dir": "B12",
+                "y_step": "D15",
+                "y_dir": "H14",
+                "x_limit_raw": "B9",
+                "y_limit_raw": "A11",
+            },
+        )
         self.assertNotIn("A5", assignments.values())
         self.assertNotIn("A5", assignments.values())
         self.assertRegex(adc, r"x_limit_raw[^\n]+PULLTYPE = PULLUP; PACKREG = OFF")
         self.assertRegex(adc, r"x_limit_raw[^\n]+PULLTYPE = PULLUP; PACKREG = OFF")
         self.assertRegex(adc, r"y_limit_raw[^\n]+PULLTYPE = PULLUP; PACKREG = OFF")
         self.assertRegex(adc, r"y_limit_raw[^\n]+PULLTYPE = PULLUP; PACKREG = OFF")
 
 
+    def test_limit_ports_remain_pinned_but_have_no_rtl_or_cdc_consumer(self) -> None:
+        top = (ROOT / "src" / "top" / f"{STEM}_top.v").read_text(encoding="utf-8")
+        self.assertRegex(top, r"input\s+wire\s+x_limit_raw")
+        self.assertRegex(top, r"input\s+wire\s+y_limit_raw")
+        self.assertEqual(top.count("x_limit_raw"), 1)
+        self.assertEqual(top.count("y_limit_raw"), 1)
+
+        for relative in (
+            "src/rtl/prod2u_p4_axis_executor.v",
+            "src/rtl/prod2u_p4_motor_hub.v",
+            "src/rtl/prod2u_p4_normal_v3_core.v",
+        ):
+            with self.subTest(relative=relative):
+                source = (ROOT / relative).read_text(encoding="utf-8")
+                self.assertNotRegex(source, r"\b(?:x_limit_raw|y_limit_raw|limit_raw)\b")
+                self.assertNotIn("limit_sync_pipe", source)
+
+        for phase in ("syn", "phy"):
+            with self.subTest(phase=phase):
+                source = (ROOT / "td" / phase / f"{STEM}.tcl").read_text(
+                    encoding="ascii"
+                )
+                self.assertNotIn("limit_sync_pipe", source)
+                self.assertNotIn("x_limit_raw", source)
+                self.assertNotIn("y_limit_raw", source)
+                self.assertIn("if {[llength $cdc_regs] != 2}", source)
+                self.assertNotIn("if {[llength $cdc_regs] != 8}", source)
+
+    def test_axis_fsm_is_two_bit_four_phase_sequential_contract(self) -> None:
+        axis = (ROOT / "src" / "rtl" / "prod2u_p4_axis_executor.v").read_text(
+            encoding="utf-8"
+        )
+        self.assertRegex(axis, r"localparam\s+\[1:0\]\s+PHASE_IDLE\s*=\s*2'd0")
+        self.assertRegex(axis, r"localparam\s+\[1:0\]\s+PHASE_DIR_SETUP\s*=\s*2'd1")
+        self.assertRegex(axis, r"localparam\s+\[1:0\]\s+PHASE_STEP_HIGH\s*=\s*2'd2")
+        self.assertRegex(axis, r"localparam\s+\[1:0\]\s+PHASE_STEP_LOW\s*=\s*2'd3")
+        self.assertRegex(axis, r"reg\s+\[1:0\]\s+motion_phase")
+
+        for phase in ("syn", "phy"):
+            with self.subTest(phase=phase):
+                source = (ROOT / "td" / phase / f"{STEM}.tcl").read_text(
+                    encoding="ascii"
+                )
+                self.assertIn("motion_phase_register_count:$axis:[llength $matches]", source)
+                self.assertIn(r"/motion_phase\[[0-1]\]$", source)
+                self.assertNotIn(r"/motion_phase\[[0-2]\]$", source)
+
     def test_sdc_contains_only_the_25_mhz_clock(self) -> None:
     def test_sdc_contains_only_the_25_mhz_clock(self) -> None:
         sdc = (ROOT / "constraints" / f"{STEM}.sdc").read_text(encoding="ascii")
         sdc = (ROOT / "constraints" / f"{STEM}.sdc").read_text(encoding="ascii")
         commands = [line for line in sdc.splitlines() if line and not line.startswith("#")]
         commands = [line for line in sdc.splitlines() if line and not line.startswith("#")]
@@ -111,31 +179,36 @@ class Prod2UP4NormalV3TDFilesTests(unittest.TestCase):
 
 
         self.assertEqual(binding["profile"], "prod2u-p4-normal-actuator-binary921-v3")
         self.assertEqual(binding["profile"], "prod2u-p4-normal-actuator-binary921-v3")
         self.assertEqual(binding["motor"]["direction_contract"], {"0": "open", "1": "close"})
         self.assertEqual(binding["motor"]["direction_contract"], {"0": "open", "1": "close"})
-        self.assertEqual(binding["motor"]["standard_move_steps"], 3200)
-        self.assertFalse(binding["motor"]["standard_move_uses_limit"])
-        self.assertEqual(binding["motor"]["jog_executed_step_cap"], 800)
-        self.assertEqual(binding["motor"]["jog_limit_policy"], "ignored")
-        self.assertEqual(binding["motor"]["active_axis_jog_policy"], "replace_latest")
-        self.assertEqual(binding["motor"]["reported_busy_policy"], "step_backed")
+        self.assertEqual(binding["motor"]["motor_driving_commands"], ["0x35"])
+        self.assertEqual(binding["motor"]["legacy_snapshot_xyz_motor_effect"], "none")
+        self.assertEqual(binding["motor"]["jog_requested_step_range"], [1, 65535])
+        self.assertIsNone(binding["motor"]["jog_executed_step_cap"])
+        self.assertEqual(
+            binding["motor"]["jog_limit_policy"], "retained_pins_no_consumer"
+        )
+        self.assertEqual(
+            binding["motor"]["jog_speed_field_policy"], "validate_then_ignore"
+        )
+        self.assertEqual(binding["motor"]["effective_step_rate_hz"], 1000)
+        self.assertEqual(binding["motor"]["ack_semantics"], "FIRST_STEP_EMITTED")
+        self.assertEqual(binding["motor"]["active_axis_jog_policy"], "immediate_reload")
+        self.assertEqual(binding["motor"]["reported_busy_policy"], "constant_zero")
         self.assertEqual(
         self.assertEqual(
             binding["motor"]["reported_busy_role"],
             binding["motor"]["reported_busy_role"],
-            "read_only_telemetry_not_jog_admission",
+            "reserved_constant_zero",
         )
         )
         self.assertEqual(binding["motor"]["valid_xy_jog_busy_rejection_sources"], [])
         self.assertEqual(binding["motor"]["valid_xy_jog_busy_rejection_sources"], [])
+        self.assertEqual(binding["motor"]["watchdog_motor_effect"], "none")
+        self.assertEqual(binding["motor"]["disable_motor_effect"], "none")
+        self.assertEqual(binding["motor"]["limit_logic_consumer"], "none")
         self.assertEqual(
         self.assertEqual(
-            binding["motor"]["watchdog_timeout_jog_policy"],
-            "clear_timeout_rearm_without_disable",
+            binding["motor"]["motor_stop_sources"],
+            ["reset", "power_loss", "reconfiguration"],
         )
         )
         self.assertEqual(binding["motor"]["x_limit_raw_ball"], "B9")
         self.assertEqual(binding["motor"]["x_limit_raw_ball"], "B9")
         self.assertEqual(binding["motor"]["y_limit_raw_ball"], "A11")
         self.assertEqual(binding["motor"]["y_limit_raw_ball"], "A11")
         self.assertEqual(binding["motor"]["unused_balls"], ["A5"])
         self.assertEqual(binding["motor"]["unused_balls"], ["A5"])
 
 
-        axis_source = (ROOT / "src" / "rtl" / "prod2u_p4_axis_executor.v").read_text(
-            encoding="utf-8"
-        )
-        self.assertIn("limit_sync_pipe", axis_source)
-        self.assertNotIn("PHASE_LIMIT_VERIFY", axis_source)
-        self.assertNotIn("limit_synced_high", axis_source)
         self.assertEqual(binding["resources"]["io"], 41)
         self.assertEqual(binding["resources"]["io"], 41)
         self.assertEqual(binding["resources"]["dsp"], 0)
         self.assertEqual(binding["resources"]["dsp"], 0)
         self.assertTrue(
         self.assertTrue(
@@ -147,6 +220,5 @@ class Prod2UP4NormalV3TDFilesTests(unittest.TestCase):
             ["HOST_ACK", "MOTION_STATUS"],
             ["HOST_ACK", "MOTION_STATUS"],
         )
         )
 
 
-
 if __name__ == "__main__":
 if __name__ == "__main__":
     unittest.main()
     unittest.main()

+ 10 - 2
tests/unit/test_prod2u_p4_output_storage_structure.py

@@ -38,13 +38,21 @@ class OutputStorageStructureTests(unittest.TestCase):
         self.assertIn("function [1:0] encode_binary_rail;", source)
         self.assertIn("function [1:0] encode_binary_rail;", source)
         self.assertIn("function [7:0] decode_binary_rail;", source)
         self.assertIn("function [7:0] decode_binary_rail;", source)
 
 
-    def test_rx_is_the_only_272_bit_request_buffer(self) -> None:
+    def test_rx_buffer_and_one_core_snapshot_latch_are_the_only_272_bit_registers(self) -> None:
         owners = []
         owners = []
         for path in sorted((ROOT / "src" / "rtl").glob("*.v")):
         for path in sorted((ROOT / "src" / "rtl").glob("*.v")):
             if "reg [271:0]" in path.read_text(encoding="ascii"):
             if "reg [271:0]" in path.read_text(encoding="ascii"):
                 owners.append(path.name)
                 owners.append(path.name)
 
 
-        self.assertEqual(owners, ["prod2u_p4_normal_v3_rx.v"])
+        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:
     def test_pwm_step_counters_use_parameter_sized_storage(self) -> None:
         source = PWM_OUTPUTS.read_text(encoding="ascii")
         source = PWM_OUTPUTS.read_text(encoding="ascii")

+ 157 - 43
tests/unit/test_prod2u_p4_protocol_v3.py

@@ -54,19 +54,25 @@ class Prod2UP4ProtocolV3Tests(unittest.TestCase):
         self.assertEqual(decoded.xyz, (100, 0, 100))
         self.assertEqual(decoded.xyz, (100, 0, 100))
 
 
     def test_motion_requests_keep_frozen_payloads_and_full_u16_steps(self) -> None:
     def test_motion_requests_keep_frozen_payloads_and_full_u16_steps(self) -> None:
-        for steps in (1, 799, 800, 801, 8191, 65535):
-            with self.subTest(steps=steps):
-                wire = protocol.build_motor_jog(
-                    axis=1,
-                    raw_dir=1,
-                    speed_code=3,
-                    steps=steps,
-                )
-                frame = protocol.decode_frame(wire)
-                decoded = protocol.decode_motion_command(frame)
-                self.assertEqual(len(wire), 24)
-                self.assertEqual(frame.payload[4:6], steps.to_bytes(2, "little"))
-                self.assertEqual(decoded.steps, steps)
+        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"):
         with self.assertRaisesRegex(ValueError, "1 to 65535"):
             protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=0, steps=0)
             protocol.build_motor_jog(axis=0, raw_dir=0, speed_code=0, steps=0)
@@ -80,6 +86,16 @@ class Prod2UP4ProtocolV3Tests(unittest.TestCase):
             "a55a0204110000000000000000083700000000000000347f",
             "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_temperature_request_can_be_framed_but_has_no_public_api(self) -> None:
     def test_legacy_temperature_request_can_be_framed_but_has_no_public_api(self) -> None:
         wire = protocol.encode_frame(
         wire = protocol.encode_frame(
             frame_type=protocol.FrameType.HOST_CMD,
             frame_type=protocol.FrameType.HOST_CMD,
@@ -112,13 +128,13 @@ class Prod2UP4ProtocolV3Tests(unittest.TestCase):
         self.assertEqual(ack.state_hash16, 0xE177)
         self.assertEqual(ack.state_hash16, 0xE177)
         self.assertEqual(ack.result_flags, 0x05)
         self.assertEqual(ack.result_flags, 0x05)
 
 
-    def test_motion_status_keeps_ten_byte_layout_and_unknown_jog_state(self) -> None:
+    def test_motion_status_keeps_ten_byte_layout_with_reserved_zero_busy_and_fault(self) -> None:
         wire = protocol.build_motion_status(
         wire = protocol.build_motion_status(
-            flags=0x01,
+            flags=0x02,
             position_valid_mask=0,
             position_valid_mask=0,
-            busy_mask=0x03,
-            current_xyz=(0xFF, 0xFE, 0xFF),
-            target_xyz=(0xFF, 100, 0xFF),
+            busy_mask=0,
+            current_xyz=(0xFF, 0xFF, 0xFF),
+            target_xyz=(0xFF, 0xFF, 0xFF),
             fault_mask=0,
             fault_mask=0,
         )
         )
         frame = protocol.decode_frame(wire)
         frame = protocol.decode_frame(wire)
@@ -126,9 +142,10 @@ class Prod2UP4ProtocolV3Tests(unittest.TestCase):
 
 
         self.assertEqual(len(frame.payload), 10)
         self.assertEqual(len(frame.payload), 10)
         self.assertEqual(len(wire), 26)
         self.assertEqual(len(wire), 26)
-        self.assertEqual(status.busy_mask, 0x03)
-        self.assertEqual(status.current_xyz, (0xFF, 0xFE, 0xFF))
-        self.assertEqual(status.target_xyz, (0xFF, 100, 0xFF))
+        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)
         self.assertEqual(status.fault_mask, 0)
 
 
     def test_versioned_host_contract_matches_minimal_motion_semantics(self) -> None:
     def test_versioned_host_contract_matches_minimal_motion_semantics(self) -> None:
@@ -151,12 +168,26 @@ class Prod2UP4ProtocolV3Tests(unittest.TestCase):
         self.assertEqual(contract["commands"]["jog"]["step_range"], [1, 65535])
         self.assertEqual(contract["commands"]["jog"]["step_range"], [1, 65535])
         self.assertEqual(contract["commands"]["jog"]["cli_axes"], ["X", "Y"])
         self.assertEqual(contract["commands"]["jog"]["cli_axes"], ["X", "Y"])
         self.assertEqual(contract["commands"]["jog"]["reserved_z_status"], "BAD_VALUE")
         self.assertEqual(contract["commands"]["jog"]["reserved_z_status"], "BAD_VALUE")
-        self.assertEqual(contract["commands"]["jog"]["executed_step_cap"], 800)
-        self.assertEqual(contract["commands"]["jog"]["over_cap_status"], "OK")
+        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(
         self.assertEqual(
             contract["commands"]["jog"]["same_axis_active_policy"],
             contract["commands"]["jog"]["same_axis_active_policy"],
-            "REPLACE_LATEST_AFTER_CURRENT_FULL_STEP",
+            "IMMEDIATE_RELOAD_AND_RESTART_DIR_SETUP",
         )
         )
+        self.assertEqual(contract["commands"]["jog"]["multiple_pending_policy"], "NONE")
         self.assertFalse(contract["commands"]["jog"]["rejects_busy"])
         self.assertFalse(contract["commands"]["jog"]["rejects_busy"])
         self.assertEqual(
         self.assertEqual(
             contract["commands"]["jog"]["admission_ignores"],
             contract["commands"]["jog"]["admission_ignores"],
@@ -169,28 +200,66 @@ class Prod2UP4ProtocolV3Tests(unittest.TestCase):
         )
         )
         self.assertEqual(
         self.assertEqual(
             contract["commands"]["jog"]["watchdog_timeout_recovery"],
             contract["commands"]["jog"]["watchdog_timeout_recovery"],
-            "CLEAR_TIMEOUT_REARM_WITHOUT_DISABLE",
+            "NOT_APPLICABLE_TIMEOUT_HAS_NO_MOTOR_EFFECT",
         )
         )
         self.assertEqual(contract["commands"]["jog"]["limit_policy"], "IGNORE_ALL_INPUTS")
         self.assertEqual(contract["commands"]["jog"]["limit_policy"], "IGNORE_ALL_INPUTS")
-        self.assertEqual(contract["motion"]["standard_open"], {"direction": 0, "steps": 3200, "checks_limit": False})
-        self.assertEqual(contract["motion"]["standard_close"], {"direction": 1, "steps": 3200, "checks_limit": False})
-        self.assertEqual(contract["motion"]["snapshot_arbitration_signal"], "AXIS_ACTIVE")
         self.assertEqual(
         self.assertEqual(
-            contract["commands"]["set_output_snapshot"]["active_axis_precedence"],
-            "BUSY_IGNORED_BEFORE_TARGET_VALIDATION",
+            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(
         self.assertEqual(
             contract["responses"]["motion_status"]["busy_semantic"],
             contract["responses"]["motion_status"]["busy_semantic"],
-            "FIRST_STEP_RISE_THROUGH_FINAL_LOW",
+            "ALWAYS_ZERO",
         )
         )
         self.assertEqual(
         self.assertEqual(
             contract["responses"]["motion_status"]["busy_role"],
             contract["responses"]["motion_status"]["busy_role"],
-            "READ_ONLY_TELEMETRY_NOT_JOG_ADMISSION",
+            "RESERVED_CONSTANT_ZERO",
         )
         )
-        self.assertFalse(contract["watchdog"]["expiry_requires_disable_before_rearm"])
-        self.assertTrue(contract["watchdog"]["next_valid_jog_clears_timeout_and_rearms"])
+        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["watchdog"]["status_query_cannot_arm_or_revive"])
-        self.assertEqual(contract["limit"]["used_only_for"], "NOT_USED_BY_FORCE_JOG_IMAGE")
+        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)
         self.assertEqual(contract["responses"]["motion_status"]["fault_mask"], 0)
 
 
     def test_host_contract_schema_freezes_force_jog_v1_semantics(self) -> None:
     def test_host_contract_schema_freezes_force_jog_v1_semantics(self) -> None:
@@ -208,16 +277,53 @@ class Prod2UP4ProtocolV3Tests(unittest.TestCase):
 
 
         self.assertEqual(jog_properties["$ref"], "#/$defs/jogCommand")
         self.assertEqual(jog_properties["$ref"], "#/$defs/jogCommand")
         self.assertEqual(snapshot_properties["$ref"], "#/$defs/snapshotCommand")
         self.assertEqual(snapshot_properties["$ref"], "#/$defs/snapshotCommand")
-        self.assertEqual(motion_properties["snapshot_arbitration_signal"]["const"], "AXIS_ACTIVE")
-        self.assertEqual(status_properties["busy_semantic"]["const"], "FIRST_STEP_RISE_THROUGH_FINAL_LOW")
+        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(
         self.assertEqual(
             status_properties["busy_role"]["const"],
             status_properties["busy_role"]["const"],
-            "READ_ONLY_TELEMETRY_NOT_JOG_ADMISSION",
+            "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",
         )
         )
-        self.assertEqual(limit_properties["used_only_for"]["const"], "NOT_USED_BY_FORCE_JOG_IMAGE")
 
 
         jog_definition = schema["$defs"]["jogCommand"]
         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"]["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(
         self.assertEqual(
             jog_definition["properties"]["admission_ignores"]["const"],
             jog_definition["properties"]["admission_ignores"]["const"],
             [
             [
@@ -228,13 +334,21 @@ class Prod2UP4ProtocolV3Tests(unittest.TestCase):
             ],
             ],
         )
         )
         watchdog_properties = schema["properties"]["watchdog"]["properties"]
         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(
         self.assertEqual(
-            watchdog_properties["expiry_requires_disable_before_rearm"]["const"],
-            False,
+            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(
         self.assertEqual(
-            watchdog_properties["next_valid_jog_clears_timeout_and_rearms"]["const"],
-            True,
+            motion_schema["motor_stop_sources"]["const"],
+            ["RESET", "POWER_LOSS", "RECONFIGURATION"],
         )
         )
 
 
     def test_host_contract_machine_freezes_header_offsets_and_crc_parameters(self) -> None:
     def test_host_contract_machine_freezes_header_offsets_and_crc_parameters(self) -> None:

+ 136 - 2
tests/unit/test_prod2u_p4_send_hex_template.py

@@ -16,6 +16,14 @@ TOOLS = ROOT / "tools"
 SEND_HEX = TOOLS / "package_templates" / "SEND_HEX.ps1"
 SEND_HEX = TOOLS / "package_templates" / "SEND_HEX.ps1"
 INITIALIZE_DISABLE = TOOLS / "package_templates" / "INITIALIZE_DISABLE.ps1"
 INITIALIZE_DISABLE = TOOLS / "package_templates" / "INITIALIZE_DISABLE.ps1"
 RUNTIME_MARKER = "# SEND_HEX_RUNTIME_START"
 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))
 sys.path.insert(0, str(TOOLS))
 
 
 import prod2u_p4_protocol as protocol  # noqa: E402
 import prod2u_p4_protocol as protocol  # noqa: E402
@@ -70,6 +78,53 @@ try {{
         )
         )
 
 
 
 
+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:
 def _ordinary_request() -> bytes:
     return protocol.build_host_command(command=protocol.CommandId.GET_STATUS)
     return protocol.build_host_command(command=protocol.CommandId.GET_STATUS)
 
 
@@ -93,7 +148,7 @@ def _motor_status_pair() -> tuple[bytes, bytes, bytes]:
         result_flags=0x08,
         result_flags=0x08,
     )
     )
     status = protocol.build_motion_status(
     status = protocol.build_motion_status(
-        flags=0,
+        flags=0x02,
         position_valid_mask=0,
         position_valid_mask=0,
         busy_mask=0,
         busy_mask=0,
         current_xyz=(0xFF, 0xFF, 0xFF),
         current_xyz=(0xFF, 0xFF, 0xFF),
@@ -149,9 +204,12 @@ class Prod2UP4SendHexTemplateTests(unittest.TestCase):
 
 
         self.assertRejected(_ordinary_request(), response, r"(?i)device rejected.*BUSY")
         self.assertRejected(_ordinary_request(), response, r"(?i)device rejected.*BUSY")
 
 
-        initialize = INITIALIZE_DISABLE.read_text(encoding="utf-8", errors="strict")
+        initialize = INITIALIZE_DISABLE.read_bytes().decode("ascii")
         self.assertIn("SEND_HEX.ps1", initialize)
         self.assertIn("SEND_HEX.ps1", initialize)
         self.assertRegex(initialize, r"(?i)exit\s+\$LASTEXITCODE")
         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:
     def test_ack_ok_and_status_must_agree(self) -> None:
         for ok, status in (
         for ok, status in (
@@ -244,6 +302,82 @@ class Prod2UP4SendHexTemplateTests(unittest.TestCase):
             with self.subTest(pattern=pattern):
             with self.subTest(pattern=pattern):
                 self.assertRejected(request, response, 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__":
 if __name__ == "__main__":
     unittest.main()
     unittest.main()

+ 16 - 21
tests/unit/test_prod2u_p4_td_cdc_structure.py

@@ -15,17 +15,16 @@ PHY = ROOT / "td" / "phy" / "prod2u_p4_normal_v3.tcl"
 
 
 
 
 class Prod2UP4TdCdcStructureTests(unittest.TestCase):
 class Prod2UP4TdCdcStructureTests(unittest.TestCase):
-    def test_each_axis_owns_a_three_stage_async_limit_synchronizer(self) -> None:
+    def test_limit_inputs_have_no_axis_synchronizer_or_hub_connection(self) -> None:
         axis = AXIS.read_text(encoding="ascii")
         axis = AXIS.read_text(encoding="ascii")
         hub = (ROOT / "src" / "rtl" / "prod2u_p4_motor_hub.v").read_text(encoding="ascii")
         hub = (ROOT / "src" / "rtl" / "prod2u_p4_motor_hub.v").read_text(encoding="ascii")
 
 
-        self.assertEqual(axis.count('(* async_reg = "true" *) reg [2:0] limit_sync_pipe;'), 1)
-        self.assertIn("limit_sync_pipe <= {limit_sync_pipe[1:0], limit_raw};", axis)
-        self.assertIn("limit_sync_pipe[2]", axis)
+        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_x_axis ("), 1)
         self.assertEqual(hub.count(") u_y_axis ("), 1)
         self.assertEqual(hub.count(") u_y_axis ("), 1)
-        self.assertIn(".limit_raw(x_limit_raw)", hub)
-        self.assertIn(".limit_raw(y_limit_raw)", hub)
+        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())
         self.assertFalse((ROOT / "src" / "rtl" / "prod2u_p4_limit_filter.v").exists())
 
 
     def test_motion_phase_has_exact_four_state_sequential_encoding(self) -> None:
     def test_motion_phase_has_exact_four_state_sequential_encoding(self) -> None:
@@ -39,7 +38,7 @@ class Prod2UP4TdCdcStructureTests(unittest.TestCase):
         observed = {
         observed = {
             name: int(value)
             name: int(value)
             for name, value in re.findall(
             for name, value in re.findall(
-                r"localparam \[2:0\] (PHASE_[A-Z_]+) = 3'd([0-7]);",
+                r"localparam \[1:0\] (PHASE_[A-Z_]+) = 2'd([0-3]);",
                 axis,
                 axis,
             )
             )
         }
         }
@@ -49,18 +48,12 @@ class Prod2UP4TdCdcStructureTests(unittest.TestCase):
             '(* keep = "true", syn_encoding = "sequential", fsm_encoding = "none" *)',
             '(* keep = "true", syn_encoding = "sequential", fsm_encoding = "none" *)',
             axis,
             axis,
         )
         )
-        self.assertRegex(axis, r"reg \[2:0\] motion_phase;")
+        self.assertRegex(axis, r"reg \[1:0\] motion_phase;")
 
 
-    def test_syn_and_phy_track_exact_eight_cdc_registers(self) -> None:
+    def test_syn_and_phy_track_only_two_uart_cdc_registers(self) -> None:
         expected_patterns = {
         expected_patterns = {
             "*/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_core/u_motors/u_x_axis/limit_sync_pipe[0]",
-            "*/u_core/u_motors/u_x_axis/limit_sync_pipe[1]",
-            "*/u_core/u_motors/u_x_axis/limit_sync_pipe[2]",
-            "*/u_core/u_motors/u_y_axis/limit_sync_pipe[0]",
-            "*/u_core/u_motors/u_y_axis/limit_sync_pipe[1]",
-            "*/u_core/u_motors/u_y_axis/limit_sync_pipe[2]",
         }
         }
         for path in (SYN, PHY):
         for path in (SYN, PHY):
             source = path.read_text(encoding="ascii")
             source = path.read_text(encoding="ascii")
@@ -68,13 +61,12 @@ class Prod2UP4TdCdcStructureTests(unittest.TestCase):
             observed = {line.strip() for line in block.splitlines() if line.strip()}
             observed = {line.strip() for line in block.splitlines() if line.strip()}
             with self.subTest(path=path.name):
             with self.subTest(path=path.name):
                 self.assertEqual(observed, expected_patterns)
                 self.assertEqual(observed, expected_patterns)
-                self.assertIn("retained_sync_register_total", source)
+                self.assertIn("if {[llength $cdc_regs] != 2}", source)
+                self.assertNotIn("limit_sync_pipe", source)
 
 
-    def test_only_async_input_to_first_stage_paths_are_false_pathed(self) -> None:
+    def test_only_uart_input_to_first_stage_is_false_pathed(self) -> None:
         expected_pairs = {
         expected_pairs = {
             "host_uart_rx */u_uart_rx/rx_sync_pipe[0]",
             "host_uart_rx */u_uart_rx/rx_sync_pipe[0]",
-            "x_limit_raw */u_core/u_motors/u_x_axis/limit_sync_pipe[0]",
-            "y_limit_raw */u_core/u_motors/u_y_axis/limit_sync_pipe[0]",
         }
         }
         for path in (SYN, PHY):
         for path in (SYN, PHY):
             source = path.read_text(encoding="ascii")
             source = path.read_text(encoding="ascii")
@@ -83,6 +75,8 @@ class Prod2UP4TdCdcStructureTests(unittest.TestCase):
             with self.subTest(path=path.name):
             with self.subTest(path=path.name):
                 self.assertEqual(observed, expected_pairs)
                 self.assertEqual(observed, expected_pairs)
                 self.assertEqual(source.count("set_false_path -from"), 2)
                 self.assertEqual(source.count("set_false_path -from"), 2)
+                self.assertNotIn("x_limit_raw", source)
+                self.assertNotIn("y_limit_raw", source)
 
 
     def test_td_structure_discovery_is_advisory_and_has_source_only_fallback(self) -> None:
     def test_td_structure_discovery_is_advisory_and_has_source_only_fallback(self) -> None:
         for path in (SYN, PHY):
         for path in (SYN, PHY):
@@ -100,14 +94,15 @@ class Prod2UP4TdCdcStructureTests(unittest.TestCase):
                 self.assertIn("CDC_GATE_ADVISORY_FAIL=", source)
                 self.assertIn("CDC_GATE_ADVISORY_FAIL=", source)
                 self.assertIn("FSM_ENCODING_GATE_ADVISORY_FAIL=", source)
                 self.assertIn("FSM_ENCODING_GATE_ADVISORY_FAIL=", source)
 
 
-    def test_td_reports_x_and_y_three_bit_sequential_motion_phase(self) -> None:
+    def test_td_reports_x_and_y_two_bit_sequential_motion_phase(self) -> None:
         for path in (SYN, PHY):
         for path in (SYN, PHY):
             source = path.read_text(encoding="ascii")
             source = path.read_text(encoding="ascii")
             with self.subTest(path=path.name):
             with self.subTest(path=path.name):
                 self.assertIn("schema=prod2u-p4-normal-v3-fsm-encoding-v2", source)
                 self.assertIn("schema=prod2u-p4-normal-v3-fsm-encoding-v2", source)
                 self.assertIn("x {*/u_core/u_motors/u_x_axis/motion_phase*}", source)
                 self.assertIn("x {*/u_core/u_motors/u_x_axis/motion_phase*}", source)
                 self.assertIn("y {*/u_core/u_motors/u_y_axis/motion_phase*}", source)
                 self.assertIn("y {*/u_core/u_motors/u_y_axis/motion_phase*}", source)
-                self.assertIn("/motion_phase\\[[0-2]\\]$", source)
+                self.assertIn("/motion_phase\\[[0-1]\\]$", source)
+                self.assertNotIn("/motion_phase\\[[0-2]\\]$", source)
                 self.assertIn("motion_phase=${axis}:[llength $matches]:sequential", source)
                 self.assertIn("motion_phase=${axis}:[llength $matches]:sequential", source)
 
 
 
 

+ 250 - 35
tools/package_prod2u_p4_normal_v3.ps1

@@ -2,11 +2,14 @@ param(
     [Parameter(Mandatory = $true)][string]$OutputDir,
     [Parameter(Mandatory = $true)][string]$OutputDir,
     [Parameter(Mandatory = $true)][string]$NormalBitstream,
     [Parameter(Mandatory = $true)][string]$NormalBitstream,
     [Parameter(Mandatory = $true)][string]$TdReceipt,
     [Parameter(Mandatory = $true)][string]$TdReceipt,
-    [Parameter(Mandatory = $true)][string]$ConfirmationTdReceipt,
+    [AllowEmptyString()][string]$ConfirmationTdReceipt = "",
     [string[]]$ValidationReceipt = @(),
     [string[]]$ValidationReceipt = @(),
     [string]$HostContract = "",
     [string]$HostContract = "",
     [string]$Commit = "",
     [string]$Commit = "",
-    [string]$WheelhouseRoot = ""
+    [string]$WheelhouseRoot = "",
+    [ValidateSet("python", "icarus", "verilator", "cocotb", "formal", "td_confirmation")]
+    [string[]]$RunningValidationLayer = @(),
+    [switch]$UrgentSingleTd
 )
 )
 
 
 Set-StrictMode -Version Latest
 Set-StrictMode -Version Latest
@@ -18,6 +21,21 @@ $readmeSourceRelative = "docs/prod2u-p4-normal-v3-runbook.zh-CN.md"
 $hostContractSchemaRelative = "schemas/prod2u_p4_normal_host_contract_v4.schema.json"
 $hostContractSchemaRelative = "schemas/prod2u_p4_normal_host_contract_v4.schema.json"
 $hardwareBindingRelative = "config/prod2u_p4_normal_v3_hw_binding.json"
 $hardwareBindingRelative = "config/prod2u_p4_normal_v3_hw_binding.json"
 $verificationTargetsRelative = "config/prod2u_p4_verification_targets_v1.json"
 $verificationTargetsRelative = "config/prod2u_p4_verification_targets_v1.json"
+$tdReceiptSchema = "prod2u-p4-normal-v3-td-build-receipt-v2"
+$validationLayerNames = @(
+    "python", "icarus", "verilator", "cocotb", "formal",
+    "td_primary", "td_confirmation", "td_primary_artifacts",
+    "td_confirmation_artifacts", "td_confirmation_bitstream",
+    "td_confirmation_synthesis", "td_confirmation_manifest",
+    "resource_primary", "resource_confirmation", "package_selftest"
+)
+$verificationEvidenceLayers = @(
+    "python", "icarus", "verilator", "cocotb", "formal",
+    "td_primary", "td_confirmation", "td_primary_artifacts",
+    "td_confirmation_artifacts", "td_confirmation_bitstream",
+    "td_confirmation_synthesis", "td_confirmation_manifest",
+    "resource_primary", "resource_confirmation"
+)
 $templateRelatives = @(
 $templateRelatives = @(
     "tools/package_templates/bootstrap.ps1",
     "tools/package_templates/bootstrap.ps1",
     "tools/package_templates/selftest.ps1",
     "tools/package_templates/selftest.ps1",
@@ -36,6 +54,13 @@ function Assert-File([string]$Path, [string]$Label) {
     }
     }
 }
 }
 
 
+function Assert-NonEmptyFile([string]$Path, [string]$Label) {
+    Assert-File $Path $Label
+    if ((Get-Item -LiteralPath $Path).Length -le 0) {
+        throw "$Label is empty: $Path"
+    }
+}
+
 function Resolve-Git {
 function Resolve-Git {
     $git = Get-Command git.exe -ErrorAction SilentlyContinue
     $git = Get-Command git.exe -ErrorAction SilentlyContinue
     if (-not $git) { $git = Get-Command git -ErrorAction SilentlyContinue }
     if (-not $git) { $git = Get-Command git -ErrorAction SilentlyContinue }
@@ -79,6 +104,17 @@ function Assert-CleanCommittedSources(
     $diffExit = $LASTEXITCODE
     $diffExit = $LASTEXITCODE
     if ($diffExit -eq 1) { throw "repository has tracked source changes outside .planning/" }
     if ($diffExit -eq 1) { throw "repository has tracked source changes outside .planning/" }
     if ($diffExit -ne 0) { throw "unable to verify repository tracked source state" }
     if ($diffExit -ne 0) { throw "unable to verify repository tracked source state" }
+    $statusLines = @(& $Git -C $repo status --porcelain=v1 --untracked-files=all)
+    if ($LASTEXITCODE -ne 0) { throw "unable to verify repository untracked source state" }
+    $unexpected = @(
+        $statusLines | Where-Object {
+            $relative = ([string]$_).Substring(3).Replace('\', '/')
+            -not ($relative -eq ".planning" -or $relative.StartsWith(".planning/"))
+        }
+    )
+    if ($unexpected.Count -gt 0) {
+        throw ("repository has untracked or modified files outside .planning/: " + ($unexpected -join ", "))
+    }
     foreach ($relative in $Relatives) {
     foreach ($relative in $Relatives) {
         $saved = $ErrorActionPreference
         $saved = $ErrorActionPreference
         $ErrorActionPreference = "SilentlyContinue"
         $ErrorActionPreference = "SilentlyContinue"
@@ -91,6 +127,107 @@ function Assert-CleanCommittedSources(
     }
     }
 }
 }
 
 
+function Assert-PrimaryPinBinding([object]$Receipt) {
+    $gate = Get-PropertyValue $Receipt "post_route_pin_gate"
+    if ($null -eq $gate -or [string](Get-PropertyValue $gate "status") -ne "pass") {
+        throw "Primary TD pin gate is not pass"
+    }
+    if ([int](Get-PropertyValue $gate "row_count") -ne 41) {
+        throw "Primary TD pin gate row count is not 41"
+    }
+    $failures = @(Get-PropertyValue $gate "failures")
+    if ($failures.Count -ne 0) {
+        throw "Primary TD pin gate contains failures"
+    }
+    $observed = Get-PropertyValue $gate "observed"
+    $expected = [ordered]@{
+        motor_en_n = @("A10", "OUTPUT", "LVCMOS33", "NONE")
+        x_step = @("C11", "OUTPUT", "LVCMOS33", "NONE")
+        x_dir = @("B12", "OUTPUT", "LVCMOS33", "NONE")
+        y_step = @("D15", "OUTPUT", "LVCMOS33", "NONE")
+        y_dir = @("H14", "OUTPUT", "LVCMOS33", "NONE")
+        x_limit_raw = @("B9", "INPUT", "LVCMOS33", "PULLUP")
+        y_limit_raw = @("A11", "INPUT", "LVCMOS33", "PULLUP")
+    }
+    foreach ($name in $expected.Keys) {
+        $record = Get-PropertyValue $observed $name
+        if ($null -eq $record -or
+            [string](Get-PropertyValue $record "location") -ne $expected[$name][0] -or
+            [string](Get-PropertyValue $record "direction") -ne $expected[$name][1] -or
+            [string](Get-PropertyValue $record "io_standard") -ne $expected[$name][2] -or
+            [string](Get-PropertyValue $record "pull_type") -ne $expected[$name][3]) {
+            throw "Primary TD pin binding mismatch: $name"
+        }
+    }
+    foreach ($property in @($observed.PSObject.Properties)) {
+        if ([string](Get-PropertyValue $property.Value "location") -eq "A5") {
+            throw "Primary TD pin gate assigns forbidden pin A5"
+        }
+    }
+}
+
+function Assert-PrimaryReceiptBinding(
+    [object]$Receipt,
+    [string]$ResolvedCommit,
+    [string]$BitstreamSha256
+) {
+    if ([string](Get-PropertyValue $Receipt "schema") -ne $tdReceiptSchema) {
+        throw "Primary TD receipt schema mismatch"
+    }
+    $sourceState = Get-PropertyValue $Receipt "source_state"
+    if ($null -eq $sourceState -or
+        (Get-PropertyValue $sourceState "clean") -ne $true -or
+        [string](Get-PropertyValue $sourceState "commit") -ne $ResolvedCommit) {
+        throw "Primary TD receipt source state is not clean and commit-bound"
+    }
+    $sourceBinding = Get-PropertyValue $Receipt "source_binding_gate"
+    if ($null -eq $sourceBinding -or
+        [string](Get-PropertyValue $sourceBinding "status") -ne "pass") {
+        throw "Primary TD receipt source binding gate is not pass"
+    }
+    $bindingGate = Get-PropertyValue $Receipt "binding_gate"
+    if ($null -eq $bindingGate -or
+        [string](Get-PropertyValue $bindingGate "status") -ne "pass") {
+        throw "Primary TD receipt device binding gate is not pass"
+    }
+    $synthesisInputHash = [string](Get-PropertyValue $Receipt "synthesis_input_hash")
+    if ($synthesisInputHash -notmatch '^[0-9a-f]{64}$') {
+        throw "Primary TD receipt synthesis input hash is invalid"
+    }
+    $manifest = Get-PropertyValue $Receipt "synthesis_input_manifest"
+    $manifestHash = [string](Get-PropertyValue $manifest "sha256")
+    $manifestInputs = Get-PropertyValue $manifest "inputs"
+    if ($null -eq $manifest -or $manifestHash -ne $synthesisInputHash -or
+        $null -eq $manifestInputs -or @($manifestInputs.PSObject.Properties).Count -eq 0) {
+        throw "Primary TD receipt synthesis manifest is not hash-bound"
+    }
+
+    $candidates = @()
+    $direct = Get-PropertyValue $Receipt "bitstream"
+    if ($null -ne $direct) { $candidates += $direct }
+    $measurements = Get-PropertyValue $Receipt "measurement_artifacts"
+    $measured = Get-PropertyValue $measurements "bitstream"
+    if ($null -ne $measured) { $candidates += $measured }
+    $artifactBound = $false
+    foreach ($candidate in $candidates) {
+        $path = [string](Get-PropertyValue $candidate "path")
+        $declaredHash = [string](Get-PropertyValue $candidate "sha256")
+        $declaredSize = Get-PropertyValue $candidate "size"
+        if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { continue }
+        $item = Get-Item -LiteralPath $path
+        if ($item.Length -le 0) { continue }
+        if ($null -ne $declaredSize -and [int64]$declaredSize -ne $item.Length) { continue }
+        if ($declaredHash -and $declaredHash -ne $BitstreamSha256) { continue }
+        if ((Get-Sha256 $path) -eq $BitstreamSha256) {
+            $artifactBound = $true
+            break
+        }
+    }
+    if (-not $artifactBound) {
+        throw "Primary TD receipt bitstream artifact is not hash-bound"
+    }
+}
+
 function New-CommitSourceSnapshot(
 function New-CommitSourceSnapshot(
     [string]$Git,
     [string]$Git,
     [string]$ResolvedCommit,
     [string]$ResolvedCommit,
@@ -144,12 +281,23 @@ function Get-PropertyValue([object]$Value, [string]$Name) {
 function Normalize-ValidationStatus([object]$Value) {
 function Normalize-ValidationStatus([object]$Value) {
     $status = [string]$Value
     $status = [string]$Value
     if ($status -eq "pass") { return "pass" }
     if ($status -eq "pass") { return "pass" }
+    if ($status -eq "running") { return "running" }
     if ($status -eq "not_run" -or $status -eq "skipped" -or $status.StartsWith("blocked")) {
     if ($status -eq "not_run" -or $status -eq "skipped" -or $status.StartsWith("blocked")) {
         return "not_run"
         return "not_run"
     }
     }
     return "fail"
     return "fail"
 }
 }
 
 
+function Get-ValidationStatusRank([string]$Status) {
+    switch ($Status) {
+        "fail" { return 4 }
+        "running" { return 3 }
+        "not_run" { return 2 }
+        "pass" { return 1 }
+        default { return 4 }
+    }
+}
+
 function New-ValidationLayer([string]$Status, [string]$Source, [object]$OriginalStatus) {
 function New-ValidationLayer([string]$Status, [string]$Source, [object]$OriginalStatus) {
     return [ordered]@{
     return [ordered]@{
         status = $Status
         status = $Status
@@ -164,7 +312,37 @@ function Set-ValidationLayer(
     [object]$Status,
     [object]$Status,
     [string]$Source
     [string]$Source
 ) {
 ) {
-    $Layers[$Name] = New-ValidationLayer (Normalize-ValidationStatus $Status) $Source $Status
+    $newLayer = New-ValidationLayer (Normalize-ValidationStatus $Status) $Source $Status
+    $existing = $Layers[$Name]
+    if ($null -eq $existing -or
+        [string]$existing.source -eq "not_provided" -or
+        ([string]$existing.source -eq "declared_running" -and $Source -ne "declared_running")) {
+        $Layers[$Name] = $newLayer
+        return
+    }
+    if ((Get-ValidationStatusRank $newLayer.status) -gt
+        (Get-ValidationStatusRank ([string]$existing.status))) {
+        $Layers[$Name] = $newLayer
+    }
+}
+
+function Test-VerificationComplete(
+    [System.Collections.IDictionary]$Layers,
+    [string]$DeliveryMode
+) {
+    if ($DeliveryMode -ne "normal_dual_td") { return $false }
+    foreach ($name in $verificationEvidenceLayers) {
+        if ([string]$Layers[$name].status -ne "pass") { return $false }
+    }
+    return $true
+}
+
+function Get-ValidationSummaryStatus([System.Collections.IDictionary]$Layers) {
+    $statuses = @($Layers.Values | ForEach-Object { [string]$_.status })
+    if ($statuses -contains "fail") { return "fail" }
+    if ($statuses -contains "running") { return "running" }
+    if ($statuses -contains "not_run") { return "not_run" }
+    return "pass"
 }
 }
 
 
 function Merge-ValidationReceipt(
 function Merge-ValidationReceipt(
@@ -357,9 +535,20 @@ function Invoke-FolderSelftest([string]$Root) {
     }
     }
 }
 }
 
 
-Assert-File $NormalBitstream "Normal bitstream"
+Assert-NonEmptyFile $NormalBitstream "Normal bitstream"
 Assert-File $TdReceipt "Primary TD build receipt"
 Assert-File $TdReceipt "Primary TD build receipt"
-Assert-File $ConfirmationTdReceipt "Confirmation TD build receipt"
+$deliveryMode = if ($UrgentSingleTd) { "urgent_single_td" } else { "normal_dual_td" }
+$confirmationTdPresent = -not [string]::IsNullOrWhiteSpace($ConfirmationTdReceipt)
+if ($UrgentSingleTd) {
+    if ($confirmationTdPresent) {
+        throw "Urgent single-TD mode must not include a Confirmation TD build receipt"
+    }
+} else {
+    if (-not $confirmationTdPresent) {
+        throw "Confirmation TD build receipt is required in normal dual-TD mode"
+    }
+    Assert-File $ConfirmationTdReceipt "Confirmation TD build receipt"
+}
 Assert-File $HostContract "Normal v3 host contract"
 Assert-File $HostContract "Normal v3 host contract"
 foreach ($receipt in $ValidationReceipt) {
 foreach ($receipt in $ValidationReceipt) {
     Assert-File $receipt "Validation receipt"
     Assert-File $receipt "Validation receipt"
@@ -384,24 +573,32 @@ Assert-CleanCommittedSources $git $resolvedCommit $sourceRelatives
 
 
 $bitstreamSha256 = Get-Sha256 $NormalBitstream
 $bitstreamSha256 = Get-Sha256 $NormalBitstream
 $tdPrimary = Read-Json $TdReceipt "Primary TD build receipt"
 $tdPrimary = Read-Json $TdReceipt "Primary TD build receipt"
-$tdConfirmation = Read-Json $ConfirmationTdReceipt "Confirmation TD build receipt"
 if ([string](Get-PropertyValue $tdPrimary "commit") -ne $resolvedCommit) {
 if ([string](Get-PropertyValue $tdPrimary "commit") -ne $resolvedCommit) {
     throw "Primary TD receipt commit does not match package commit"
     throw "Primary TD receipt commit does not match package commit"
 }
 }
 if ([string](Get-PropertyValue $tdPrimary "bitstream_sha256") -ne $bitstreamSha256) {
 if ([string](Get-PropertyValue $tdPrimary "bitstream_sha256") -ne $bitstreamSha256) {
     throw "Primary TD receipt bitstream hash does not match package bitstream"
     throw "Primary TD receipt bitstream hash does not match package bitstream"
 }
 }
+Assert-PrimaryReceiptBinding $tdPrimary $resolvedCommit $bitstreamSha256
+Assert-PrimaryPinBinding $tdPrimary
 $synthesisInputHash = [string](Get-PropertyValue $tdPrimary "synthesis_input_hash")
 $synthesisInputHash = [string](Get-PropertyValue $tdPrimary "synthesis_input_hash")
-$confirmationCommit = [string](Get-PropertyValue $tdConfirmation "commit")
-if ($confirmationCommit -ne $resolvedCommit) {
-    throw "Confirmation TD receipt commit does not match package commit"
-}
-$confirmationBitstreamSha256 = Get-PropertyValue $tdConfirmation "bitstream_sha256"
-$confirmationSynthesisInputHash = Get-PropertyValue $tdConfirmation "synthesis_input_hash"
 $primaryManifest = Get-PropertyValue $tdPrimary "synthesis_input_manifest"
 $primaryManifest = Get-PropertyValue $tdPrimary "synthesis_input_manifest"
-$confirmationManifest = Get-PropertyValue $tdConfirmation "synthesis_input_manifest"
 $primaryManifestSha256 = Get-PropertyValue $primaryManifest "sha256"
 $primaryManifestSha256 = Get-PropertyValue $primaryManifest "sha256"
-$confirmationManifestSha256 = Get-PropertyValue $confirmationManifest "sha256"
+$tdConfirmation = $null
+$confirmationBitstreamSha256 = $null
+$confirmationSynthesisInputHash = $null
+$confirmationManifestSha256 = $null
+if ($confirmationTdPresent) {
+    $tdConfirmation = Read-Json $ConfirmationTdReceipt "Confirmation TD build receipt"
+    $confirmationCommit = [string](Get-PropertyValue $tdConfirmation "commit")
+    if ($confirmationCommit -ne $resolvedCommit) {
+        throw "Confirmation TD receipt commit does not match package commit"
+    }
+    $confirmationBitstreamSha256 = Get-PropertyValue $tdConfirmation "bitstream_sha256"
+    $confirmationSynthesisInputHash = Get-PropertyValue $tdConfirmation "synthesis_input_hash"
+    $confirmationManifest = Get-PropertyValue $tdConfirmation "synthesis_input_manifest"
+    $confirmationManifestSha256 = Get-PropertyValue $confirmationManifest "sha256"
+}
 
 
 $outFull = [System.IO.Path]::GetFullPath($OutputDir)
 $outFull = [System.IO.Path]::GetFullPath($OutputDir)
 $commitRoot = Join-Path $outFull $resolvedCommit
 $commitRoot = Join-Path $outFull $resolvedCommit
@@ -429,7 +626,9 @@ try {
     $packagedConfirmationReceipt = Join-Path $evidenceDir "td-confirmation-receipt.json"
     $packagedConfirmationReceipt = Join-Path $evidenceDir "td-confirmation-receipt.json"
     Copy-Item -LiteralPath $NormalBitstream -Destination $packagedBitstream
     Copy-Item -LiteralPath $NormalBitstream -Destination $packagedBitstream
     Copy-Item -LiteralPath $TdReceipt -Destination $packagedPrimaryReceipt
     Copy-Item -LiteralPath $TdReceipt -Destination $packagedPrimaryReceipt
-    Copy-Item -LiteralPath $ConfirmationTdReceipt -Destination $packagedConfirmationReceipt
+    if ($confirmationTdPresent) {
+        Copy-Item -LiteralPath $ConfirmationTdReceipt -Destination $packagedConfirmationReceipt
+    }
     Copy-Item -LiteralPath (Join-Path $sourceSnapshot $hostContractRelative) -Destination (Join-Path $configDir "host-contract.json")
     Copy-Item -LiteralPath (Join-Path $sourceSnapshot $hostContractRelative) -Destination (Join-Path $configDir "host-contract.json")
     Copy-Item -LiteralPath (Join-Path $sourceSnapshot $hardwareBindingRelative) -Destination (Join-Path $configDir "prod2u_p4_normal_v3_hw_binding.json")
     Copy-Item -LiteralPath (Join-Path $sourceSnapshot $hardwareBindingRelative) -Destination (Join-Path $configDir "prod2u_p4_normal_v3_hw_binding.json")
     Copy-Item -LiteralPath (Join-Path $sourceSnapshot $verificationTargetsRelative) -Destination (Join-Path $configDir "prod2u_p4_verification_targets_v1.json")
     Copy-Item -LiteralPath (Join-Path $sourceSnapshot $verificationTargetsRelative) -Destination (Join-Path $configDir "prod2u_p4_verification_targets_v1.json")
@@ -455,39 +654,44 @@ try {
     Remove-Item -LiteralPath $sourceSnapshot -Recurse -Force
     Remove-Item -LiteralPath $sourceSnapshot -Recurse -Force
 
 
     $layers = [ordered]@{}
     $layers = [ordered]@{}
-    foreach ($name in @(
-        "python", "icarus", "verilator", "cocotb", "formal",
-        "td_primary", "td_confirmation", "td_primary_artifacts",
-        "td_confirmation_artifacts", "td_confirmation_bitstream",
-        "td_confirmation_synthesis", "td_confirmation_manifest",
-        "resource_primary", "resource_confirmation", "package_selftest"
-    )) {
+    foreach ($name in $validationLayerNames) {
         $layers[$name] = New-ValidationLayer "not_run" "not_provided" "not_run"
         $layers[$name] = New-ValidationLayer "not_run" "not_provided" "not_run"
     }
     }
+    foreach ($name in $RunningValidationLayer) {
+        Set-ValidationLayer $layers $name "running" "declared_running"
+    }
     Set-ValidationLayer $layers "td_primary" (Get-PropertyValue $tdPrimary "status") "evidence/td-primary-receipt.json"
     Set-ValidationLayer $layers "td_primary" (Get-PropertyValue $tdPrimary "status") "evidence/td-primary-receipt.json"
-    Set-ValidationLayer $layers "td_confirmation" (Get-PropertyValue $tdConfirmation "status") "evidence/td-confirmation-receipt.json"
     Set-ValidationLayer $layers "resource_primary" (Get-ResourceStatus $tdPrimary) "evidence/td-primary-receipt.json"
     Set-ValidationLayer $layers "resource_primary" (Get-ResourceStatus $tdPrimary) "evidence/td-primary-receipt.json"
-    Set-ValidationLayer $layers "resource_confirmation" (Get-ResourceStatus $tdConfirmation) "evidence/td-confirmation-receipt.json"
-    Set-ValidationLayer $layers "td_confirmation_bitstream" (Get-TdBitstreamBindingStatus $tdConfirmation) "evidence/td-confirmation-receipt.json"
-    Set-ValidationLayer $layers "td_confirmation_synthesis" (Get-ComparisonStatus $confirmationSynthesisInputHash $synthesisInputHash) "evidence/td-confirmation-receipt.json"
-    Set-ValidationLayer $layers "td_confirmation_manifest" (Get-ComparisonStatus $confirmationManifestSha256 $primaryManifestSha256) "evidence/td-confirmation-receipt.json"
+    if ($confirmationTdPresent) {
+        Set-ValidationLayer $layers "td_confirmation" (Get-PropertyValue $tdConfirmation "status") "evidence/td-confirmation-receipt.json"
+        Set-ValidationLayer $layers "resource_confirmation" (Get-ResourceStatus $tdConfirmation) "evidence/td-confirmation-receipt.json"
+        Set-ValidationLayer $layers "td_confirmation_bitstream" (Get-TdBitstreamBindingStatus $tdConfirmation) "evidence/td-confirmation-receipt.json"
+        Set-ValidationLayer $layers "td_confirmation_synthesis" (Get-ComparisonStatus $confirmationSynthesisInputHash $synthesisInputHash) "evidence/td-confirmation-receipt.json"
+        Set-ValidationLayer $layers "td_confirmation_manifest" (Get-ComparisonStatus $confirmationManifestSha256 $primaryManifestSha256) "evidence/td-confirmation-receipt.json"
+    }
 
 
     $primaryArtifacts = Copy-TdArtifacts $tdPrimary (Join-Path $evidenceDir "td-primary") "evidence/td-primary"
     $primaryArtifacts = Copy-TdArtifacts $tdPrimary (Join-Path $evidenceDir "td-primary") "evidence/td-primary"
-    $confirmationArtifacts = Copy-TdArtifacts $tdConfirmation (Join-Path $evidenceDir "td-confirmation") "evidence/td-confirmation"
     $primaryPinGate = Copy-TdPinGate $tdPrimary (Join-Path $evidenceDir "td-primary\pin-gate.json") "evidence/td-primary/pin-gate.json"
     $primaryPinGate = Copy-TdPinGate $tdPrimary (Join-Path $evidenceDir "td-primary\pin-gate.json") "evidence/td-primary/pin-gate.json"
-    $confirmationPinGate = Copy-TdPinGate $tdConfirmation (Join-Path $evidenceDir "td-confirmation\pin-gate.json") "evidence/td-confirmation/pin-gate.json"
     $primaryArtifacts["pin_gate"] = $primaryPinGate
     $primaryArtifacts["pin_gate"] = $primaryPinGate
-    $confirmationArtifacts["pin_gate"] = $confirmationPinGate
     $layers["td_primary"]["artifacts"] = $primaryArtifacts
     $layers["td_primary"]["artifacts"] = $primaryArtifacts
-    $layers["td_confirmation"]["artifacts"] = $confirmationArtifacts
     Set-ValidationLayer $layers "td_primary_artifacts" (Get-ArtifactValidationStatus $primaryArtifacts) "evidence/td-primary"
     Set-ValidationLayer $layers "td_primary_artifacts" (Get-ArtifactValidationStatus $primaryArtifacts) "evidence/td-primary"
-    Set-ValidationLayer $layers "td_confirmation_artifacts" (Get-ArtifactValidationStatus $confirmationArtifacts) "evidence/td-confirmation"
+    if ($confirmationTdPresent) {
+        $confirmationArtifacts = Copy-TdArtifacts $tdConfirmation (Join-Path $evidenceDir "td-confirmation") "evidence/td-confirmation"
+        $confirmationPinGate = Copy-TdPinGate $tdConfirmation (Join-Path $evidenceDir "td-confirmation\pin-gate.json") "evidence/td-confirmation/pin-gate.json"
+        $confirmationArtifacts["pin_gate"] = $confirmationPinGate
+        $layers["td_confirmation"]["artifacts"] = $confirmationArtifacts
+        Set-ValidationLayer $layers "td_confirmation_artifacts" (Get-ArtifactValidationStatus $confirmationArtifacts) "evidence/td-confirmation"
+    }
 
 
     $validationSources = @()
     $validationSources = @()
     $validationIndex = 0
     $validationIndex = 0
     foreach ($receiptPath in $ValidationReceipt) {
     foreach ($receiptPath in $ValidationReceipt) {
         $validationIndex += 1
         $validationIndex += 1
         $receipt = Read-Json $receiptPath "Validation receipt"
         $receipt = Read-Json $receiptPath "Validation receipt"
+        $receiptCommit = Get-PropertyValue $receipt "commit"
+        if ($null -ne $receiptCommit -and [string]$receiptCommit -ne $resolvedCommit) {
+            throw "Validation receipt commit does not match package commit"
+        }
         $base = [System.IO.Path]::GetFileNameWithoutExtension($receiptPath) -replace '[^A-Za-z0-9_.-]', '_'
         $base = [System.IO.Path]::GetFileNameWithoutExtension($receiptPath) -replace '[^A-Za-z0-9_.-]', '_'
         $fileName = ("{0:D2}-{1}.json" -f $validationIndex, $base)
         $fileName = ("{0:D2}-{1}.json" -f $validationIndex, $base)
         $target = Join-Path $validationDir $fileName
         $target = Join-Path $validationDir $fileName
@@ -502,17 +706,22 @@ try {
         Merge-ValidationReceipt $layers $receipt $relative
         Merge-ValidationReceipt $layers $receipt $relative
     }
     }
 
 
+    $verificationComplete = Test-VerificationComplete $layers $deliveryMode
+
     $validationSummaryPath = Join-Path $evidenceDir "validation-summary.json"
     $validationSummaryPath = Join-Path $evidenceDir "validation-summary.json"
     $validationSummary = [ordered]@{
     $validationSummary = [ordered]@{
         schema = "prod2u-p4-normal-v3-validation-summary-v1"
         schema = "prod2u-p4-normal-v3-validation-summary-v1"
         commit = $resolvedCommit
         commit = $resolvedCommit
         bitstream_sha256 = $bitstreamSha256
         bitstream_sha256 = $bitstreamSha256
+        delivery_mode = $deliveryMode
+        verification_complete = $verificationComplete
+        confirmation_td_present = $confirmationTdPresent
         layers = $layers
         layers = $layers
         sources = @($validationSources)
         sources = @($validationSources)
         policy = [ordered]@{
         policy = [ordered]@{
             image_created_when_bitstream_nonempty = $true
             image_created_when_bitstream_nonempty = $true
             validation_failures_block_package = $false
             validation_failures_block_package = $false
-            allowed_statuses = @("pass", "fail", "not_run")
+            allowed_statuses = @("pass", "fail", "running", "not_run")
         }
         }
     }
     }
     Write-Json $validationSummaryPath $validationSummary
     Write-Json $validationSummaryPath $validationSummary
@@ -532,9 +741,12 @@ try {
         profile = "prod2u-p4-normal-actuator-binary921-v3"
         profile = "prod2u-p4-normal-actuator-binary921-v3"
         commit = $resolvedCommit
         commit = $resolvedCommit
         bitstream_sha256 = $bitstreamSha256
         bitstream_sha256 = $bitstreamSha256
+        delivery_mode = $deliveryMode
+        verification_complete = $verificationComplete
+        confirmation_td_present = $confirmationTdPresent
         confirmation_bitstream_sha256 = $confirmationBitstreamSha256
         confirmation_bitstream_sha256 = $confirmationBitstreamSha256
         td_receipt_sha256 = Get-Sha256 $packagedPrimaryReceipt
         td_receipt_sha256 = Get-Sha256 $packagedPrimaryReceipt
-        confirmation_td_receipt_sha256 = Get-Sha256 $packagedConfirmationReceipt
+        confirmation_td_receipt_sha256 = if ($confirmationTdPresent) { Get-Sha256 $packagedConfirmationReceipt } else { $null }
         validation_summary_sha256 = Get-Sha256 $validationSummaryPath
         validation_summary_sha256 = Get-Sha256 $validationSummaryPath
         package_selftest_result_sha256 = Get-Sha256 $selftestResultPath
         package_selftest_result_sha256 = Get-Sha256 $selftestResultPath
         synthesis_input_hash = $synthesisInputHash
         synthesis_input_hash = $synthesisInputHash
@@ -572,7 +784,10 @@ try {
         package = $final
         package = $final
         commit = $resolvedCommit
         commit = $resolvedCommit
         bitstream_sha256 = $bitstreamSha256
         bitstream_sha256 = $bitstreamSha256
-        validation_status = if (@($layers.Values | Where-Object { $_.status -eq "fail" }).Count -eq 0) { "pass" } else { "fail" }
+        delivery_mode = $deliveryMode
+        verification_complete = $verificationComplete
+        confirmation_td_present = $confirmationTdPresent
+        validation_status = Get-ValidationSummaryStatus $layers
         package_selftest_status = $selftestResult.status
         package_selftest_status = $selftestResult.status
     } | ConvertTo-Json -Compress
     } | ConvertTo-Json -Compress
 } finally {
 } finally {

+ 1 - 0
tools/package_templates/INITIALIZE_DISABLE.ps1

@@ -6,6 +6,7 @@ param(
 Set-StrictMode -Version Latest
 Set-StrictMode -Version Latest
 $ErrorActionPreference = "Stop"
 $ErrorActionPreference = "Stop"
 $root = Split-Path -Parent $MyInvocation.MyCommand.Path
 $root = Split-Path -Parent $MyInvocation.MyCommand.Path
+Write-Warning "DANGER: DISABLE DOES NOT STOP an active JOG in this temporary image. Only RESET, POWER-OFF, or CPLD RECONFIGURATION can STOP the motor."
 & powershell.exe -NoProfile -ExecutionPolicy Bypass -File (Join-Path $root "SEND_HEX.ps1") `
 & powershell.exe -NoProfile -ExecutionPolicy Bypass -File (Join-Path $root "SEND_HEX.ps1") `
     -Port $Port `
     -Port $Port `
     -Baud $Baud `
     -Baud $Baud `

+ 19 - 5
tools/package_templates/SEND_HEX.ps1

@@ -110,6 +110,20 @@ function Get-RequestOpcode([byte[]]$Request) {
     return [int]$requestFrame.Payload[0]
     return [int]$requestFrame.Payload[0]
 }
 }
 
 
+function Get-ResponseTimeoutMs(
+    [byte[]]$Request,
+    [int]$RequestedTimeoutMs
+) {
+    if ($RequestedTimeoutMs -le 0) {
+        throw "RequestedTimeoutMs must be positive"
+    }
+    $opcode = Get-RequestOpcode -Request $Request
+    if ($opcode -eq 0x35) {
+        return [Math]::Max($RequestedTimeoutMs, 3000)
+    }
+    return $RequestedTimeoutMs
+}
+
 function Get-StatusName([int]$Status) {
 function Get-StatusName([int]$Status) {
     switch ($Status) {
     switch ($Status) {
         0x00 { return "OK" }
         0x00 { return "OK" }
@@ -209,10 +223,9 @@ function Assert-ResponseContract([byte[]]$Request, [byte[]]$ResponseBytes) {
 # SEND_HEX_RUNTIME_START
 # SEND_HEX_RUNTIME_START
 
 
 $request = Convert-HexToBytes $Hex
 $request = Convert-HexToBytes $Hex
-[void](Get-RequestOpcode -Request $request)
-if ($TimeoutMs -le 0) {
-    throw "TimeoutMs must be positive"
-}
+$effectiveTimeoutMs = Get-ResponseTimeoutMs `
+    -Request $request `
+    -RequestedTimeoutMs $TimeoutMs
 
 
 $serial = [System.IO.Ports.SerialPort]::new($Port, $Baud, "None", 8, "One")
 $serial = [System.IO.Ports.SerialPort]::new($Port, $Baud, "None", 8, "One")
 $serial.Handshake = "None"
 $serial.Handshake = "None"
@@ -221,7 +234,7 @@ $serial.RtsEnable = $false
 $serial.ReadTimeout = 25
 $serial.ReadTimeout = 25
 $serial.WriteTimeout = 250
 $serial.WriteTimeout = 250
 $buffer = [System.Collections.Generic.List[byte]]::new()
 $buffer = [System.Collections.Generic.List[byte]]::new()
-$deadline = [DateTime]::UtcNow.AddMilliseconds($TimeoutMs)
+$deadline = [DateTime]::UtcNow.AddMilliseconds($effectiveTimeoutMs)
 $quietDeadline = $null
 $quietDeadline = $null
 
 
 try {
 try {
@@ -261,6 +274,7 @@ $result = Assert-ResponseContract -Request $request -ResponseBytes $response
     status = $result.status
     status = $result.status
     port = $Port
     port = $Port
     baud = $Baud
     baud = $Baud
+    effective_timeout_ms = $effectiveTimeoutMs
     request_hex = Convert-BytesToHex $request
     request_hex = Convert-BytesToHex $request
     request_opcode = $result.request_opcode
     request_opcode = $result.request_opcode
     ack = $result.ack
     ack = $result.ack

+ 113 - 14
tools/package_templates/selftest.ps1

@@ -1,11 +1,24 @@
 Set-StrictMode -Version Latest
 Set-StrictMode -Version Latest
 $ErrorActionPreference = "Stop"
 $ErrorActionPreference = "Stop"
 $root = Split-Path -Parent $MyInvocation.MyCommand.Path
 $root = Split-Path -Parent $MyInvocation.MyCommand.Path
+$expectedLayerNames = @(
+    "python", "icarus", "verilator", "cocotb", "formal",
+    "td_primary", "td_confirmation", "td_primary_artifacts",
+    "td_confirmation_artifacts", "td_confirmation_bitstream",
+    "td_confirmation_synthesis", "td_confirmation_manifest",
+    "resource_primary", "resource_confirmation", "package_selftest"
+)
+$verificationEvidenceLayers = @(
+    "python", "icarus", "verilator", "cocotb", "formal",
+    "td_primary", "td_confirmation", "td_primary_artifacts",
+    "td_confirmation_artifacts", "td_confirmation_bitstream",
+    "td_confirmation_synthesis", "td_confirmation_manifest",
+    "resource_primary", "resource_confirmation"
+)
 $required = @(
 $required = @(
     "fw.bit",
     "fw.bit",
     "package-info.json",
     "package-info.json",
     "evidence\td-primary-receipt.json",
     "evidence\td-primary-receipt.json",
-    "evidence\td-confirmation-receipt.json",
     "evidence\validation-summary.json",
     "evidence\validation-summary.json",
     "evidence\package-selftest-result.json",
     "evidence\package-selftest-result.json",
     "config\host-contract.json",
     "config\host-contract.json",
@@ -38,6 +51,14 @@ function Assert-ValidJson([string]$Relative) {
     }
     }
 }
 }
 
 
+function Get-ValidationSummaryStatus([object]$Layers) {
+    $statuses = @($Layers.PSObject.Properties | ForEach-Object { [string]$_.Value.status })
+    if ($statuses -contains "fail") { return "fail" }
+    if ($statuses -contains "running") { return "running" }
+    if ($statuses -contains "not_run") { return "not_run" }
+    return "pass"
+}
+
 foreach ($relative in @(
 foreach ($relative in @(
     "config\prod2u_p4_normal_v3_hw_binding.json",
     "config\prod2u_p4_normal_v3_hw_binding.json",
     "config\prod2u_p4_verification_targets_v1.json"
     "config\prod2u_p4_verification_targets_v1.json"
@@ -52,6 +73,27 @@ if ([string]$info.schema -ne "prod2u-p4-normal-v3-folder-package-info-v3") {
 if ([string]$info.profile -ne "prod2u-p4-normal-actuator-binary921-v3") {
 if ([string]$info.profile -ne "prod2u-p4-normal-actuator-binary921-v3") {
     throw "package profile mismatch"
     throw "package profile mismatch"
 }
 }
+$deliveryMode = [string]$info.delivery_mode
+if (-not ($info.verification_complete -is [bool])) {
+    throw "package verification_complete must be boolean"
+}
+if (-not ($info.confirmation_td_present -is [bool])) {
+    throw "package confirmation_td_present must be boolean"
+}
+$verificationComplete = $info.verification_complete
+$confirmationTdPresent = $info.confirmation_td_present
+if ($deliveryMode -notin @("normal_dual_td", "urgent_single_td")) {
+    throw "package delivery mode is invalid"
+}
+if ($deliveryMode -eq "normal_dual_td") {
+    if (-not $confirmationTdPresent) {
+        throw "normal dual-TD package must contain a confirmation receipt"
+    }
+} else {
+    if ($verificationComplete -or $confirmationTdPresent) {
+        throw "urgent single-TD package completeness fields disagree"
+    }
+}
 $commit = [string]$info.commit
 $commit = [string]$info.commit
 if ($commit -notmatch '^[0-9a-f]{40}$') { throw "package commit is invalid" }
 if ($commit -notmatch '^[0-9a-f]{40}$') { throw "package commit is invalid" }
 $firmware = Join-Path $root "fw.bit"
 $firmware = Join-Path $root "fw.bit"
@@ -75,8 +117,20 @@ $selftestResult = Join-Path $root "evidence\package-selftest-result.json"
 if ([string]$info.td_receipt_sha256 -ne (Get-BoundSha256 $primaryReceipt)) {
 if ([string]$info.td_receipt_sha256 -ne (Get-BoundSha256 $primaryReceipt)) {
     throw "primary TD receipt hash mismatch"
     throw "primary TD receipt hash mismatch"
 }
 }
-if ([string]$info.confirmation_td_receipt_sha256 -ne (Get-BoundSha256 $confirmationReceipt)) {
-    throw "confirmation TD receipt hash mismatch"
+if ($confirmationTdPresent) {
+    if (-not (Test-Path -LiteralPath $confirmationReceipt -PathType Leaf)) {
+        throw "confirmation TD receipt is missing"
+    }
+    if ([string]$info.confirmation_td_receipt_sha256 -ne (Get-BoundSha256 $confirmationReceipt)) {
+        throw "confirmation TD receipt hash mismatch"
+    }
+} else {
+    if (Test-Path -LiteralPath $confirmationReceipt -PathType Leaf) {
+        throw "urgent single-TD package unexpectedly contains a confirmation receipt"
+    }
+    if ($null -ne $info.confirmation_td_receipt_sha256) {
+        throw "urgent single-TD confirmation receipt hash must be null"
+    }
 }
 }
 if ([string]$info.validation_summary_sha256 -ne (Get-BoundSha256 $validationSummary)) {
 if ([string]$info.validation_summary_sha256 -ne (Get-BoundSha256 $validationSummary)) {
     throw "validation summary hash mismatch"
     throw "validation summary hash mismatch"
@@ -86,22 +140,29 @@ if ([string]$info.package_selftest_result_sha256 -ne (Get-BoundSha256 $selftestR
 }
 }
 
 
 $primary = Get-Content -LiteralPath $primaryReceipt -Raw -Encoding UTF8 | ConvertFrom-Json
 $primary = Get-Content -LiteralPath $primaryReceipt -Raw -Encoding UTF8 | ConvertFrom-Json
-$confirmation = Get-Content -LiteralPath $confirmationReceipt -Raw -Encoding UTF8 | ConvertFrom-Json
 if ([string]$primary.commit -ne $commit) { throw "primary TD receipt commit mismatch" }
 if ([string]$primary.commit -ne $commit) { throw "primary TD receipt commit mismatch" }
 if ([string]$primary.bitstream_sha256 -ne $bitstreamSha256) {
 if ([string]$primary.bitstream_sha256 -ne $bitstreamSha256) {
     throw "primary TD receipt bitstream mismatch"
     throw "primary TD receipt bitstream mismatch"
 }
 }
-if ([string]$confirmation.commit -ne $commit) {
-    throw "confirmation TD receipt commit mismatch"
-}
 if ([string]$info.synthesis_input_hash -ne [string]$primary.synthesis_input_hash) {
 if ([string]$info.synthesis_input_hash -ne [string]$primary.synthesis_input_hash) {
     throw "primary synthesis input hash mismatch"
     throw "primary synthesis input hash mismatch"
 }
 }
-if ([string]$info.confirmation_synthesis_input_hash -ne [string]$confirmation.synthesis_input_hash) {
-    throw "confirmation synthesis input hash mismatch"
-}
-if ([string]$info.confirmation_bitstream_sha256 -ne [string]$confirmation.bitstream_sha256) {
-    throw "confirmation bitstream hash binding mismatch"
+if ($confirmationTdPresent) {
+    $confirmation = Get-Content -LiteralPath $confirmationReceipt -Raw -Encoding UTF8 | ConvertFrom-Json
+    if ([string]$confirmation.commit -ne $commit) {
+        throw "confirmation TD receipt commit mismatch"
+    }
+    if ([string]$info.confirmation_synthesis_input_hash -ne [string]$confirmation.synthesis_input_hash) {
+        throw "confirmation synthesis input hash mismatch"
+    }
+    if ([string]$info.confirmation_bitstream_sha256 -ne [string]$confirmation.bitstream_sha256) {
+        throw "confirmation bitstream hash binding mismatch"
+    }
+} else {
+    if ($null -ne $info.confirmation_synthesis_input_hash -or
+        $null -ne $info.confirmation_bitstream_sha256) {
+        throw "urgent single-TD confirmation bindings must be null"
+    }
 }
 }
 $validation = Get-Content -LiteralPath $validationSummary -Raw -Encoding UTF8 | ConvertFrom-Json
 $validation = Get-Content -LiteralPath $validationSummary -Raw -Encoding UTF8 | ConvertFrom-Json
 if ([string]$validation.schema -ne "prod2u-p4-normal-v3-validation-summary-v1") {
 if ([string]$validation.schema -ne "prod2u-p4-normal-v3-validation-summary-v1") {
@@ -110,11 +171,46 @@ if ([string]$validation.schema -ne "prod2u-p4-normal-v3-validation-summary-v1")
 if ([string]$validation.commit -ne $commit -or [string]$validation.bitstream_sha256 -ne $bitstreamSha256) {
 if ([string]$validation.commit -ne $commit -or [string]$validation.bitstream_sha256 -ne $bitstreamSha256) {
     throw "validation summary binding mismatch"
     throw "validation summary binding mismatch"
 }
 }
+if ([string]$validation.delivery_mode -ne $deliveryMode -or
+    -not ($validation.verification_complete -is [bool]) -or
+    -not ($validation.confirmation_td_present -is [bool]) -or
+    $validation.verification_complete -ne $verificationComplete -or
+    $validation.confirmation_td_present -ne $confirmationTdPresent) {
+    throw "validation summary delivery fields mismatch"
+}
+$observedLayerNames = @($validation.layers.PSObject.Properties.Name | Sort-Object)
+$expectedSortedLayerNames = @($expectedLayerNames | Sort-Object)
+if (@(Compare-Object $expectedSortedLayerNames $observedLayerNames).Count -ne 0) {
+    throw "validation layer set mismatch"
+}
 foreach ($property in @($validation.layers.PSObject.Properties)) {
 foreach ($property in @($validation.layers.PSObject.Properties)) {
-    if ([string]$property.Value.status -notin @("pass", "fail", "not_run")) {
+    if ([string]$property.Value.status -notin @("pass", "fail", "running", "not_run")) {
         throw "validation layer status is invalid: $($property.Name)"
         throw "validation layer status is invalid: $($property.Name)"
     }
     }
 }
 }
+if ($deliveryMode -eq "urgent_single_td") {
+    if ([string]$validation.layers.td_confirmation.status -notin @("not_run", "running")) {
+        throw "urgent td_confirmation must be not_run or running"
+    }
+    foreach ($name in @(
+        "td_confirmation_artifacts", "td_confirmation_bitstream",
+        "td_confirmation_synthesis", "td_confirmation_manifest",
+        "resource_confirmation"
+    )) {
+        if ([string]$validation.layers.$name.status -ne "not_run") {
+            throw "urgent confirmation layer must be not_run: $name"
+        }
+    }
+}
+$expectedVerificationComplete = $deliveryMode -eq "normal_dual_td"
+foreach ($name in $verificationEvidenceLayers) {
+    if ([string]$validation.layers.$name.status -ne "pass") {
+        $expectedVerificationComplete = $false
+    }
+}
+if ($verificationComplete -ne $expectedVerificationComplete) {
+    throw "verification_complete does not match validation evidence"
+}
 
 
 $expectedFiles = @{}
 $expectedFiles = @{}
 foreach ($property in @($info.file_sha256.PSObject.Properties)) {
 foreach ($property in @($info.file_sha256.PSObject.Properties)) {
@@ -140,5 +236,8 @@ foreach ($relative in $observedFiles.Keys) {
     status = "pass"
     status = "pass"
     commit = $commit
     commit = $commit
     bitstream_sha256 = $bitstreamSha256
     bitstream_sha256 = $bitstreamSha256
-    validation_status = if (@($validation.layers.PSObject.Properties | Where-Object { $_.Value.status -eq "fail" }).Count -eq 0) { "pass" } else { "fail" }
+    delivery_mode = $deliveryMode
+    verification_complete = $verificationComplete
+    confirmation_td_present = $confirmationTdPresent
+    validation_status = Get-ValidationSummaryStatus $validation.layers
 } | ConvertTo-Json -Compress
 } | ConvertTo-Json -Compress

+ 20 - 28
tools/prod2u_p4_cli.py

@@ -19,7 +19,6 @@ from prod2u_p4_protocol import (
     MAGIC,
     MAGIC,
     CommandId,
     CommandId,
     FrameType,
     FrameType,
-    FORCE_JOG_STEP_CAP,
     HostAck,
     HostAck,
     MotionOpcode,
     MotionOpcode,
     MotionStatus,
     MotionStatus,
@@ -386,19 +385,25 @@ def build_parser() -> argparse.ArgumentParser:
     snapshot = sub.add_parser(
     snapshot = sub.add_parser(
         "set-all-outputs",
         "set-all-outputs",
         description=(
         description=(
-            "Sets PTC, fan, solenoid, and X/Y/Z target fields. X/Y targets may start "
-            "independent 3200-step moves; 0 requests closed, 100 requests open, and Z "
-            "remains a protocol-only no-op."
+            "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("--ptc", type=_bounded_int(0, 100), default=0)
     snapshot.add_argument("--fan", type=_bounded_int(0, 100), default=30)
     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("--solenoid", type=_bounded_int(0, 100), choices=(0, 100), default=0)
-    snapshot.add_argument("--x", type=_bounded_int(0, 100), choices=(0, 100), default=0)
-    snapshot.add_argument("--y", type=_bounded_int(0, 100), choices=(0, 100), default=0)
-    snapshot.add_argument("--z", 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")
+    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("--axis", type=_bounded_int(0, 1), required=True)
     jog.add_argument("--raw-dir", 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("--speed-code", type=_bounded_int(0, 3), required=True)
@@ -427,7 +432,9 @@ def _selftest() -> dict[str, Any]:
         "baud": BAUD,
         "baud": BAUD,
         "port": PORT,
         "port": PORT,
         "jog_request_steps_max": 65535,
         "jog_request_steps_max": 65535,
-        "jog_actual_steps_cap": FORCE_JOG_STEP_CAP,
+        "jog_executed_steps": "requested_u16_without_cap",
+        "jog_effective_step_rate_hz": 1000,
+        "jog_ack_semantics": "FIRST_STEP_EMITTED",
         "hardware_opened": False,
         "hardware_opened": False,
         "program_sram_attempted": False,
         "program_sram_attempted": False,
     }
     }
@@ -668,27 +675,12 @@ def _live_request(args: argparse.Namespace, endpoint: Any) -> dict[str, Any]:
         result = session.command(
         result = session.command(
             request,
             request,
             expected_command=CommandId.SET_OUTPUT_SNAPSHOT,
             expected_command=CommandId.SET_OUTPUT_SNAPSHOT,
-            expected_state_hash16=None,
+            expected_state_hash16=requested_hash,
+            allowed_statuses=(StatusCode.OK,),
+            expected_detail=0,
             required_result_flags=0x01,
             required_result_flags=0x01,
-            allowed_result_flags=0x0F,
+            allowed_result_flags=0x01,
         )
         )
-        if result.ack.detail & 0x80:
-            session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK contains reserved detail bits")
-        if result.ack.status == StatusCode.OK and result.ack.detail != 0:
-            session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot OK ACK contains skip detail")
-        if result.ack.status == StatusCode.PARTIAL and result.ack.detail == 0:
-            session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot PARTIAL ACK is missing skip detail")
-        busy_mask = result.ack.detail & 0x07
-        invalid_mask = (result.ack.detail >> 3) & 0x07
-        solenoid_skipped = bool(result.ack.detail & 0x40)
-        if busy_mask & invalid_mask:
-            session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK busy and invalid masks overlap")
-        if not solenoid_skipped and result.ack.state_hash16 != requested_hash:
-            session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK state hash does not match applied outputs")
-        accepted_or_noop_mask = (~(busy_mask | invalid_mask)) & 0x07
-        expected_result_flags = 0x01 | (accepted_or_noop_mask << 1)
-        if result.ack.result_flags != expected_result_flags:
-            session._fail(CommandId.SET_OUTPUT_SNAPSHOT, "snapshot ACK result flags do not match skip detail")
         return {"status": "pass", "ack": result.ack.__dict__}
         return {"status": "pass", "ack": result.ack.__dict__}
     if args.command == "jog":
     if args.command == "jog":
         result = session.command(
         result = session.command(

+ 248 - 44
tools/prod2u_p4_harness.py

@@ -62,22 +62,23 @@ EXPECTED_CDC_SYNC_REGISTERS = frozenset(
     {
     {
         "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_core/u_motors/u_x_axis/limit_sync_pipe[0]",
-        "u_core/u_motors/u_x_axis/limit_sync_pipe[1]",
-        "u_core/u_motors/u_x_axis/limit_sync_pipe[2]",
-        "u_core/u_motors/u_y_axis/limit_sync_pipe[0]",
-        "u_core/u_motors/u_y_axis/limit_sync_pipe[1]",
-        "u_core/u_motors/u_y_axis/limit_sync_pipe[2]",
     }
     }
 )
 )
 EXPECTED_CDC_FALSE_PATH_ENDPOINTS = frozenset(
 EXPECTED_CDC_FALSE_PATH_ENDPOINTS = frozenset(
     {
     {
         "u_uart_rx/rx_sync_pipe[0]",
         "u_uart_rx/rx_sync_pipe[0]",
-        "u_core/u_motors/u_x_axis/limit_sync_pipe[0]",
-        "u_core/u_motors/u_y_axis/limit_sync_pipe[0]",
     }
     }
 )
 )
-EXPECTED_FSM_AXES = {"x": 3, "y": 3}
+EXPECTED_FSM_AXES = {"x": 2, "y": 2}
+REQUIRED_MOTOR_LIMIT_PINS = {
+    "motor_en_n": {"location": "A10", "direction": "OUTPUT", "pull_type": "NONE"},
+    "x_step": {"location": "C11", "direction": "OUTPUT", "pull_type": "NONE"},
+    "x_dir": {"location": "B12", "direction": "OUTPUT", "pull_type": "NONE"},
+    "y_step": {"location": "D15", "direction": "OUTPUT", "pull_type": "NONE"},
+    "y_dir": {"location": "H14", "direction": "OUTPUT", "pull_type": "NONE"},
+    "x_limit_raw": {"location": "B9", "direction": "INPUT", "pull_type": "PULLUP"},
+    "y_limit_raw": {"location": "A11", "direction": "INPUT", "pull_type": "PULLUP"},
+}
 BUILD_ROOT_RELATIVE = Path("td") / PROFILE
 BUILD_ROOT_RELATIVE = Path("td") / PROFILE
 TD_SCRIPTS = {
 TD_SCRIPTS = {
     "syn": ROOT / "td" / "syn" / f"{PROFILE}.tcl",
     "syn": ROOT / "td" / "syn" / f"{PROFILE}.tcl",
@@ -143,7 +144,7 @@ def td_receipt_bitstream_binding_status(receipt: Mapping[str, Any]) -> str:
         if candidate.get("sha256") != digest:
         if candidate.get("sha256") != digest:
             continue
             continue
         path = Path(str(candidate.get("path", "")))
         path = Path(str(candidate.get("path", "")))
-        if not path.is_file() or sha256_file(path) == digest:
+        if path.is_file() and sha256_file(path) == digest:
             return "pass"
             return "pass"
     return "fail"
     return "fail"
 
 
@@ -153,6 +154,19 @@ def canonical_sha256(value: object) -> str:
     return hashlib.sha256(encoded).hexdigest()
     return hashlib.sha256(encoded).hexdigest()
 
 
 
 
+def validation_layer_summary(layers: object) -> str:
+    if not isinstance(layers, Mapping):
+        return "fail"
+    statuses = {
+        layer.get("status") if isinstance(layer, Mapping) else None
+        for layer in layers.values()
+    }
+    for status in ("fail", "running", "not_run"):
+        if status in statuses:
+            return status
+    return "pass" if statuses and statuses == {"pass"} else "fail"
+
+
 def load_receipt(path: Path) -> dict[str, Any]:
 def load_receipt(path: Path) -> dict[str, Any]:
     payload = json.loads(Path(path).read_text(encoding="utf-8-sig"))
     payload = json.loads(Path(path).read_text(encoding="utf-8-sig"))
     if not isinstance(payload, dict):
     if not isinstance(payload, dict):
@@ -2251,8 +2265,8 @@ def post_route_pin_gate(rows: Sequence[Mapping[str, str]] | None) -> dict[str, A
     if "A5" in locations:
     if "A5" in locations:
         failures.append("forbidden_location_assigned:A5")
         failures.append("forbidden_location_assigned:A5")
     required = {
     required = {
-        "x_limit_raw": {"location": "B9", "io_standard": "LVCMOS33", "pull_type": "PULLUP"},
-        "y_limit_raw": {"location": "A11", "io_standard": "LVCMOS33", "pull_type": "PULLUP"},
+        name: {**expected, "io_standard": "LVCMOS33"}
+        for name, expected in REQUIRED_MOTOR_LIMIT_PINS.items()
     }
     }
     for name, expected in required.items():
     for name, expected in required.items():
         observed = by_name.get(name)
         observed = by_name.get(name)
@@ -2356,8 +2370,10 @@ def pin_binding_gate() -> dict[str, Any]:
         "sys_clk": ("J1", "NONE"),
         "sys_clk": ("J1", "NONE"),
         "host_uart_rx": ("N11", "NONE"),
         "host_uart_rx": ("N11", "NONE"),
         "host_uart_tx": ("M10", "NONE"),
         "host_uart_tx": ("M10", "NONE"),
-        "x_limit_raw": ("B9", "PULLUP"),
-        "y_limit_raw": ("A11", "PULLUP"),
+        **{
+            signal: (expected["location"], expected["pull_type"])
+            for signal, expected in REQUIRED_MOTOR_LIMIT_PINS.items()
+        },
     }
     }
     for signal, (ball, pull) in required.items():
     for signal, (ball, pull) in required.items():
         observed = by_signal.get(signal)
         observed = by_signal.get(signal)
@@ -2870,15 +2886,16 @@ def _emit(payload: Mapping[str, Any], args: argparse.Namespace, label: str) -> i
     return 0 if payload.get("status") == "pass" else 1
     return 0 if payload.get("status") == "pass" else 1
 
 
 
 
-def package_required_files() -> tuple[str, ...]:
-    return (
+def package_required_files(*, confirmation_td_present: bool = True) -> tuple[str, ...]:
+    required = (
         "fw.bit",
         "fw.bit",
         "package-info.json",
         "package-info.json",
         "evidence/td-primary-receipt.json",
         "evidence/td-primary-receipt.json",
-        "evidence/td-confirmation-receipt.json",
         "evidence/validation-summary.json",
         "evidence/validation-summary.json",
         "evidence/package-selftest-result.json",
         "evidence/package-selftest-result.json",
         "config/host-contract.json",
         "config/host-contract.json",
+        "config/prod2u_p4_normal_v3_hw_binding.json",
+        "config/prod2u_p4_verification_targets_v1.json",
         "schemas/host-contract.schema.json",
         "schemas/host-contract.schema.json",
         "bootstrap.ps1",
         "bootstrap.ps1",
         "selftest.ps1",
         "selftest.ps1",
@@ -2888,6 +2905,9 @@ def package_required_files() -> tuple[str, ...]:
         "PROGRAM_SRAM.ps1",
         "PROGRAM_SRAM.ps1",
         "README.zh-CN.md",
         "README.zh-CN.md",
     )
     )
+    if confirmation_td_present:
+        return required + ("evidence/td-confirmation-receipt.json",)
+    return required
 
 
 
 
 def package_selftest_payload(
 def package_selftest_payload(
@@ -2912,7 +2932,6 @@ def package_selftest_payload(
     inputs = (
     inputs = (
         (info_path, "package_info"),
         (info_path, "package_info"),
         (primary_td_path, "primary_td"),
         (primary_td_path, "primary_td"),
-        (confirmation_td_path, "confirmation_td"),
         (validation_path, "validation"),
         (validation_path, "validation"),
         (packaged_selftest_path, "packaged_selftest"),
         (packaged_selftest_path, "packaged_selftest"),
     )
     )
@@ -2928,6 +2947,20 @@ def package_selftest_payload(
         else:
         else:
             loaded_inputs[label] = loaded
             loaded_inputs[label] = loaded
     info = loaded_inputs.get("package_info", {})
     info = loaded_inputs.get("package_info", {})
+    delivery_mode = info.get("delivery_mode") if info else None
+    if delivery_mode not in {"normal_dual_td", "urgent_single_td"}:
+        failures.append("package_delivery_mode_invalid")
+    confirmation_expected = delivery_mode != "urgent_single_td"
+    if confirmation_expected or confirmation_td_path.exists():
+        try:
+            loaded = json.loads(confirmation_td_path.read_text(encoding="utf-8-sig"))
+        except (OSError, UnicodeError, json.JSONDecodeError) as exc:
+            failures.append(f"confirmation_td_unreadable:{exc}")
+        else:
+            if not isinstance(loaded, Mapping):
+                failures.append("confirmation_td_not_object")
+            else:
+                loaded_inputs["confirmation_td"] = loaded
     primary_td = loaded_inputs.get("primary_td", {})
     primary_td = loaded_inputs.get("primary_td", {})
     confirmation_td = loaded_inputs.get("confirmation_td", {})
     confirmation_td = loaded_inputs.get("confirmation_td", {})
     validation = loaded_inputs.get("validation", {})
     validation = loaded_inputs.get("validation", {})
@@ -2943,6 +2976,19 @@ def package_selftest_payload(
             failures.append("package_info_schema_mismatch")
             failures.append("package_info_schema_mismatch")
         if info.get("profile") != RUNTIME_PROFILE:
         if info.get("profile") != RUNTIME_PROFILE:
             failures.append("package_profile_mismatch")
             failures.append("package_profile_mismatch")
+        verification_complete = info.get("verification_complete")
+        confirmation_td_present = info.get("confirmation_td_present")
+        if not isinstance(verification_complete, bool):
+            failures.append("package_verification_complete_invalid")
+        if not isinstance(confirmation_td_present, bool):
+            failures.append("package_confirmation_td_present_invalid")
+        elif confirmation_td_present != confirmation_td_path.is_file():
+            failures.append("package_confirmation_td_presence_mismatch")
+        if delivery_mode == "urgent_single_td":
+            if verification_complete is not False:
+                failures.append("urgent_verification_complete_must_be_false")
+            if confirmation_td_present is not False:
+                failures.append("urgent_confirmation_td_present_must_be_false")
         commit = str(info.get("commit", ""))
         commit = str(info.get("commit", ""))
         if not re.fullmatch(r"[0-9a-f]{40}", commit):
         if not re.fullmatch(r"[0-9a-f]{40}", commit):
             failures.append("package_commit_invalid")
             failures.append("package_commit_invalid")
@@ -2983,12 +3029,13 @@ def package_selftest_payload(
     if not isinstance(expected_files, Mapping) or dict(expected_files) != actual_files:
     if not isinstance(expected_files, Mapping) or dict(expected_files) != actual_files:
         failures.append("package_file_hash_map_mismatch")
         failures.append("package_file_hash_map_mismatch")
 
 
+    required_files = package_required_files(confirmation_td_present=confirmation_expected)
     checked_files = [
     checked_files = [
         relative
         relative
-        for relative in package_required_files()
+        for relative in required_files
         if (package / relative).is_file()
         if (package / relative).is_file()
     ]
     ]
-    for relative in package_required_files():
+    for relative in required_files:
         if not (package / relative).is_file():
         if not (package / relative).is_file():
             failures.append(f"package_file_missing:{relative}")
             failures.append(f"package_file_missing:{relative}")
 
 
@@ -3016,13 +3063,16 @@ def package_selftest_payload(
             failures.append("validation_summary_schema_mismatch")
             failures.append("validation_summary_schema_mismatch")
         if validation.get("commit") != commit or validation.get("bitstream_sha256") != digest:
         if validation.get("commit") != commit or validation.get("bitstream_sha256") != digest:
             failures.append("validation_summary_binding_mismatch")
             failures.append("validation_summary_binding_mismatch")
+        for name in ("delivery_mode", "verification_complete", "confirmation_td_present"):
+            if validation.get(name) != info.get(name):
+                failures.append(f"validation_summary_{name}_mismatch")
         layers = validation.get("layers")
         layers = validation.get("layers")
         if not isinstance(layers, Mapping):
         if not isinstance(layers, Mapping):
             failures.append("validation_layers_missing")
             failures.append("validation_layers_missing")
         else:
         else:
             for name, layer in layers.items():
             for name, layer in layers.items():
                 status = layer.get("status") if isinstance(layer, Mapping) else None
                 status = layer.get("status") if isinstance(layer, Mapping) else None
-                if status not in {"pass", "fail", "not_run"}:
+                if status not in {"pass", "fail", "running", "not_run"}:
                     failures.append(f"validation_layer_status_invalid:{name}")
                     failures.append(f"validation_layer_status_invalid:{name}")
             comparisons = {
             comparisons = {
                 "td_confirmation_synthesis": (
                 "td_confirmation_synthesis": (
@@ -3060,6 +3110,27 @@ def package_selftest_payload(
                 layer = layers.get(name)
                 layer = layers.get(name)
                 if not isinstance(layer, Mapping) or layer.get("status") != expected_status:
                 if not isinstance(layer, Mapping) or layer.get("status") != expected_status:
                     failures.append(f"validation_layer_semantic_mismatch:{name}")
                     failures.append(f"validation_layer_semantic_mismatch:{name}")
+            if delivery_mode == "urgent_single_td":
+                confirmation_layer = layers.get("td_confirmation")
+                confirmation_status = (
+                    confirmation_layer.get("status")
+                    if isinstance(confirmation_layer, Mapping)
+                    else None
+                )
+                if confirmation_status not in {"not_run", "running"}:
+                    failures.append(
+                        "urgent_confirmation_layer_invalid:td_confirmation"
+                    )
+                for name in (
+                    "td_confirmation_artifacts",
+                    "td_confirmation_bitstream",
+                    "td_confirmation_synthesis",
+                    "td_confirmation_manifest",
+                    "resource_confirmation",
+                ):
+                    layer = layers.get(name)
+                    if not isinstance(layer, Mapping) or layer.get("status") != "not_run":
+                        failures.append(f"urgent_confirmation_layer_not_not_run:{name}")
 
 
     script_result: dict[str, Any] = {"status": "not_run", "returncode": None}
     script_result: dict[str, Any] = {"status": "not_run", "returncode": None}
     selftest = package / "selftest.ps1"
     selftest = package / "selftest.ps1"
@@ -3098,6 +3169,9 @@ def package_selftest_payload(
         "commit": info.get("commit") if info else None,
         "commit": info.get("commit") if info else None,
         "bitstream_sha256": digest,
         "bitstream_sha256": digest,
         "package_dir": str(package),
         "package_dir": str(package),
+        "delivery_mode": info.get("delivery_mode") if info else None,
+        "verification_complete": info.get("verification_complete") if info else None,
+        "confirmation_td_present": info.get("confirmation_td_present") if info else None,
         "package_info_sha256": sha256_file(info_path) if info_path.is_file() else None,
         "package_info_sha256": sha256_file(info_path) if info_path.is_file() else None,
         "td_receipt_sha256": sha256_file(primary_td_path) if primary_td_path.is_file() else None,
         "td_receipt_sha256": sha256_file(primary_td_path) if primary_td_path.is_file() else None,
         "confirmation_td_receipt_sha256": (
         "confirmation_td_receipt_sha256": (
@@ -3116,15 +3190,7 @@ def package_selftest_payload(
         "confirmation_bitstream_sha256": (
         "confirmation_bitstream_sha256": (
             confirmation_td.get("bitstream_sha256") if confirmation_td else None
             confirmation_td.get("bitstream_sha256") if confirmation_td else None
         ),
         ),
-        "validation_status": (
-            "fail"
-            if isinstance(validation.get("layers"), Mapping)
-            and any(
-                isinstance(layer, Mapping) and layer.get("status") == "fail"
-                for layer in validation["layers"].values()
-            )
-            else "pass"
-        ),
+        "validation_status": validation_layer_summary(validation.get("layers")),
         "packaged_selftest_status": packaged_selftest.get("status") if packaged_selftest else None,
         "packaged_selftest_status": packaged_selftest.get("status") if packaged_selftest else None,
         "package_file_sha256": actual_files,
         "package_file_sha256": actual_files,
         "package_file_manifest_sha256": canonical_sha256(actual_files) if actual_files else None,
         "package_file_manifest_sha256": canonical_sha256(actual_files) if actual_files else None,
@@ -3248,14 +3314,20 @@ def _td_final_failures(
         if routed_pins.get("row_count") != 41:
         if routed_pins.get("row_count") != 41:
             failures.append(prefix + "post_route_pin_count")
             failures.append(prefix + "post_route_pin_count")
         observed = routed_pins.get("observed")
         observed = routed_pins.get("observed")
-        expected_limits = {
-            "x_limit_raw": ("B9", "LVCMOS33", "PULLUP"),
-            "y_limit_raw": ("A11", "LVCMOS33", "PULLUP"),
+        expected_pins = {
+            signal: (
+                expected["location"],
+                expected["direction"],
+                "LVCMOS33",
+                expected["pull_type"],
+            )
+            for signal, expected in REQUIRED_MOTOR_LIMIT_PINS.items()
         }
         }
-        for signal, expected in expected_limits.items():
+        for signal, expected in expected_pins.items():
             row = observed.get(signal) if isinstance(observed, Mapping) else None
             row = observed.get(signal) if isinstance(observed, Mapping) else None
             values = (
             values = (
                 row.get("location"),
                 row.get("location"),
+                row.get("direction"),
                 row.get("io_standard"),
                 row.get("io_standard"),
                 row.get("pull_type"),
                 row.get("pull_type"),
             ) if isinstance(row, Mapping) else None
             ) if isinstance(row, Mapping) else None
@@ -3315,6 +3387,8 @@ def _package_final_failures(
     *,
     *,
     expected_commit: str,
     expected_commit: str,
     expected_bitstream_sha256: str,
     expected_bitstream_sha256: str,
+    expected_primary_td_receipt_sha256: str,
+    expected_confirmation_td_receipt_sha256: str,
 ) -> list[str]:
 ) -> list[str]:
     failures: list[str] = []
     failures: list[str] = []
     if receipt.get("schema") != PACKAGE_RECEIPT_SCHEMA:
     if receipt.get("schema") != PACKAGE_RECEIPT_SCHEMA:
@@ -3323,26 +3397,152 @@ def _package_final_failures(
         failures.append("package:status_or_commit")
         failures.append("package:status_or_commit")
     if receipt.get("bitstream_sha256") != expected_bitstream_sha256:
     if receipt.get("bitstream_sha256") != expected_bitstream_sha256:
         failures.append("package:bitstream_sha256")
         failures.append("package:bitstream_sha256")
+    if receipt.get("delivery_mode") != "normal_dual_td":
+        failures.append("package:delivery_mode")
     if receipt.get("failures") != []:
     if receipt.get("failures") != []:
         failures.append("package:failures")
         failures.append("package:failures")
+    if receipt.get("verification_complete") is not True:
+        failures.append("package:verification_incomplete")
+    if receipt.get("confirmation_td_present") is not True:
+        failures.append("package:confirmation_td_missing")
+    if receipt.get("validation_status") != "pass":
+        failures.append("package:validation_incomplete")
+    if receipt.get("packaged_selftest_status") != "pass":
+        failures.append("package:packaged_selftest")
     selftest = receipt.get("selftest")
     selftest = receipt.get("selftest")
     if not isinstance(selftest, Mapping) or selftest.get("status") != "pass" or selftest.get("returncode") != 0:
     if not isinstance(selftest, Mapping) or selftest.get("status") != "pass" or selftest.get("returncode") != 0:
         failures.append("package:selftest")
         failures.append("package:selftest")
     package_dir = Path(str(receipt.get("package_dir", "")))
     package_dir = Path(str(receipt.get("package_dir", "")))
     info_path = package_dir / "package-info.json"
     info_path = package_dir / "package-info.json"
     bitstream = package_dir / "fw.bit"
     bitstream = package_dir / "fw.bit"
-    if not info_path.is_file() or not bitstream.is_file():
-        failures.append("package:artifacts")
-    else:
+    primary_path = package_dir / "evidence" / "td-primary-receipt.json"
+    confirmation_path = package_dir / "evidence" / "td-confirmation-receipt.json"
+    validation_path = package_dir / "evidence" / "validation-summary.json"
+    packaged_selftest_path = package_dir / "evidence" / "package-selftest-result.json"
+    for relative in package_required_files(confirmation_td_present=True):
+        if not (package_dir / relative).is_file():
+            failures.append(f"package:required_file:{relative}")
+
+    loaded: dict[str, Mapping[str, Any]] = {}
+    for label, path in (
+        ("info", info_path),
+        ("primary_td", primary_path),
+        ("confirmation_td", confirmation_path),
+        ("validation", validation_path),
+        ("packaged_selftest", packaged_selftest_path),
+    ):
+        if not path.is_file():
+            continue
         try:
         try:
-            info = load_receipt(info_path)
+            loaded[label] = load_receipt(path)
         except (OSError, UnicodeError, json.JSONDecodeError, ValueError):
         except (OSError, UnicodeError, json.JSONDecodeError, ValueError):
-            failures.append("package:info_unreadable")
-        else:
-            if info.get("commit") != expected_commit or info.get("bitstream_sha256") != expected_bitstream_sha256:
-                failures.append("package:info_binding")
-            if sha256_file(bitstream) != expected_bitstream_sha256:
-                failures.append("package:file_hash")
+            failures.append(f"package:{label}_unreadable")
+
+    info = loaded.get("info", {})
+    primary_td = loaded.get("primary_td", {})
+    confirmation_td = loaded.get("confirmation_td", {})
+    validation = loaded.get("validation", {})
+    packaged_selftest = loaded.get("packaged_selftest", {})
+    if info:
+        if (
+            info.get("schema") != "prod2u-p4-normal-v3-folder-package-info-v3"
+            or info.get("profile") != RUNTIME_PROFILE
+            or info.get("commit") != expected_commit
+            or info.get("bitstream_sha256") != expected_bitstream_sha256
+        ):
+            failures.append("package:info_binding")
+        if info.get("delivery_mode") != "normal_dual_td":
+            failures.append("package:info_delivery_mode")
+        if info.get("verification_complete") is not True:
+            failures.append("package:info_verification_incomplete")
+        if info.get("confirmation_td_present") is not True:
+            failures.append("package:info_confirmation_td_missing")
+
+    if bitstream.is_file():
+        if sha256_file(bitstream) != expected_bitstream_sha256:
+            failures.append("package:file_hash")
+
+    actual_hashes = {
+        "package_info_sha256": sha256_file(info_path) if info_path.is_file() else None,
+        "td_receipt_sha256": sha256_file(primary_path) if primary_path.is_file() else None,
+        "confirmation_td_receipt_sha256": (
+            sha256_file(confirmation_path) if confirmation_path.is_file() else None
+        ),
+        "validation_summary_sha256": (
+            sha256_file(validation_path) if validation_path.is_file() else None
+        ),
+        "package_selftest_result_sha256": (
+            sha256_file(packaged_selftest_path)
+            if packaged_selftest_path.is_file()
+            else None
+        ),
+    }
+    for field, actual in actual_hashes.items():
+        if receipt.get(field) != actual:
+            failures.append(f"package:receipt_hash:{field}")
+    for field in (
+        "td_receipt_sha256",
+        "confirmation_td_receipt_sha256",
+        "validation_summary_sha256",
+        "package_selftest_result_sha256",
+    ):
+        if info and info.get(field) != actual_hashes[field]:
+            failures.append(f"package:info_hash:{field}")
+    if actual_hashes["td_receipt_sha256"] != expected_primary_td_receipt_sha256:
+        failures.append("package:primary_td_external_binding")
+    if (
+        actual_hashes["confirmation_td_receipt_sha256"]
+        != expected_confirmation_td_receipt_sha256
+    ):
+        failures.append("package:confirmation_td_external_binding")
+
+    actual_files = {
+        path.relative_to(package_dir).as_posix(): sha256_file(path)
+        for path in sorted(package_dir.rglob("*"))
+        if path.is_file() and path not in {info_path, packaged_selftest_path}
+    }
+    if not info or info.get("file_sha256") != actual_files:
+        failures.append("package:file_manifest:info")
+    if receipt.get("package_file_sha256") != actual_files:
+        failures.append("package:file_manifest:receipt")
+    if receipt.get("package_file_manifest_sha256") != canonical_sha256(actual_files):
+        failures.append("package:file_manifest:digest")
+
+    if primary_td:
+        if (
+            primary_td.get("commit") != expected_commit
+            or primary_td.get("bitstream_sha256") != expected_bitstream_sha256
+            or info.get("synthesis_input_hash") != primary_td.get("synthesis_input_hash")
+        ):
+            failures.append("package:primary_td_binding")
+    if confirmation_td:
+        if (
+            confirmation_td.get("commit") != expected_commit
+            or info.get("confirmation_bitstream_sha256")
+            != confirmation_td.get("bitstream_sha256")
+            or info.get("confirmation_synthesis_input_hash")
+            != confirmation_td.get("synthesis_input_hash")
+        ):
+            failures.append("package:confirmation_td_binding")
+    if validation:
+        if (
+            validation.get("schema")
+            != "prod2u-p4-normal-v3-validation-summary-v1"
+            or validation.get("commit") != expected_commit
+            or validation.get("bitstream_sha256") != expected_bitstream_sha256
+            or validation.get("delivery_mode") != "normal_dual_td"
+            or validation.get("verification_complete") is not True
+            or validation.get("confirmation_td_present") is not True
+        ):
+            failures.append("package:validation_binding")
+        if validation_layer_summary(validation.get("layers")) != "pass":
+            failures.append("package:validation_layers")
+    if (
+        not packaged_selftest
+        or packaged_selftest.get("status") != "pass"
+        or packaged_selftest.get("returncode") != 0
+    ):
+        failures.append("package:packaged_selftest_content")
     return failures
     return failures
 
 
 
 
@@ -3405,6 +3605,10 @@ def cmd_final_gate(args: argparse.Namespace) -> int:
             package,
             package,
             expected_commit=str(expected_commit),
             expected_commit=str(expected_commit),
             expected_bitstream_sha256=str(primary.get("bitstream_sha256", "")),
             expected_bitstream_sha256=str(primary.get("bitstream_sha256", "")),
+            expected_primary_td_receipt_sha256=sha256_file(paths["td"]),
+            expected_confirmation_td_receipt_sha256=sha256_file(
+                paths["td_confirmation"]
+            ),
         )
         )
     )
     )
     if primary.get("synthesis_input_hash") != confirmation.get("synthesis_input_hash"):
     if primary.get("synthesis_input_hash") != confirmation.get("synthesis_input_hash"):

+ 116 - 215
tools/prod2u_p4_normal_v3_model.py

@@ -41,19 +41,15 @@ STATUS_UNSUPPORTED = 0x01
 STATUS_BAD_FLAGS = 0x02
 STATUS_BAD_FLAGS = 0x02
 STATUS_BAD_LENGTH = 0x03
 STATUS_BAD_LENGTH = 0x03
 STATUS_BAD_VALUE = 0x05
 STATUS_BAD_VALUE = 0x05
-STATUS_BUSY = 0x09
 STATUS_PARTIAL = 0x16
 STATUS_PARTIAL = 0x16
 
 
 PTC_COUNT = 24
 PTC_COUNT = 24
 FAN_COUNT = 4
 FAN_COUNT = 4
 AXIS_COUNT = 3
 AXIS_COUNT = 3
 UNKNOWN_POSITION = 0xFF
 UNKNOWN_POSITION = 0xFF
-INTERMEDIATE_POSITION = 0xFE
-STANDARD_STEPS = 3200
-FORCE_JOG_STEP_CAP = 800
 WATCHDOG_TIMEOUT_MS = 5000
 WATCHDOG_TIMEOUT_MS = 5000
 DIR_SETUP_MS = 1
 DIR_SETUP_MS = 1
-SPEED_STEP_MS = (50, 25, 10, 1)
+SPEED_STEP_MS = (1, 1, 1, 1)
 SAFE_PTC = (0,) * PTC_COUNT
 SAFE_PTC = (0,) * PTC_COUNT
 SAFE_FAN = (30,) * FAN_COUNT
 SAFE_FAN = (30,) * FAN_COUNT
 SAFE_SOLENOID = 0
 SAFE_SOLENOID = 0
@@ -511,7 +507,7 @@ def encode_snapshot_frame(
     ptc = _percent_values(ptc_percent, count=PTC_COUNT, label="PTC")
     ptc = _percent_values(ptc_percent, count=PTC_COUNT, label="PTC")
     fan = _percent_values(fan_percent, count=FAN_COUNT, label="FAN")
     fan = _percent_values(fan_percent, count=FAN_COUNT, label="FAN")
     checked_solenoid = _binary_values((solenoid,), count=1, label="solenoid")[0]
     checked_solenoid = _binary_values((solenoid,), count=1, label="solenoid")[0]
-    checked_xyz = _binary_values(xyz, count=AXIS_COUNT, label="XYZ")
+    checked_xyz = _byte_values(xyz, count=AXIS_COUNT, label="XYZ")
     payload = bytes((CMD_SET_SNAPSHOT, 0, *ptc, *fan, checked_solenoid, *checked_xyz))
     payload = bytes((CMD_SET_SNAPSHOT, 0, *ptc, *fan, checked_solenoid, *checked_xyz))
     return encode_standard_frame(FRAME_HOST_BATCH, payload)
     return encode_standard_frame(FRAME_HOST_BATCH, payload)
 
 
@@ -592,7 +588,7 @@ class NormalV3Model:
 
 
     @property
     @property
     def busy_mask(self) -> int:
     def busy_mask(self) -> int:
-        return sum((1 << index) for index, axis in enumerate(self.axes[:2]) if axis.busy)
+        return 0
 
 
     @property
     @property
     def active_mask(self) -> int:
     def active_mask(self) -> int:
@@ -604,11 +600,11 @@ class NormalV3Model:
 
 
     @property
     @property
     def position_valid_mask(self) -> int:
     def position_valid_mask(self) -> int:
-        return sum((1 << index) for index, axis in enumerate(self.axes[:2]) if axis.position_valid)
+        return 0
 
 
     @property
     @property
     def fault_mask(self) -> int:
     def fault_mask(self) -> int:
-        return sum((1 << index) for index, axis in enumerate(self.axes[:2]) if axis.fault)
+        return 0
 
 
     def state_fingerprint(self) -> tuple[object, ...]:
     def state_fingerprint(self) -> tuple[object, ...]:
         frozen = _freeze_state(self.state_payload())
         frozen = _freeze_state(self.state_payload())
@@ -637,31 +633,17 @@ class NormalV3Model:
     def _set_xy_state(axis: AxisState, state: str) -> None:
     def _set_xy_state(axis: AxisState, state: str) -> None:
         axis.state = state
         axis.state = state
         axis.fault = False
         axis.fault = False
-        if state == AXIS_UNCALIBRATED:
-            axis.position_valid = False
-            axis.current = UNKNOWN_POSITION
-            axis.target = UNKNOWN_POSITION
-        elif state == AXIS_CLOSED:
-            axis.position_valid = True
-            axis.current = 0
-            axis.target = 0
-        elif state == AXIS_OPEN:
-            axis.position_valid = True
-            axis.current = 100
-            axis.target = 100
-        elif state == AXIS_OPENING:
-            axis.position_valid = False
-            axis.current = INTERMEDIATE_POSITION
-            axis.target = 100
-        elif state == AXIS_CLOSING:
-            axis.position_valid = False
-            axis.current = INTERMEDIATE_POSITION
-            axis.target = 0
-        elif state == AXIS_INTERMEDIATE:
-            axis.position_valid = False
-            axis.current = UNKNOWN_POSITION
-            axis.target = UNKNOWN_POSITION
-        else:
+        axis.position_valid = False
+        axis.current = UNKNOWN_POSITION
+        axis.target = UNKNOWN_POSITION
+        if state not in (
+            AXIS_UNCALIBRATED,
+            AXIS_CLOSED,
+            AXIS_OPENING,
+            AXIS_OPEN,
+            AXIS_CLOSING,
+            AXIS_INTERMEDIATE,
+        ):
             raise ValueError(f"unsupported XY axis state: {state}")
             raise ValueError(f"unsupported XY axis state: {state}")
 
 
     @staticmethod
     @staticmethod
@@ -715,16 +697,13 @@ class NormalV3Model:
         if elapsed_ms < 0:
         if elapsed_ms < 0:
             raise ValueError("elapsed_ms must be non-negative")
             raise ValueError("elapsed_ms must be non-negative")
         remaining_ms = elapsed_ms
         remaining_ms = elapsed_ms
-        while (
-            remaining_ms > 0
-            and self.watchdog_armed
-            and not self.disabled
-            and not self.watchdog_timeout
-        ):
-            delta_ms = min(
-                remaining_ms,
-                WATCHDOG_TIMEOUT_MS - self.watchdog_elapsed_ms,
-            )
+        while remaining_ms > 0:
+            delta_ms = remaining_ms
+            if self.watchdog_armed and not self.disabled and not self.watchdog_timeout:
+                delta_ms = min(
+                    delta_ms,
+                    WATCHDOG_TIMEOUT_MS - self.watchdog_elapsed_ms,
+                )
             accumulating_axes: list[int] = []
             accumulating_axes: list[int] = []
             for axis_index, axis in enumerate(self.axes[:2]):
             for axis_index, axis in enumerate(self.axes[:2]):
                 if not axis.drive_active or axis.remaining_steps <= 0:
                 if not axis.drive_active or axis.remaining_steps <= 0:
@@ -739,8 +718,6 @@ class NormalV3Model:
 
 
             self._advance_control_time(delta_ms)
             self._advance_control_time(delta_ms)
             remaining_ms -= delta_ms
             remaining_ms -= delta_ms
-            if self.watchdog_timeout:
-                break
 
 
             for axis_index in accumulating_axes:
             for axis_index in accumulating_axes:
                 axis = self.axes[axis_index]
                 axis = self.axes[axis_index]
@@ -763,25 +740,20 @@ class NormalV3Model:
                     self.finish_axis_step(axis_index)
                     self.finish_axis_step(axis_index)
 
 
     def _advance_control_time(self, elapsed_ms: int) -> None:
     def _advance_control_time(self, elapsed_ms: int) -> None:
-        if not self.watchdog_armed or self.disabled or self.watchdog_timeout:
-            return
-        if self.watchdog_elapsed_ms + elapsed_ms >= WATCHDOG_TIMEOUT_MS:
-            self.watchdog_expire()
-        else:
-            self.watchdog_elapsed_ms += elapsed_ms
-        if not self.watchdog_timeout:
-            for axis_index, axis in enumerate(self.axes[:2]):
-                if axis.dir_setup_remaining_ms <= 0:
-                    continue
-                axis.dir_setup_remaining_ms = max(
-                    0,
-                    axis.dir_setup_remaining_ms - elapsed_ms,
-                )
-                if (
-                    axis.dir_setup_remaining_ms == 0
-                    and axis.drive_active
-                ):
-                    self._complete_dir_setup(axis_index)
+        if self.watchdog_armed and not self.disabled and not self.watchdog_timeout:
+            if self.watchdog_elapsed_ms + elapsed_ms >= WATCHDOG_TIMEOUT_MS:
+                self.watchdog_expire()
+            else:
+                self.watchdog_elapsed_ms += elapsed_ms
+        for axis_index, axis in enumerate(self.axes[:2]):
+            if axis.dir_setup_remaining_ms <= 0:
+                continue
+            axis.dir_setup_remaining_ms = max(
+                0,
+                axis.dir_setup_remaining_ms - elapsed_ms,
+            )
+            if axis.dir_setup_remaining_ms == 0 and axis.drive_active:
+                self._complete_dir_setup(axis_index)
 
 
     def _complete_dir_setup(self, axis_index: int) -> None:
     def _complete_dir_setup(self, axis_index: int) -> None:
         axis = self.axes[axis_index]
         axis = self.axes[axis_index]
@@ -796,15 +768,6 @@ class NormalV3Model:
 
 
     def _force_safe(self, *, disabled: bool, watchdog_timeout: bool) -> None:
     def _force_safe(self, *, disabled: bool, watchdog_timeout: bool) -> None:
         self._safe_outputs()
         self._safe_outputs()
-        for index, axis in enumerate(self.axes):
-            if index < 2:
-                self._set_xy_state(axis, AXIS_UNCALIBRATED)
-            else:
-                axis.state = AXIS_UNCALIBRATED
-                axis.position_valid = False
-                axis.current = UNKNOWN_POSITION
-                axis.target = UNKNOWN_POSITION
-            self._clear_motion(axis)
         self.disabled = disabled
         self.disabled = disabled
         self.watchdog_timeout = watchdog_timeout
         self.watchdog_timeout = watchdog_timeout
         self.watchdog_armed = False
         self.watchdog_armed = False
@@ -882,64 +845,16 @@ class NormalV3Model:
                 reason=str(exc),
                 reason=str(exc),
             )
             )
 
 
-        if self.watchdog_timeout:
-            return self._result(
-                accepted=False,
-                command=command,
-                status=STATUS_BUSY,
-                reason="watchdog timeout requires DISABLE before re-arm",
-            )
-
-        busy_mask = 0
-        invalid_mask = 0
-        accepted_mask = 0
-        checked_xyz: list[int | None] = []
-        for index, target in enumerate(xyz):
-            axis = self.axes[index]
-            bit = 1 << index
-            if index < 2 and axis.drive_active:
-                busy_mask |= bit
-                checked_xyz.append(None)
-                continue
-            if target not in (0, 100):
-                invalid_mask |= bit
-                checked_xyz.append(None)
-            else:
-                checked_xyz.append(target)
-                accepted_mask |= bit
-
         self.ptc_percent = checked_ptc
         self.ptc_percent = checked_ptc
         self.fan_percent = checked_fan
         self.fan_percent = checked_fan
-        solenoid_skipped = bool(self.active_mask and checked_solenoid != self.solenoid)
-        if not solenoid_skipped:
-            self.solenoid = checked_solenoid
-        for index, target in enumerate(checked_xyz):
-            if target is None or not (accepted_mask & (1 << index)):
-                continue
-            if index >= 2:
-                continue
-            axis = self.axes[index]
-            self._set_xy_state(axis, AXIS_OPENING if target == 100 else AXIS_CLOSING)
-            axis.busy = False
-            axis.drive_active = True
-            axis.step_phase = "idle"
-            axis.pending_jog = None
-            axis.move_kind = "standard"
-            axis.raw_dir = 0 if target == 100 else 1
-            axis.speed_code = 3
-            axis.remaining_steps = STANDARD_STEPS
-            axis.steps_executed = 0
-            axis.step_elapsed_ms = 0
-            axis.dir_setup_remaining_ms = DIR_SETUP_MS
+        self.solenoid = checked_solenoid
         self._arm_watchdog()
         self._arm_watchdog()
-
-        partial = bool(busy_mask or invalid_mask or solenoid_skipped)
         return self._result(
         return self._result(
             accepted=True,
             accepted=True,
             command=command,
             command=command,
-            status=STATUS_PARTIAL if partial else STATUS_OK,
-            detail=busy_mask | (invalid_mask << 3) | (int(solenoid_skipped) << 6),
-            result_flags=1 | (accepted_mask << 1),
+            status=STATUS_OK,
+            detail=0,
+            result_flags=0x01,
         )
         )
 
 
     def _apply_host(self, payload: bytes) -> ModelResult:
     def _apply_host(self, payload: bytes) -> ModelResult:
@@ -1006,17 +921,14 @@ class NormalV3Model:
             return self._result(accepted=False, command=MOTION_JOG, status=STATUS_BAD_VALUE)
             return self._result(accepted=False, command=MOTION_JOG, status=STATUS_BAD_VALUE)
         axis = self.axes[axis_index]
         axis = self.axes[axis_index]
         self._set_xy_state(axis, AXIS_INTERMEDIATE)
         self._set_xy_state(axis, AXIS_INTERMEDIATE)
-        clamped_steps = min(steps, FORCE_JOG_STEP_CAP)
-        if axis.drive_active and axis.step_phase in ("high", "low"):
-            axis.pending_jog = (raw_dir, speed_code, clamped_steps)
-        else:
-            self._load_force_jog(
-                axis,
-                raw_dir=raw_dir,
-                speed_code=speed_code,
-                steps=clamped_steps,
-            )
-        self._arm_watchdog()
+        self._load_force_jog(
+            axis,
+            raw_dir=raw_dir,
+            speed_code=speed_code,
+            steps=steps,
+        )
+        axis.dir_setup_remaining_ms = 0
+        self.begin_axis_step(axis_index)
         return self._result(accepted=True, command=MOTION_JOG, status=STATUS_OK)
         return self._result(accepted=True, command=MOTION_JOG, status=STATUS_OK)
 
 
     def _load_force_jog(
     def _load_force_jog(
@@ -1041,32 +953,10 @@ class NormalV3Model:
 
 
     def _complete_motion_segment(self, axis_index: int) -> None:
     def _complete_motion_segment(self, axis_index: int) -> None:
         axis = self.axes[axis_index]
         axis = self.axes[axis_index]
-        move_kind = axis.move_kind
-        if axis_index >= 2:
-            if move_kind == "jog":
-                axis.state = AXIS_UNCALIBRATED
-                axis.position_valid = False
-                axis.current = UNKNOWN_POSITION
-                axis.target = UNKNOWN_POSITION
-            elif move_kind == "standard":
-                target = axis.target
-                axis.state = AXIS_OPEN if target == 100 else AXIS_CLOSED
-                axis.position_valid = True
-                axis.current = target
-                axis.target = target
-                axis.fault = False
-            self._clear_motion(axis)
-            return
-
-        if move_kind == "jog":
-            self._set_xy_state(axis, AXIS_INTERMEDIATE)
-            self._clear_motion(axis)
-        elif move_kind == "standard":
-            completed_target = axis.target
-            self._set_xy_state(axis, AXIS_OPEN if completed_target == 100 else AXIS_CLOSED)
-            self._clear_motion(axis)
-        else:
-            raise AssertionError("busy axis has no modeled move kind")
+        if axis_index not in (0, 1) or axis.move_kind != "jog":
+            raise AssertionError("only X/Y JOG can complete motor motion")
+        self._set_xy_state(axis, AXIS_INTERMEDIATE)
+        self._clear_motion(axis)
 
 
     def _prepare_axis_event(self, axis_index: int) -> tuple[int, str] | None:
     def _prepare_axis_event(self, axis_index: int) -> tuple[int, str] | None:
         axis = self.axes[axis_index]
         axis = self.axes[axis_index]
@@ -1097,7 +987,7 @@ class NormalV3Model:
         ):
         ):
             raise ValueError("axis has no complete step ready to commit")
             raise ValueError("axis has no complete step ready to commit")
         axis.step_phase = "high"
         axis.step_phase = "high"
-        axis.busy = True
+        axis.busy = False
 
 
     def lower_axis_step(self, axis_index: int) -> None:
     def lower_axis_step(self, axis_index: int) -> None:
         if axis_index not in (0, 1):
         if axis_index not in (0, 1):
@@ -1166,8 +1056,6 @@ class NormalV3Model:
                 break
                 break
             elapsed_ms = min(active_due)
             elapsed_ms = min(active_due)
             self._advance_control_time(elapsed_ms)
             self._advance_control_time(elapsed_ms)
-            if self.watchdog_timeout:
-                break
 
 
             for axis_index in range(AXIS_COUNT):
             for axis_index in range(AXIS_COUNT):
                 if due_ms[axis_index] is not None:
                 if due_ms[axis_index] is not None:
@@ -1223,24 +1111,20 @@ class NormalV3Model:
         self.execute_axis_steps(axis_index, axis.remaining_steps)
         self.execute_axis_steps(axis_index, axis.remaining_steps)
 
 
     def motor_status_payload(self) -> bytes:
     def motor_status_payload(self) -> bytes:
-        flags = int(bool(self.busy_mask))
-        en_active = (
-            any(axis.drive_active for axis in self.axes)
-            and not self.disabled
-            and not self.watchdog_timeout
-        )
-        flags |= int(en_active) << 1
+        flags = 0x02
         flags |= int(self.disabled) << 2
         flags |= int(self.disabled) << 2
         flags |= int(self.watchdog_timeout) << 3
         flags |= int(self.watchdog_timeout) << 3
-        current = [self.axes[0].current, self.axes[1].current, UNKNOWN_POSITION]
-        target = [self.axes[0].target, self.axes[1].target, UNKNOWN_POSITION]
         return bytes((
         return bytes((
             flags,
             flags,
-            self.position_valid_mask,
-            self.busy_mask,
-            *current,
-            *target,
-            self.fault_mask,
+            0,
+            0,
+            UNKNOWN_POSITION,
+            UNKNOWN_POSITION,
+            UNKNOWN_POSITION,
+            UNKNOWN_POSITION,
+            UNKNOWN_POSITION,
+            UNKNOWN_POSITION,
+            0,
         ))
         ))
 
 
     def feed_stream(
     def feed_stream(
@@ -1308,12 +1192,11 @@ def run_replay() -> dict[str, object]:
     subject = NormalV3Model()
     subject = NormalV3Model()
     enable = subject.apply_frame(GOLDEN_VECTORS["enable"])
     enable = subject.apply_frame(GOLDEN_VECTORS["enable"])
     checks.append({
     checks.append({
-        "name": "enable_snapshot_starts_independent_close_moves",
+        "name": "snapshot_xyz_has_no_motor_effect",
         "status": "pass"
         "status": "pass"
-        if enable.accepted and subject.active_mask == 3 and subject.busy_mask == 0
+        if enable.accepted and subject.active_mask == 0 and subject.busy_mask == 0
         else "fail",
         else "fail",
     })
     })
-    subject.execute_parallel_steps((STANDARD_STEPS, STANDARD_STEPS, 0))
 
 
     before_mark = subject.state_fingerprint()
     before_mark = subject.state_fingerprint()
     mark = subject.apply_frame(GOLDEN_VECTORS["mark_x"])
     mark = subject.apply_frame(GOLDEN_VECTORS["mark_x"])
@@ -1327,45 +1210,52 @@ def run_replay() -> dict[str, object]:
     })
     })
 
 
     opened = subject.apply_frame(GOLDEN_VECTORS["open"])
     opened = subject.apply_frame(GOLDEN_VECTORS["open"])
-    open_setup_busy = subject.busy_mask
-    subject.execute_parallel_steps((1, 1, 0))
-    open_step_busy = subject.busy_mask
-    subject.execute_parallel_steps((STANDARD_STEPS - 1, STANDARD_STEPS - 1, 0))
     checks.append({
     checks.append({
-        "name": "open_xy_step_backed_busy",
+        "name": "legacy_open_fields_are_ignored",
         "status": "pass"
         "status": "pass"
         if opened.accepted
         if opened.accepted
-        and open_setup_busy == 0
-        and open_step_busy == 3
-        and all(axis.current == 100 for axis in subject.axes[:2])
+        and subject.active_mask == 0
+        and all(axis.current == UNKNOWN_POSITION for axis in subject.axes[:2])
         else "fail",
         else "fail",
     })
     })
 
 
     force_jog = encode_motion_frame(
     force_jog = encode_motion_frame(
         bytes((MOTION_JOG, 0, 1, 3, 0xFF, 0xFF, 0, 0))
         bytes((MOTION_JOG, 0, 1, 3, 0xFF, 0xFF, 0, 0))
     )
     )
-    jog = subject.apply_frame(force_jog)
-    jog_clamped = subject.axes[0].remaining_steps
-    subject.execute_axis_steps(0, FORCE_JOG_STEP_CAP)
+    jog_subject = NormalV3Model()
+    jog = jog_subject.apply_frame(force_jog)
     checks.append({
     checks.append({
-        "name": "force_jog_clamps_and_ignores_limits",
+        "name": "jog_preserves_u16_and_acks_on_first_step",
         "status": "pass"
         "status": "pass"
         if jog.accepted
         if jog.accepted
-        and jog_clamped == FORCE_JOG_STEP_CAP
-        and subject.axes[0].current == UNKNOWN_POSITION
-        and subject.active_mask == 0
+        and jog_subject.axes[0].remaining_steps == 0xFFFF
+        and jog_subject.axes[0].step_phase == "high"
+        and jog_subject.axes[0].current == UNKNOWN_POSITION
+        and jog_subject.active_mask == 1
+        and jog_subject.busy_mask == 0
+        and not jog_subject.watchdog_armed
         else "fail",
         else "fail",
     })
     })
 
 
-    closed = subject.apply_frame(GOLDEN_VECTORS["close"])
-    close_setup_busy = subject.busy_mask
-    subject.execute_parallel_steps((STANDARD_STEPS, STANDARD_STEPS, 0))
+    before_motion = (
+        jog_subject.axes[0].drive_active,
+        jog_subject.axes[0].raw_dir,
+        jog_subject.axes[0].remaining_steps,
+        jog_subject.axes[0].step_phase,
+    )
+    jog_subject.disabled = False
+    jog_subject.watchdog_armed = True
+    jog_subject.watchdog_expire()
     checks.append({
     checks.append({
-        "name": "close_xy_ignores_limits",
+        "name": "watchdog_safes_outputs_without_motor_effect",
         "status": "pass"
         "status": "pass"
-        if closed.accepted
-        and close_setup_busy == 0
-        and all(axis.current == 0 for axis in subject.axes[:2])
+        if before_motion
+        == (
+            jog_subject.axes[0].drive_active,
+            jog_subject.axes[0].raw_dir,
+            jog_subject.axes[0].remaining_steps,
+            jog_subject.axes[0].step_phase,
+        )
         else "fail",
         else "fail",
     })
     })
 
 
@@ -1376,19 +1266,20 @@ def run_replay() -> dict[str, object]:
         "status": "pass" if not unknown.accepted and unknown.status == STATUS_UNSUPPORTED and subject.state_fingerprint() == before_unknown else "fail",
         "status": "pass" if not unknown.accepted and unknown.status == STATUS_UNSUPPORTED and subject.state_fingerprint() == before_unknown else "fail",
     })
     })
 
 
-    subject.apply_frame(encode_motion_frame(bytes((MOTION_JOG, 0, 0, 0, 10, 0, 0, 0))))
-    subject.watchdog_expire()
-    final = subject.state_payload()
+    final = jog_subject.state_payload()
+    motion_status = jog_subject.motor_status_payload()
     final_ok = (
     final_ok = (
         final["ptc_percent"] == [0] * 24
         final["ptc_percent"] == [0] * 24
         and final["fan_percent"] == [30] * 4
         and final["fan_percent"] == [30] * 4
         and final["solenoid"] == 0
         and final["solenoid"] == 0
-        and final["active_mask"] == 0
+        and final["active_mask"] == 1
         and final["busy_mask"] == 0
         and final["busy_mask"] == 0
         and final["axes"][0]["current"] == UNKNOWN_POSITION
         and final["axes"][0]["current"] == UNKNOWN_POSITION
         and final["watchdog_timeout"] is True
         and final["watchdog_timeout"] is True
+        and motion_status[0] & 0x02
+        and motion_status[1:] == bytes((0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0))
     )
     )
-    checks.append({"name": "watchdog_safe_state", "status": "pass" if final_ok else "fail"})
+    checks.append({"name": "constant_motion_status", "status": "pass" if final_ok else "fail"})
     status = "pass" if all(check["status"] == "pass" for check in checks) else "fail"
     status = "pass" if all(check["status"] == "pass" for check in checks) else "fail"
     return {
     return {
         "status": status,
         "status": status,
@@ -1409,16 +1300,26 @@ def run_model() -> dict[str, object]:
     rejected = subject.apply_frame(bytes(bad))
     rejected = subject.apply_frame(bytes(bad))
     rejected_atomically = not rejected.accepted and subject.state_fingerprint() == initial
     rejected_atomically = not rejected.accepted and subject.state_fingerprint() == initial
     valid = subject.apply_frame(GOLDEN_VECTORS["open"])
     valid = subject.apply_frame(GOLDEN_VECTORS["open"])
+    jog_subject = NormalV3Model()
+    jog = jog_subject.apply_frame(GOLDEN_VECTORS["jog_x"])
     checks = {
     checks = {
         "canonical_crc": crc16_ccitt_false(b"123456789") == 0x29B1,
         "canonical_crc": crc16_ccitt_false(b"123456789") == 0x29B1,
         "initial_safe_hash": state_hash16(SAFE_PTC, SAFE_FAN, SAFE_SOLENOID) == 0xE177,
         "initial_safe_hash": state_hash16(SAFE_PTC, SAFE_FAN, SAFE_SOLENOID) == 0xE177,
         "bad_crc_rejected_atomically": rejected_atomically,
         "bad_crc_rejected_atomically": rejected_atomically,
-        "valid_snapshot_committed": valid.accepted and subject.ptc_percent == (10,) * 24,
-        "valid_axes_start_with_step_backed_busy_clear": (
+        "valid_snapshot_committed_without_motor": valid.accepted and subject.ptc_percent == (10,) * 24,
+        "snapshot_xyz_ignored": valid.status == STATUS_OK and valid.detail == 0,
+        "jog_first_step_ack": (
+            jog.accepted
+            and jog_subject.active_mask == 1
+            and jog_subject.axes[0].step_phase == "high"
+            and jog_subject.axes[0].remaining_steps == 1
+            and not jog_subject.watchdog_armed
+            and jog_subject.busy_mask == 0
+        ),
+        "status_fields_constant": (
             valid.status == STATUS_OK
             valid.status == STATUS_OK
-            and valid.detail == 0
-            and subject.active_mask == 3
-            and subject.busy_mask == 0
+            and jog_subject.motor_status_payload()[1:]
+            == bytes((0, 0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0))
         ),
         ),
     }
     }
     return {
     return {

+ 10 - 11
tools/prod2u_p4_protocol.py

@@ -25,7 +25,6 @@ HOST_ACK_PAYLOAD_LEN = 8
 OUTPUT_SNAPSHOT_PAYLOAD_LEN = 34
 OUTPUT_SNAPSHOT_PAYLOAD_LEN = 34
 MOTION_COMMAND_PAYLOAD_LEN = 8
 MOTION_COMMAND_PAYLOAD_LEN = 8
 MOTION_STATUS_PAYLOAD_LEN = 10
 MOTION_STATUS_PAYLOAD_LEN = 10
-FORCE_JOG_STEP_CAP = 800
 PTC_CHANNEL_COUNT = 24
 PTC_CHANNEL_COUNT = 24
 FAN_CHANNEL_COUNT = 4
 FAN_CHANNEL_COUNT = 4
 
 
@@ -297,7 +296,7 @@ def build_output_snapshot(
     xyz_values = tuple(xyz)
     xyz_values = tuple(xyz)
     if len(xyz_values) != 3:
     if len(xyz_values) != 3:
         raise ValueError("snapshot requires exactly 3 XYZ values")
         raise ValueError("snapshot requires exactly 3 XYZ values")
-    checked_xyz = tuple(_binary_output(value, "XYZ") for value in xyz_values)
+    checked_xyz = tuple(_u8(value, "XYZ") for value in xyz_values)
     payload = bytes((CommandId.SET_OUTPUT_SNAPSHOT, 0))
     payload = bytes((CommandId.SET_OUTPUT_SNAPSHOT, 0))
     payload += bytes(ptc + fan + (checked_solenoid,) + checked_xyz)
     payload += bytes(ptc + fan + (checked_solenoid,) + checked_xyz)
     return encode_frame(
     return encode_frame(
@@ -317,7 +316,7 @@ def decode_output_snapshot(value: P4Frame | bytes | bytearray) -> OutputSnapshot
     ptc = _percent_tuple(payload[2:26], count=PTC_CHANNEL_COUNT, label="PTC")
     ptc = _percent_tuple(payload[2:26], count=PTC_CHANNEL_COUNT, label="PTC")
     fan = _percent_tuple(payload[26:30], count=FAN_CHANNEL_COUNT, label="FAN")
     fan = _percent_tuple(payload[26:30], count=FAN_CHANNEL_COUNT, label="FAN")
     solenoid = _binary_output(payload[30], "solenoid")
     solenoid = _binary_output(payload[30], "solenoid")
-    xyz_values = tuple(_binary_output(value, "XYZ") for value in payload[31:34])
+    xyz_values = tuple(payload[31:34])
     return OutputSnapshot(
     return OutputSnapshot(
         ptc_percent=ptc,
         ptc_percent=ptc,
         fan_percent=fan,
         fan_percent=fan,
@@ -503,16 +502,16 @@ def _validate_motion_status_contract(
     target_xyz: tuple[int, int, int],
     target_xyz: tuple[int, int, int],
     fault_mask: int,
     fault_mask: int,
 ) -> None:
 ) -> None:
-    if (position_valid_mask | busy_mask | fault_mask) & 0x04:
-        raise ValueError("MOTION_STATUS Z valid, busy, and fault bits must be zero")
-    if current_xyz[2] != 0xFF or target_xyz[2] != 0xFF:
-        raise ValueError("MOTION_STATUS Z current and target must remain unknown")
-    if bool(flags & 0x01) != bool(busy_mask):
-        raise ValueError("MOTION_STATUS any_busy must equal busy_mask nonzero")
+    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:
     if flags & 0x08 and not flags & 0x04:
         raise ValueError("MOTION_STATUS watchdog_timeout requires disabled")
         raise ValueError("MOTION_STATUS watchdog_timeout requires disabled")
-    if flags & 0x04 and flags & 0x02:
-        raise ValueError("MOTION_STATUS disabled state cannot report en_active")
 
 
 
 
 def build_motion_status(
 def build_motion_status(